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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use super::*;
use crate::ast::{Statement, TablePrivilegeSpec};
use crate::catalog::{
    resolution::RelationResolution,
    security::{
        columns::role_has_column_privilege,
        grants::{bind_grant_schemas, GrantNamespace},
        table::{requested_acl_privileges, role_has_privilege, TablePrivilegeCheck},
    },
};
use std::cell::RefCell;

fn statement(sql: &str) -> GrantTableStmt {
    let Statement::GrantTable(statement) = crate::compile(sql).unwrap().remove(0) else {
        panic!("expected table grant")
    };
    statement
}
fn roles() -> BTreeMap<String, RoleDefinition> {
    let mut roles = BTreeMap::from([("uqa".into(), RoleDefinition::bootstrap())]);
    for (index, name) in ["alice", "reader", "independent"].into_iter().enumerate() {
        let Statement::CreateRole(role) = crate::compile(&format!("CREATE ROLE {name}"))
            .unwrap()
            .remove(0)
        else {
            panic!("expected role")
        };
        roles.insert(
            name.into(),
            RoleDefinition::from_create(&role, 20_001 + index as i64, [index as u8 + 1; 16]),
        );
    }
    roles
}
type AppliedGrant = (TableSecurity, usize, Vec<(&'static str, String)>);

struct SessionRole<'a>(&'a str);

impl crate::catalog::roles::RoleReferenceNames for SessionRole<'_> {
    fn outer_role(&self) -> crate::catalog::roles::RoleReference {
        self.current_role()
    }
    fn current_role(&self) -> crate::catalog::roles::RoleReference {
        self.0.into()
    }

    fn session_role(&self) -> crate::catalog::roles::RoleReference {
        self.current_role()
    }
}

fn apply(
    sql: &str,
    user: &str,
    roles: &BTreeMap<String, RoleDefinition>,
    current: &TableSecurity,
) -> Result<AppliedGrant, SQLError> {
    let statement = statement(sql);
    let grantees = statement
        .grantees
        .iter()
        .map(|role| {
            crate::catalog::roles::resolve_acl_role_specification(&SessionRole(user), role, roles)
        })
        .collect::<Result<Vec<_>, _>>()?;
    let requested = requested_acl_privileges(&statement.privileges)?;
    let memberships = BTreeMap::new();
    let application = TableGrantApplication {
        statement: &statement,
        grantees: &grantees,
        requested: &requested,
        current_user: &user,
        roles,
        memberships: &memberships,
    };
    let (next, grantable) = application.apply(current)?;
    let mut notices = Vec::new();
    application.record_warning(
        grantable,
        &RelationIdentity::new("public", "items"),
        &mut notices,
    );
    Ok((next, grantable, notices))
}
fn column_allowed(
    security: &TableSecurity,
    column: &str,
    role: &str,
    roles: &BTreeMap<String, RoleDefinition>,
) -> bool {
    role_has_column_privilege(
        security,
        column,
        role,
        TablePrivilegeCheck {
            privilege: TableAclPrivilege::Update,
            grant_option: false,
        },
        roles,
        &BTreeMap::new(),
    )
}
fn target(kind: &'static str) -> ResolvedTableGrantTarget {
    ResolvedTableGrantTarget {
        acl_columns: None,
        requested: "items".into(),
        name: "public.items".into(),
        relation: RelationIdentity::new("public", "items"),
        kind,
    }
}

#[test]
fn table_and_column_grants_preserve_input_security_and_grant_options() {
    let roles = roles();
    let current = TableSecurity::owner("uqa");
    let (next, count, notices) = apply(
        "GRANT SELECT, UPDATE(id) ON TABLE items TO reader WITH GRANT OPTION",
        "uqa",
        &roles,
        &current,
    )
    .unwrap();
    assert_eq!(count, 2);
    assert!(notices.is_empty());
    assert_eq!(current, TableSecurity::owner("uqa"));
    assert!(role_has_privilege(
        &next,
        "reader",
        TablePrivilegeCheck {
            privilege: TableAclPrivilege::Select,
            grant_option: true
        },
        &roles,
        &BTreeMap::new()
    ));
    assert!(role_has_column_privilege(
        &next,
        "id",
        "reader",
        TablePrivilegeCheck {
            privilege: TableAclPrivilege::Update,
            grant_option: true
        },
        &roles,
        &BTreeMap::new()
    ));
    assert!(!column_allowed(&next, "other", "reader", &roles));
}

