uqa-sql 0.4.0

PostgreSQL-compatible SQL compiler built on libpg_query
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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Table and column GRANT/REVOKE validation, ACL candidates and diagnostics.
#[cfg(test)]
mod tests;
use super::{
    columns::{grant_column_acl, revoke_column_acl, select_column_acl_grantor},
    table::{
        grant_acl, revoke_acl, select_acl_grantor, validate_table_security_invariants,
        RequestedTablePrivileges, TableAclPrivilege,
    },
    BoundTableSecurity, TableSecurity,
};
use crate::catalog::roles::identity::RoleSubject;
use crate::catalog::{
    roles::{RoleDefinition, RoleMembership, RoleMembershipKey},
    stored_view::StoredView,
};
use crate::{
    ast::{GrantTableStmt, SequencePrivilege, TablePrivilege, TableRevokeBehavior},
    SQLError,
};
use std::collections::{BTreeMap, BTreeSet};
use uqa_core::catalog_acl::AclGrantee;
use uqa_core::RelationIdentity;
pub type ViewPrivilegeUpdate = (RelationIdentity, StoredView);
pub type ForeignTablePrivilegeUpdate = (RelationIdentity, BoundTableSecurity);
pub type ForeignTableGrantTarget<'a> = (
    &'a ResolvedTableGrantTarget,
    BoundTableSecurity,
    Vec<String>,
);
pub mod targets;
pub struct ResolvedTableGrantTarget {
    pub requested: String,
    pub name: String,
    pub relation: RelationIdentity,
    pub kind: &'static str,
    /// Attribute tuples selected in column order before authorization or writer waits. `None` denotes an uncoordinated analysis input.
    pub acl_columns: Option<BTreeSet<String>>,
}
impl ResolvedTableGrantTarget {
    pub fn includes_acl_tuple(&self, column: Option<&str>) -> bool {
        column.is_none_or(|column| {
            self.acl_columns
                .as_ref()
                .is_none_or(|columns| columns.contains(column))
        })
    }
}

fn apply_table_acl(
    statement: &GrantTableStmt,
    grantees: &[AclGrantee],
    privileges: &[TableAclPrivilege],
    current_user: &(impl RoleSubject + ?Sized),
    roles: &BTreeMap<String, RoleDefinition>,
    memberships: &BTreeMap<RoleMembershipKey, RoleMembership>,
    current: &TableSecurity,
) -> Result<(TableSecurity, usize), SQLError> {
    let grantors = privileges
        .iter()
        .map(|privilege| {
            (
                *privilege,
                select_acl_grantor(current, *privilege, current_user, roles, memberships),
            )
        })
        .collect::<Vec<_>>();
    let grantable = grantors
        .iter()
        .filter(|(_, grantor)| grantor.is_some())
        .count();
    let mut next = current.clone();
    for (privilege, grantor) in grantors {
        let Some(grantor) = grantor else {
            continue;
        };
        if statement.is_grant {
            grant_acl(
                &mut next,
                privilege,
                grantees,
                &grantor,
                statement.grant_option,
            );
        } else {
            revoke_acl(
                &mut next,
                privilege,
                grantees,
                &grantor,
                statement.grant_option_only,
                statement.revoke_behavior == TableRevokeBehavior::Cascade,
            )?;
        }
    }
    Ok((next, grantable))
}

fn apply_column_acl(
    application: &TableGrantApplication<'_>,
    privileges: &[(TableAclPrivilege, String)],
    authorization: &TableSecurity,
    current: &TableSecurity,
    selected: Option<&BTreeSet<String>>,
) -> Result<(TableSecurity, usize), SQLError> {
    let TableGrantApplication {
        statement,
        grantees,
        current_user,
        roles,
        memberships,
        ..
    } = application;
    let grantors = privileges
        .iter()
        .map(|(privilege, column)| {
            (
                *privilege,
                column.clone(),
                select_column_acl_grantor(
                    authorization,
                    column,
                    *privilege,
                    current_user,
                    roles,
                    memberships,
                ),
            )
        })
        .collect::<Vec<_>>();
    let grantable = grantors
        .iter()
        .filter(|(privilege, column, grantor)| {
            grantor.is_some()
                && application
                    .requested
                    .columns
                    .contains(&(*privilege, column.clone()))
        })
        .count();
    let mut next = current.clone();
    for (privilege, column, grantor) in grantors {
        if selected.is_some_and(|columns| !columns.contains(&column)) {
            continue;
        }
        let Some(grantor) = grantor else {
            continue;
        };
        if statement.is_grant {
            grant_column_acl(
                &mut next,
                &column,
                privilege,
                grantees,
                &grantor,
                statement.grant_option,
            );
        } else {
            revoke_column_acl(
                &mut next,
                &column,
                privilege,
                grantees,
                &grantor,
                statement.grant_option_only,
                statement.revoke_behavior == TableRevokeBehavior::Cascade,
            )?;
        }
    }
    next.column_acls.retain(|_, acl| !acl.is_empty());
    Ok((next, grantable))
}

