Skip to main content

uqa_sql/catalog/security/
object_acl.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Check, grant and revoke the ACL of an object with one grantable privilege, as `PostgreSQL`'s `aclchk.c` does for routine `EXECUTE` and type `USAGE`. An absent ACL is the default ACL: the privilege for PUBLIC and for the owner. Owners always hold grant options.
8
9use crate::ast::ObjectAclEntry;
10use crate::catalog::roles::{
11    identity::RoleSubject, role_inherits, RoleDefinition, RoleMembership, RoleMembershipKey,
12    RoleReference,
13};
14use crate::SQLError;
15use std::collections::{BTreeMap, BTreeSet};
16use uqa_core::{catalog_acl::AclGrantee, catalog_role::RoleIdentity};
17
18/// Whether a role holding `has_role` memberships may use the object, or grant it when `grant_option` is set.
19pub fn privilege_allowed(
20    owner: &RoleIdentity,
21    acl: Option<&[ObjectAclEntry]>,
22    grant_option: bool,
23    superuser: bool,
24    has_role: impl Fn(&RoleIdentity) -> bool,
25) -> bool {
26    try_privilege_allowed(owner, acl, grant_option, superuser, |role| {
27        Ok::<_, std::convert::Infallible>(has_role(role))
28    })
29    .unwrap_or_else(|impossible| match impossible {})
30}
31
32/// Observe the same ordered ACL through a fallible membership resolver, preserving its first error and short-circuiting permitted entries.
33pub fn try_privilege_allowed<E>(
34    owner: &RoleIdentity,
35    acl: Option<&[ObjectAclEntry]>,
36    grant_option: bool,
37    superuser: bool,
38    mut has_role: impl FnMut(&RoleIdentity) -> Result<bool, E>,
39) -> Result<bool, E> {
40    if superuser || (grant_option && has_role(owner)?) {
41        return Ok(true);
42    }
43    let Some(acl) = acl else {
44        return Ok(!grant_option);
45    };
46    for entry in acl {
47        if grant_option && !entry.grant_option {
48            continue;
49        }
50        match &entry.role {
51            None if !grant_option => return Ok(true),
52            Some(role) if has_role(role)? => return Ok(true),
53            _ => {}
54        }
55    }
56    Ok(false)
57}
58
59/// Roles whose grant option is reachable from the owner through grant-option entries.
60pub fn grant_option_roles(
61    owner: RoleIdentity,
62    acl: Option<&[ObjectAclEntry]>,
63) -> BTreeSet<RoleIdentity> {
64    let mut reachable = BTreeSet::from([owner]);
65    let Some(acl) = acl else {
66        return reachable;
67    };
68    loop {
69        let mut changed = false;
70        for entry in acl {
71            if let Some(role) = entry.role {
72                if entry.grant_option && reachable.contains(&entry.grantor) {
73                    changed |= reachable.insert(role);
74                }
75            }
76        }
77        if !changed {
78            return reachable;
79        }
80    }
81}
82
83/// `select_best_grantor`: the owner when the current user inherits it, then the current user's own grant option, then an inherited role's grant option. `None` means the command grants or revokes nothing and warns.
84pub fn select_grantor(
85    owner: RoleIdentity,
86    acl: Option<&[ObjectAclEntry]>,
87    current_user: &(impl RoleSubject + ?Sized),
88    roles: &BTreeMap<String, RoleDefinition>,
89    memberships: &BTreeMap<RoleMembershipKey, RoleMembership>,
90) -> Option<RoleIdentity> {
91    if role_inherits(roles, memberships, current_user, &owner) {
92        return Some(owner);
93    }
94    let grant_options = grant_option_roles(owner, acl);
95    if let Some(identity) = current_user
96        .role_definition(roles)
97        .map(RoleDefinition::identity)
98        .filter(|identity| grant_options.contains(identity))
99    {
100        return Some(identity);
101    }
102    acl.and_then(|acl| {
103        acl.iter()
104            .filter_map(|entry| entry.role)
105            .filter(|role| grant_options.contains(role))
106            .find(|role| role_inherits(roles, memberships, current_user, role))
107    })
108}
109
110fn materialize(
111    owner: RoleIdentity,
112    acl: &mut Option<Vec<ObjectAclEntry>>,
113) -> &mut Vec<ObjectAclEntry> {
114    acl.get_or_insert_with(|| {
115        vec![
116            ObjectAclEntry {
117                role: None,
118                grantor: owner,
119                grant_option: false,
120            },
121            ObjectAclEntry {
122                role: Some(owner),
123                grantor: owner,
124                grant_option: false,
125            },
126        ]
127    })
128}
129
130/// The ACL a GRANT or REVOKE stores: `ExecGrant_common` substitutes the default ACL for a missing one and always writes its result, so the default becomes explicit even when the command changes nothing.
131#[must_use]
132pub fn explicit_acl(
133    owner: RoleIdentity,
134    mut acl: Option<Vec<ObjectAclEntry>>,
135) -> Option<Vec<ObjectAclEntry>> {
136    materialize(owner, &mut acl);
137    acl
138}
139
140/// Add the privilege, merging the grant option into an existing entry from the same grantor.
141pub fn grant(
142    owner: RoleIdentity,
143    acl: &mut Option<Vec<ObjectAclEntry>>,
144    grantee: Option<RoleIdentity>,
145    grantor: RoleIdentity,
146    grant_option: bool,
147) {
148    let entries = materialize(owner, acl);
149    if let Some(entry) = entries
150        .iter_mut()
151        .find(|entry| entry.role == grantee && entry.grantor == grantor)
152    {
153        entry.grant_option |= grant_option;
154    } else {
155        entries.push(ObjectAclEntry {
156            role: grantee,
157            grantor,
158            grant_option,
159        });
160    }
161}
162
163/// Remove the privilege or only its grant option; revoking what the grantor did not grant changes nothing, and `ExecGrant_*` warns only when the grantor holds no grant option. Privileges granted through a lost grant option require CASCADE.
164pub fn revoke(
165    owner: RoleIdentity,
166    acl: &mut Option<Vec<ObjectAclEntry>>,
167    grantee: Option<RoleIdentity>,
168    grantor: RoleIdentity,
169    grant_option_only: bool,
170    cascade: bool,
171) -> Result<(), SQLError> {
172    let before = grant_option_roles(owner, acl.as_deref());
173    let entries = materialize(owner, acl);
174    let Some(position) = entries
175        .iter()
176        .position(|entry| entry.role == grantee && entry.grantor == grantor)
177    else {
178        return Ok(());
179    };
180    if grant_option_only {
181        if !entries[position].grant_option {
182            return Ok(());
183        }
184        entries[position].grant_option = false;
185    } else {
186        entries.remove(position);
187    }
188    revoke_dependents(owner, acl, &before, cascade)
189}
190
191fn revoke_dependents(
192    owner: RoleIdentity,
193    acl: &mut Option<Vec<ObjectAclEntry>>,
194    before: &BTreeSet<RoleIdentity>,
195    cascade: bool,
196) -> Result<(), SQLError> {
197    loop {
198        let current = grant_option_roles(owner, acl.as_deref());
199        let lost = before
200            .difference(&current)
201            .copied()
202            .collect::<BTreeSet<_>>();
203        let Some(entries) = acl.as_mut() else {
204            return Ok(());
205        };
206        if lost.is_empty() || !entries.iter().any(|entry| lost.contains(&entry.grantor)) {
207            return Ok(());
208        }
209        if !cascade {
210            return Err(SQLError::Diagnostic {
211                sqlstate: "2BP01".into(),
212                message: "dependent privileges exist".into(),
213                detail: None,
214                hint: Some("Use CASCADE to revoke them too.".into()),
215            });
216        }
217        entries.retain(|entry| !lost.contains(&entry.grantor));
218    }
219}
220
221/// `aclnewowner`: the new owner replaces the old one as grantee and grantor, and entries that become identical merge.
222pub fn rewrite_owner(
223    acl: &mut Option<Vec<ObjectAclEntry>>,
224    old_owner: RoleIdentity,
225    new_owner: RoleIdentity,
226) {
227    let Some(entries) = acl.as_mut() else {
228        return;
229    };
230    for entry in entries.iter_mut() {
231        if entry.role == Some(old_owner) {
232            entry.role = Some(new_owner);
233        }
234        if entry.grantor == old_owner {
235            entry.grantor = new_owner;
236        }
237    }
238    let mut merged: Vec<ObjectAclEntry> = Vec::with_capacity(entries.len());
239    for entry in std::mem::take(entries) {
240        if let Some(existing) = merged
241            .iter_mut()
242            .find(|existing| existing.role == entry.role && existing.grantor == entry.grantor)
243        {
244            existing.grant_option |= entry.grant_option;
245        } else {
246            merged.push(entry);
247        }
248    }
249    *entries = merged;
250}
251
252/// Validate the role identities and grant paths of an ACL: every endpoint names a role incarnation, PUBLIC holds no grant option, no grant path repeats, and every grantor's grant option is reachable from the owner.
253pub fn validate_acl(
254    owner: RoleIdentity,
255    acl: Option<&[ObjectAclEntry]>,
256    object_kind: &str,
257) -> Result<(), SQLError> {
258    let invalid =
259        |message: &str| SQLError::Internal(format!("invalid {object_kind} authority: {message}"));
260    if !owner.is_valid() {
261        return Err(invalid("missing owner incarnation"));
262    }
263    let reachable = grant_option_roles(owner, acl);
264    let mut paths = BTreeSet::new();
265    for entry in acl.into_iter().flatten() {
266        if !entry.grantor.is_valid() || entry.role.is_some_and(|role| !role.is_valid()) {
267            return Err(invalid("missing ACL endpoint incarnation"));
268        }
269        if entry.role.is_none() && entry.grant_option {
270            return Err(invalid("PUBLIC cannot retain a grant option"));
271        }
272        if !paths.insert((entry.role, entry.grantor)) {
273            return Err(invalid("duplicate ACL grant path"));
274        }
275        if !reachable.contains(&entry.grantor) {
276            return Err(invalid("ACL grantor has no owner-rooted grant option"));
277        }
278    }
279    Ok(())
280}
281
282/// The owner and every role named by the ACL.
283pub fn acl_roles(owner: RoleIdentity, acl: Option<&[ObjectAclEntry]>) -> BTreeSet<RoleIdentity> {
284    let mut identities = BTreeSet::from([owner]);
285    for entry in acl.into_iter().flatten() {
286        identities.extend(entry.role);
287        identities.insert(entry.grantor);
288    }
289    identities
290}
291
292/// Record the names of roles that an ACL change newly references, excluding the owners.
293pub fn added_acl_roles(
294    before: (RoleIdentity, Option<&[ObjectAclEntry]>),
295    after: (RoleIdentity, Option<&[ObjectAclEntry]>),
296    roles: &BTreeMap<String, RoleDefinition>,
297    object_kind: &str,
298    added: &mut BTreeSet<String>,
299) -> Result<(), SQLError> {
300    let mut old = acl_roles(before.0, before.1);
301    old.remove(&before.0);
302    let mut new = acl_roles(after.0, after.1);
303    new.remove(&after.0);
304    validate_acl(after.0, after.1, object_kind)?;
305    for identity in new.difference(&old) {
306        added.insert(
307            identity
308                .role_name(roles)
309                .ok_or_else(|| {
310                    SQLError::Internal(format!(
311                        "invalid {object_kind} authority: missing ACL incarnation"
312                    ))
313                })?
314                .to_owned(),
315        );
316    }
317    Ok(())
318}
319
320/// Bind grantee names to role incarnations; PUBLIC stays unbound.
321pub fn bind_grantees(
322    grantees: &[AclGrantee],
323    roles: &BTreeMap<String, RoleDefinition>,
324) -> Result<Vec<Option<RoleIdentity>>, SQLError> {
325    grantees
326        .iter()
327        .map(|grantee| {
328            grantee
329                .role_name()
330                .map(|name| {
331                    RoleReference::from(name)
332                        .bind(roles)
333                        .map(|role| role.identity())
334                })
335                .transpose()
336        })
337        .collect()
338}
339
340/// The WARNING of a GRANT or REVOKE whose current user holds no grant option, naming the object without its schema.
341pub fn acl_warning(is_grant: bool, local_name: &str) -> crate::SQLNotice {
342    super::acl_warning::acl_warning(is_grant, false, local_name)
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    fn role(value: u8) -> RoleIdentity {
350        RoleIdentity {
351            oid: i64::from(value),
352            object_id: [value; 16],
353        }
354    }
355
356    fn grant_entry(grantee: u8, grantor: u8) -> ObjectAclEntry {
357        ObjectAclEntry {
358            role: Some(role(grantee)),
359            grantor: role(grantor),
360            grant_option: true,
361        }
362    }
363
364    #[test]
365    fn grant_option_reachability_requires_an_owner_root() {
366        let disconnected_cycle = [grant_entry(2, 3), grant_entry(3, 2)];
367        assert_eq!(
368            grant_option_roles(role(1), Some(&disconnected_cycle)),
369            BTreeSet::from([role(1)])
370        );
371        let rooted_cycle = [grant_entry(2, 1), grant_entry(3, 2), grant_entry(2, 3)];
372        assert_eq!(
373            grant_option_roles(role(1), Some(&rooted_cycle)),
374            BTreeSet::from([role(1), role(2), role(3)])
375        );
376    }
377
378    #[test]
379    fn grant_option_reachability_accepts_an_independent_owner_path() {
380        let acl = [
381            grant_entry(2, 1),
382            grant_entry(3, 2),
383            grant_entry(3, 1),
384            grant_entry(4, 3),
385        ];
386        assert_eq!(
387            grant_option_roles(role(1), Some(&acl[2..])),
388            BTreeSet::from([role(1), role(3), role(4)])
389        );
390    }
391
392    #[test]
393    fn revoking_a_grant_option_with_dependent_grants_requires_cascade() {
394        let owner = role(1);
395        let mut acl = None;
396        grant(owner, &mut acl, Some(role(2)), owner, true);
397        grant(owner, &mut acl, Some(role(3)), role(2), false);
398        let error = revoke(owner, &mut acl.clone(), Some(role(2)), owner, true, false).unwrap_err();
399        assert_eq!(error.sqlstate(), Some("2BP01"));
400        assert_eq!(error.hint(), Some("Use CASCADE to revoke them too."));
401        revoke(owner, &mut acl, Some(role(2)), owner, true, true).unwrap();
402        assert_eq!(
403            acl.unwrap(),
404            [
405                ObjectAclEntry {
406                    role: None,
407                    grantor: owner,
408                    grant_option: false
409                },
410                ObjectAclEntry {
411                    role: Some(owner),
412                    grantor: owner,
413                    grant_option: false
414                },
415                ObjectAclEntry {
416                    role: Some(role(2)),
417                    grantor: owner,
418                    grant_option: false
419                },
420            ]
421        );
422    }
423}