#[test]
fn column_revoke_restrict_preserves_input_and_cascade_keeps_independent_grant_paths() {
    let roles = roles();
    let security = TableSecurity::owner("uqa");
    let (security, _, _) = apply(
        "GRANT UPDATE(id) ON items TO alice WITH GRANT OPTION",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    let (security, _, _) = apply(
        "GRANT UPDATE(id) ON items TO reader",
        "alice",
        &roles,
        &security,
    )
    .unwrap();
    let (security, _, _) = apply(
        "GRANT UPDATE(id) ON items TO independent",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    let before = security.clone();
    assert_eq!(
        apply(
            "REVOKE UPDATE(id) ON items FROM alice RESTRICT",
            "uqa",
            &roles,
            &security
        )
        .unwrap_err()
        .sqlstate(),
        Some("2BP01")
    );
    assert_eq!(security, before);
    let (next, _, _) = apply(
        "REVOKE UPDATE(id) ON items FROM alice CASCADE",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    assert!(!column_allowed(&next, "id", "alice", &roles));
    assert!(!column_allowed(&next, "id", "reader", &roles));
    assert!(column_allowed(&next, "id", "independent", &roles));
}

#[test]
fn partial_grant_publishes_only_authorized_privileges_and_reports_a_warning() {
    let roles = roles();
    let (current, _, _) = apply(
        "GRANT SELECT ON items TO alice WITH GRANT OPTION",
        "uqa",
        &roles,
        &TableSecurity::owner("uqa"),
    )
    .unwrap();
    let (next, count, notices) = apply(
        "GRANT SELECT, UPDATE ON items TO reader",
        "alice",
        &roles,
        &current,
    )
    .unwrap();
    assert_eq!(count, 1);
    assert_eq!(
        notices,
        vec![(
            "WARNING",
            "not all privileges were granted for \"items\"".into()
        )]
    );
    assert!(role_has_privilege(
        &next,
        "reader",
        TablePrivilegeCheck {
            privilege: TableAclPrivilege::Select,
            grant_option: false
        },
        &roles,
        &BTreeMap::new()
    ));
    assert!(!column_allowed(&next, "id", "reader", &roles));
}

#[test]
fn absent_grant_authority_preserves_security_and_distinguishes_grant_and_revoke_warnings() {
    let roles = roles();
    let current = TableSecurity::owner("uqa");
    for (sql, message) in [
        (
            "GRANT SELECT ON items TO reader",
            "no privileges were granted for \"items\"",
        ),
        (
            "REVOKE SELECT ON items FROM reader",
            "no privileges could be revoked for \"items\"",
        ),
    ] {
        let (next, count, notices) = apply(sql, "alice", &roles, &current).unwrap();
        assert_eq!(next, current);
        assert_eq!(count, 0);
        assert_eq!(notices, vec![("WARNING", message.into())]);
    }
}

#[test]
fn role_errors_precede_public_grant_options_and_explicit_grantor_validation() {
    let roles = roles();
    let mut grant = statement("GRANT SELECT ON items TO PUBLIC WITH GRANT OPTION");
    assert_eq!(
        validate_table_acl_roles(
            &grant,
            &["absent".into(), uqa_core::catalog_acl::AclGrantee::Public],
            Some("absent"),
            "uqa",
            &roles
        )
        .unwrap_err()
        .sqlstate(),
        Some("42704")
    );
    assert_eq!(
        validate_table_acl_roles(
            &grant,
            &[uqa_core::catalog_acl::AclGrantee::Public],
            Some("absent"),
            "uqa",
            &roles
        )
        .unwrap_err()
        .sqlstate(),
        Some("0LP01")
    );
    grant.grant_option = false;
    assert_eq!(
        validate_table_acl_roles(&grant, &["reader".into()], Some("absent"), "uqa", &roles)
            .unwrap_err()
            .sqlstate(),
        Some("42704")
    );
    assert_eq!(
        validate_table_acl_roles(&grant, &["reader".into()], Some("alice"), "uqa", &roles)
            .unwrap_err()
            .sqlstate(),
        Some("0A000")
    );
    validate_table_acl_roles(
        &grant,
        &[uqa_core::catalog_acl::AclGrantee::Public],
        Some("uqa"),
        "uqa",
        &roles,
    )
    .unwrap();
}

#[test]
fn sequence_targets_reject_column_privileges_before_acl_application() {
    let grant = statement("GRANT SELECT(id) ON items TO reader");
    let error = validate_table_grant_target_kinds(&grant, &[target("table"), target("sequence")])
        .unwrap_err();
    assert_eq!(error.sqlstate(), Some("42703"));
    assert!(error
        .to_string()
        .contains("column \"id\" of relation \"items\" does not exist"));
    validate_table_grant_target_kinds(
        &statement("GRANT SELECT ON items TO reader"),
        &[target("foreign table")],
    )
    .unwrap();
}

#[test]
fn table_syntax_sequence_privileges_keep_input_order_and_mark_inapplicable_permissions() {
    assert_eq!(
        table_sequence_privileges(&[]),
        (
            vec![
                SequencePrivilege::Select,
                SequencePrivilege::Update,
                SequencePrivilege::Usage
            ],
            false
        )
    );
    let specs = vec![
        TablePrivilegeSpec {
            privilege: TablePrivilege::Update,
            columns: Vec::new(),
        },
        TablePrivilegeSpec {
            privilege: TablePrivilege::Insert,
            columns: Vec::new(),
        },
        TablePrivilegeSpec {
            privilege: TablePrivilege::Select,
            columns: Vec::new(),
        },
        TablePrivilegeSpec {
            privilege: TablePrivilege::Update,
            columns: Vec::new(),
        },
    ];
    assert_eq!(
        table_sequence_privileges(&specs),
        (
            vec![SequencePrivilege::Update, SequencePrivilege::Select],
            true
        )
    );
}

struct Resolution {
    outcome: RelationResolution,
    calls: RefCell<Vec<String>>,
}
impl targets::TableGrantResolution for Resolution {
    fn resolve_visible_relation_kind(&self, name: &str) -> Result<RelationResolution, SQLError> {
        self.calls.borrow_mut().push(name.into());
        Ok(if name == "present" {
            RelationResolution::Found("public.present".into(), "table")
        } else {
            self.outcome.clone()
        })
    }
}

#[test]
fn named_targets_stop_at_the_first_missing_schema_or_relation() {
    for (outcome, state) in [
        (RelationResolution::MissingSchema("absent".into()), "3F000"),
        (RelationResolution::MissingRelation, "42P01"),
    ] {
        let resolution = Resolution {
            outcome,
            calls: RefCell::new(Vec::new()),
        };
        let error = targets::bind_named_table_grants(
            &resolution,
            &["present".into(), "missing".into(), "never".into()],
        )
        .err()
        .unwrap();
        assert_eq!(error.sqlstate(), Some(state));
        assert_eq!(*resolution.calls.borrow(), vec!["present", "missing"]);
    }
}

struct Namespace {
    allocated: bool,
}
impl GrantNamespace for Namespace {
    fn temporary_schema_name(&self) -> String {
        "pg_temp_42".into()
    }
    fn temporary_namespace_allocated(&self) -> bool {
        self.allocated
    }
    fn has_namespace(&self, name: &str) -> Result<bool, String> {
        Ok(name == "public")
    }
}

#[test]
fn schema_grants_share_temporary_alias_binding_and_preserve_first_occurrence_order() {
    assert_eq!(
        bind_grant_schemas(
            &Namespace { allocated: true },
            &[
                "public".into(),
                "pg_temp".into(),
                "public".into(),
                "pg_temp_42".into()
            ]
        )
        .unwrap(),
        vec!["public", "pg_temp_42"]
    );
    let error =
        bind_grant_schemas(&Namespace { allocated: false }, &["pg_temp".into()]).unwrap_err();
    assert_eq!(error.sqlstate(), Some("3F000"));
    assert!(error
        .to_string()
        .contains("schema \"pg_temp\" does not exist"));
}

#[test]
fn foreign_acl_candidates_validate_columns_without_mutating_the_source_security() {
    let roles = roles();
    let statement = statement("GRANT UPDATE(id) ON items TO reader");
    let requested = requested_acl_privileges(&statement.privileges).unwrap();
    let memberships = BTreeMap::new();
    let application = TableGrantApplication {
        statement: &statement,
        grantees: &["reader".into()],
        requested: &requested,
        current_user: &"uqa",
        roles: &roles,
        memberships: &memberships,
    };
    let target = target("foreign table");
    let security = TableSecurity::owner("uqa");
    let updates = foreign_table_privilege_updates(
        vec![(
            &target,
            BoundTableSecurity::bind(&security, &roles).unwrap(),
            vec!["id".into()],
        )],
        &application,
        &mut Vec::new(),
        &mut std::collections::BTreeSet::new(),
    )
    .unwrap();
    assert_eq!(updates.len(), 1);
    assert!(column_allowed(
        &updates[0].1.resolve(&roles).unwrap(),
        "id",
        "reader",
        &roles
    ));
    assert_eq!(security, TableSecurity::owner("uqa"));
    assert!(foreign_table_privilege_updates(
        vec![(
            &target,
            BoundTableSecurity::bind(&security, &roles).unwrap(),
            vec!["different".into()]
        )],
        &application,
        &mut Vec::new(),
        &mut std::collections::BTreeSet::new()
    )
    .is_err());
}

#[test]
fn table_revoke_removes_implied_column_grants_and_checks_their_dependent_paths() {
    let roles = roles();
    let security = TableSecurity::owner("uqa");
    let (security, _, _) = apply(
        "GRANT SELECT(title) ON items TO alice WITH GRANT OPTION",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    let (security, _, _) = apply(
        "GRANT SELECT(title) ON items TO reader",
        "alice",
        &roles,
        &security,
    )
    .unwrap();
    let error = apply(
        "REVOKE SELECT ON items FROM alice RESTRICT",
        "uqa",
        &roles,
        &security,
    )
    .unwrap_err();
    assert_eq!(error.sqlstate(), Some("2BP01"));
    let (revoked, granted, notices) = apply(
        "REVOKE SELECT ON items FROM alice CASCADE",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    assert_eq!(granted, 1);
    assert!(notices.is_empty());
    assert!(revoked.column_acls.is_empty());
}

#[test]
fn table_grant_option_revoke_tracks_column_grants_authorized_by_the_table_acl() {
    let roles = roles();
    let security = TableSecurity::owner("uqa");
    let (security, _, _) = apply(
        "GRANT SELECT ON items TO alice WITH GRANT OPTION",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    let (security, _, _) = apply(
        "GRANT SELECT(title) ON items TO reader",
        "alice",
        &roles,
        &security,
    )
    .unwrap();
    assert_eq!(
        apply(
            "REVOKE GRANT OPTION FOR SELECT ON items FROM alice RESTRICT",
            "uqa",
            &roles,
            &security
        )
        .unwrap_err()
        .sqlstate(),
        Some("2BP01")
    );
    let (security, _, _) = apply(
        "REVOKE GRANT OPTION FOR SELECT ON items FROM alice CASCADE",
        "uqa",
        &roles,
        &security,
    )
    .unwrap();
    assert!(security.column_acls.is_empty());
    assert!(role_has_privilege(
        &security,
        "alice",
        TablePrivilegeCheck {
            privilege: TableAclPrivilege::Select,
            grant_option: false
        },
        &roles,
        &BTreeMap::new()
    ));
}

#[test]
fn selected_attribute_candidates_preserve_new_grants_on_previously_skipped_columns() {
    let roles = roles();
    let (current, _, _) = apply(
        "GRANT UPDATE(a, b) ON items TO reader",
        "uqa",
        &roles,
        &TableSecurity::owner("uqa"),
    )
    .unwrap();
    let statement = statement("REVOKE UPDATE ON items FROM reader");
    let requested = requested_acl_privileges(&statement.privileges).unwrap();
    let application = TableGrantApplication {
        statement: &statement,
        grantees: &["reader".into()],
        requested: &requested,
        current_user: &"uqa",
        roles: &roles,
        memberships: &BTreeMap::new(),
    };
    let mut target = target("table");
    target.acl_columns = Some(BTreeSet::from(["b".into()]));
    let (next, count) = application.apply_to(&target, &current).unwrap();
    assert_eq!(count, 1);
    assert!(column_allowed(&next, "a", "reader", &roles));
    assert!(!column_allowed(&next, "b", "reader", &roles));
    assert!(!target.includes_acl_tuple(Some("a")));
    assert!(target.includes_acl_tuple(Some("b")));
    assert!(target.includes_acl_tuple(None));
}