pub struct TableGrantApplication<'a> {
    pub statement: &'a GrantTableStmt,
    pub grantees: &'a [AclGrantee],
    pub requested: &'a RequestedTablePrivileges,
    pub current_user: &'a dyn RoleSubject,
    pub roles: &'a BTreeMap<String, RoleDefinition>,
    pub memberships: &'a BTreeMap<RoleMembershipKey, RoleMembership>,
}

impl TableGrantApplication<'_> {
    /// `PostgreSQL` replaces relation ACL tuples for table-level commands, and nonempty requested attribute ACLs even when their bits are unchanged.
    pub fn replaced_tuples(
        &self,
        before: &TableSecurity,
        after: &TableSecurity,
    ) -> Vec<Option<String>> {
        let mut tuples = Vec::new();
        let implicit_columns = !self.statement.is_grant
            && self.requested.table.iter().any(|privilege| {
                matches!(
                    privilege,
                    TableAclPrivilege::Select
                        | TableAclPrivilege::Insert
                        | TableAclPrivilege::Update
                        | TableAclPrivilege::References
                )
            });
        if !self.requested.table.is_empty() {
            tuples.push(None);
        }
        let columns = before
            .column_acls
            .keys()
            .chain(after.column_acls.keys())
            .chain(self.requested.columns.iter().map(|(_, column)| column))
            .collect::<std::collections::BTreeSet<_>>();
        for column in columns {
            if before.column_acls.get(column) != after.column_acls.get(column)
                || ((implicit_columns
                    || self
                        .requested
                        .columns
                        .iter()
                        .any(|(_, name)| name == column))
                    && after
                        .column_acls
                        .get(column)
                        .is_some_and(|acl| !acl.is_empty()))
            {
                tuples.push(Some(column.clone()));
            }
        }
        tuples
    }

    pub fn apply(&self, current: &TableSecurity) -> Result<(TableSecurity, usize), SQLError> {
        self.apply_columns(current, None)
    }

    pub fn apply_to(
        &self,
        target: &ResolvedTableGrantTarget,
        current: &TableSecurity,
    ) -> Result<(TableSecurity, usize), SQLError> {
        self.apply_columns(current, target.acl_columns.as_ref())
    }

    /// Inspect one attribute in catalog order without revisiting earlier attribute ACLs.
    pub fn replaces_attribute(
        &self,
        current: &TableSecurity,
        column: &str,
    ) -> Result<bool, SQLError> {
        let selected = BTreeSet::from([column.to_owned()]);
        let (next, _) = self.apply_columns(current, Some(&selected))?;
        Ok(self
            .replaced_tuples(current, &next)
            .iter()
            .any(|tuple| tuple.as_deref() == Some(column)))
    }

    fn apply_columns(
        &self,
        current: &TableSecurity,
        selected: Option<&BTreeSet<String>>,
    ) -> Result<(TableSecurity, usize), SQLError> {
        let (next, table_grantable) = apply_table_acl(
            self.statement,
            self.grantees,
            &self.requested.table,
            self.current_user,
            self.roles,
            self.memberships,
            current,
        )?;
        let mut columns = self.requested.columns.clone();
        let mut implied = Vec::new();
        if !self.statement.is_grant {
            for privilege in &self.requested.table {
                if matches!(
                    privilege,
                    TableAclPrivilege::Select
                        | TableAclPrivilege::Insert
                        | TableAclPrivilege::Update
                        | TableAclPrivilege::References
                ) {
                    for column in current.column_acls.keys() {
                        let key = (*privilege, column.clone());
                        if !columns.contains(&key) {
                            columns.push(key.clone());
                        }
                        implied.push(key);
                    }
                }
            }
        }
        let (mut next, column_grantable) =
            apply_column_acl(self, &columns, current, &next, selected)?;
        // Relation grant-option loss also invalidates column grants made through that relation authority.
        for (privilege, column) in implied {
            if selected.is_some_and(|columns| !columns.contains(&column)) {
                continue;
            }
            let before = super::columns::column_grant_option_roles(current, &column, privilege);
            super::columns::revoke_dependent_column_acl(
                &mut next,
                &column,
                privilege,
                &before,
                self.statement.revoke_behavior == TableRevokeBehavior::Cascade,
            )?;
        }
        next.column_acls.retain(|_, acl| !acl.is_empty());
        Ok((next, table_grantable + column_grantable))
    }

    pub fn record_warning(
        &self,
        grantable: usize,
        relation: &RelationIdentity,
        notices: &mut Vec<(&'static str, String)>,
    ) {
        let requested = self.requested.table.len() + self.requested.columns.len();
        if grantable != requested {
            notices.push(table_acl_warning(
                self.statement.is_grant,
                grantable != 0,
                &relation.name,
            ));
        }
    }
}

pub fn validate_requested_columns(
    target: &RelationIdentity,
    columns: &[String],
    requested: &RequestedTablePrivileges,
) -> Result<(), SQLError> {
    for (_, requested_column) in &requested.columns {
        if !columns.contains(requested_column) {
            return Err(SQLError::Routine {
                sqlstate: "42703".into(),
                message: format!(
                    "column \"{requested_column}\" of relation \"{}\" does not exist",
                    target.name
                ),
            });
        }
    }
    Ok(())
}

pub fn validate_table_grant_target_kinds(
    statement: &GrantTableStmt,
    targets: &[ResolvedTableGrantTarget],
) -> Result<(), SQLError> {
    for target in targets {
        if !matches!(
            target.kind,
            "table" | "view" | "materialized view" | "foreign table" | "sequence"
        ) {
            return Err(SQLError::Unsupported(format!(
                "{} privileges for \"{}\" are not supported",
                target.kind, target.requested
            )));
        }
    }
    if let Some(column) = statement
        .privileges
        .iter()
        .flat_map(|privilege| &privilege.columns)
        .next()
    {
        if let Some(target) = targets.iter().find(|target| target.kind == "sequence") {
            return Err(SQLError::Routine {
                sqlstate: "42703".into(),
                message: format!(
                    "column \"{column}\" of relation \"{}\" does not exist",
                    target.relation.name
                ),
            });
        }
    }
    Ok(())
}

pub fn validate_table_acl_roles(
    statement: &GrantTableStmt,
    grantees: &[AclGrantee],
    requested_grantor: Option<&str>,
    current_user: &(impl RoleSubject + ?Sized),
    roles: &BTreeMap<String, RoleDefinition>,
) -> Result<(), SQLError> {
    for role in grantees {
        if role
            .role_name()
            .is_some_and(|name| !roles.contains_key(name))
        {
            return Err(SQLError::Routine {
                sqlstate: "42704".into(),
                message: format!("role \"{role}\" does not exist"),
            });
        }
    }
    if statement.is_grant && statement.grant_option && grantees.iter().any(AclGrantee::is_public) {
        return Err(SQLError::Routine {
            sqlstate: "0LP01".into(),
            message: "grant options can only be granted to roles".into(),
        });
    }
    if let Some(requested_grantor) = requested_grantor {
        if !roles.contains_key(requested_grantor) {
            return Err(SQLError::Routine {
                sqlstate: "42704".into(),
                message: format!("role \"{requested_grantor}\" does not exist"),
            });
        }
        if current_user.role_name(roles) != Some(requested_grantor) {
            return Err(SQLError::Routine {
                sqlstate: "0A000".into(),
                message: "grantor must be current user".into(),
            });
        }
    }
    Ok(())
}

pub fn table_sequence_privileges(
    privileges: &[crate::ast::TablePrivilegeSpec],
) -> (Vec<SequencePrivilege>, bool) {
    if privileges.is_empty() {
        return (
            vec![
                SequencePrivilege::Select,
                SequencePrivilege::Update,
                SequencePrivilege::Usage,
            ],
            false,
        );
    }
    let mut mapped = Vec::new();
    let mut inapplicable = false;
    for spec in privileges {
        let privilege = if spec.columns.is_empty() {
            match &spec.privilege {
                TablePrivilege::Select => Some(SequencePrivilege::Select),
                TablePrivilege::Update => Some(SequencePrivilege::Update),
                TablePrivilege::Usage => Some(SequencePrivilege::Usage),
                _ => {
                    inapplicable = true;
                    None
                }
            }
        } else {
            Some(SequencePrivilege::ColumnsUnsupported)
        };
        if let Some(privilege) = privilege {
            if !mapped.contains(&privilege) {
                mapped.push(privilege);
            }
        }
    }
    (mapped, inapplicable)
}

fn table_acl_warning(is_grant: bool, partial: bool, name: &str) -> (&'static str, String) {
    let message = match (is_grant, partial) {
        (true, true) => format!("not all privileges were granted for \"{name}\""),
        (true, false) => format!("no privileges were granted for \"{name}\""),
        (false, true) => format!("not all privileges could be revoked for \"{name}\""),
        (false, false) => format!("no privileges could be revoked for \"{name}\""),
    };
    ("WARNING", message)
}
pub fn view_privilege_updates(
    targets: Vec<(&ResolvedTableGrantTarget, StoredView)>,
    application: &TableGrantApplication<'_>,
    notices: &mut Vec<(&'static str, String)>,
    dependencies: &mut std::collections::BTreeSet<String>,
) -> Result<Vec<ViewPrivilegeUpdate>, SQLError> {
    let mut updates = Vec::new();
    for (target, mut view) in targets {
        let current = view
            .security
            .resolve(application.roles)
            .map_err(SQLError::Internal)?;
        let (next, grantable) = application.apply_to(target, &current)?;
        crate::catalog::security::dependencies::added_table_acl_roles(
            &current,
            &next,
            dependencies,
        );
        let columns = view.output_columns.as_deref().ok_or_else(|| {
            SQLError::Internal(format!(
                "loaded view `{}` has no durable public column metadata",
                target.relation.qualified_name()
            ))
        })?;
        validate_table_security_invariants(&next, Some(columns), application.roles).map_err(
            |error| {
                SQLError::Internal(format!(
                    "view `{}` produced invalid privilege metadata: {error}",
                    target.relation.qualified_name()
                ))
            },
        )?;
        application.record_warning(grantable, &target.relation, notices);
        if application
            .replaced_tuples(&current, &next)
            .iter()
            .any(|column| target.includes_acl_tuple(column.as_deref()))
        {
            view.set_security(
                BoundTableSecurity::bind(&next, application.roles).map_err(SQLError::Internal)?,
            );
            updates.push((target.relation.clone(), view));
        }
    }
    Ok(updates)
}
pub fn foreign_table_privilege_updates(
    targets: Vec<ForeignTableGrantTarget<'_>>,
    application: &TableGrantApplication<'_>,
    notices: &mut Vec<(&'static str, String)>,
    dependencies: &mut std::collections::BTreeSet<String>,
) -> Result<Vec<ForeignTablePrivilegeUpdate>, SQLError> {
    let mut updates = Vec::new();
    for (target, current, columns) in targets {
        let current = current
            .resolve(application.roles)
            .map_err(SQLError::Internal)?;
        let (next, grantable) = application.apply_to(target, &current)?;
        crate::catalog::security::dependencies::added_table_acl_roles(
            &current,
            &next,
            dependencies,
        );
        validate_table_security_invariants(&next, Some(&columns), application.roles).map_err(
            |error| {
                SQLError::Internal(format!(
                    "foreign table `{}` produced invalid privilege metadata: {error}",
                    target.relation.qualified_name()
                ))
            },
        )?;
        application.record_warning(grantable, &target.relation, notices);
        if application
            .replaced_tuples(&current, &next)
            .iter()
            .any(|column| target.includes_acl_tuple(column.as_deref()))
        {
            updates.push((
                target.relation.clone(),
                BoundTableSecurity::bind(&next, application.roles).map_err(SQLError::Internal)?,
            ));
        }
    }
    Ok(updates)
}