Skip to main content

uqa_sql/catalog/security/
table_binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Table and column ACLs retain role incarnations independently of display names.
8
9use super::{role_bindings, TableAclEntry, TablePrivileges, TableSecurity};
10use crate::catalog::roles::{RoleDefinition, RoleIdentity, RoleReference};
11use std::collections::BTreeMap;
12use uqa_core::catalog_acl::AclGrantee;
13use uqa_core::catalog_role::BoundAclEntry;
14
15mod production;
16pub use production::CapturedTablePrivileges;
17
18pub type BoundTableAclEntry = BoundAclEntry<TablePrivileges>;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct BoundTableSecurity {
22    pub role_owner: RoleIdentity,
23    pub acl: Option<Vec<BoundTableAclEntry>>,
24    pub column_acls: BTreeMap<String, Vec<BoundTableAclEntry>>,
25    pub acl_revisions: uqa_core::catalog_acl::RelationAclRevisions,
26}
27
28impl BoundTableSecurity {
29    pub fn remove_column_acl(&mut self, column: &str) {
30        self.column_acls.remove(column);
31        self.acl_revisions.columns.remove(column);
32    }
33
34    pub fn rename_column_acl(&mut self, from: &str, to: &str) {
35        if let Some(acl) = self.column_acls.remove(from) {
36            self.column_acls.insert(to.to_owned(), acl);
37        }
38        if let Some(revision) = self.acl_revisions.columns.remove(from) {
39            self.acl_revisions.columns.insert(to.to_owned(), revision);
40        }
41    }
42
43    pub fn from_row(row: uqa_core::catalog_acl::BoundRelationSecurity) -> Self {
44        Self {
45            role_owner: row.role_owner,
46            acl: row.acl,
47            column_acls: row.column_acls,
48            acl_revisions: row.acl_revisions,
49        }
50    }
51
52    pub fn row(&self) -> uqa_core::catalog_acl::BoundRelationSecurity {
53        uqa_core::catalog_acl::BoundRelationSecurity {
54            role_owner: self.role_owner,
55            acl: self.acl.clone(),
56            column_acls: self.column_acls.clone(),
57            acl_revisions: self.acl_revisions.clone(),
58        }
59    }
60
61    pub fn owner(role_owner: RoleIdentity) -> Self {
62        Self {
63            role_owner,
64            acl: None,
65            column_acls: BTreeMap::new(),
66            acl_revisions: uqa_core::catalog_acl::RelationAclRevisions::default(),
67        }
68    }
69
70    pub fn owner_reference(
71        &self,
72        roles: &BTreeMap<String, RoleDefinition>,
73    ) -> Result<RoleReference, crate::SQLError> {
74        owner_reference_with_control(
75            self.role_owner,
76            roles,
77            &uqa_core::memory::ProductionControl::uncontrolled(),
78        )
79    }
80
81    pub fn bind(
82        security: &TableSecurity,
83        roles: &BTreeMap<String, RoleDefinition>,
84    ) -> Result<Self, String> {
85        let bind = |name: &str| role_bindings::bind_role(roles, name, "table");
86        let entries = |entries: &[TableAclEntry]| {
87            entries
88                .iter()
89                .map(|entry| {
90                    Ok(BoundTableAclEntry {
91                        role: entry.role.role_name().map(bind).transpose()?,
92                        grantor: bind(entry.grantor.as_deref().unwrap_or(&security.role_owner))?,
93                        privileges: entry.privileges,
94                        grant_options: entry.grant_options,
95                    })
96                })
97                .collect::<Result<Vec<_>, String>>()
98        };
99        Ok(Self {
100            role_owner: bind(&security.role_owner)?,
101            acl_revisions: uqa_core::catalog_acl::RelationAclRevisions::default(),
102            acl: security.acl.as_deref().map(entries).transpose()?,
103            column_acls: security
104                .column_acls
105                .iter()
106                .map(|(column, acl)| Ok((column.clone(), entries(acl)?)))
107                .collect::<Result<_, String>>()?,
108        })
109    }
110
111    /// Resolve names only from the role view accompanying this security snapshot.
112    pub fn resolve(
113        &self,
114        roles: &BTreeMap<String, RoleDefinition>,
115    ) -> Result<TableSecurity, String> {
116        resolve_privileges(
117            self.role_owner,
118            self.acl.as_deref(),
119            self.column_acls.iter(),
120            roles,
121        )
122    }
123
124    pub fn validate(
125        &self,
126        columns: Option<&[String]>,
127        roles: &BTreeMap<String, RoleDefinition>,
128    ) -> Result<(), String> {
129        if self.acl_revisions.relation == Some([0; 16])
130            || self.acl_revisions.columns.iter().any(|(column, revision)| {
131                *revision == [0; 16] || columns.is_some_and(|columns| !columns.contains(column))
132            })
133        {
134            return Err("invalid relation or attribute ACL tuple identity".into());
135        }
136        super::table::validate_table_security_invariants(&self.resolve(roles)?, columns, roles)
137    }
138
139    pub fn depends_on(&self, role: RoleIdentity) -> bool {
140        self.role_owner == role
141            || self
142                .acl
143                .iter()
144                .flatten()
145                .chain(self.column_acls.values().flatten())
146                .any(|entry| entry.role == Some(role) || entry.grantor == role)
147    }
148}
149
150#[cfg(test)]
151mod tests;
152
153/// Resolve a captured owner incarnation against the selected catalog, retaining its admitted name.
154pub fn owner_reference_with_control(
155    owner: RoleIdentity,
156    roles: &BTreeMap<String, RoleDefinition>,
157    control: &uqa_core::memory::ProductionControl<'_>,
158) -> Result<RoleReference, crate::SQLError> {
159    let role = role_bindings::role_definition_with_control(roles, owner, "table", control)?;
160    RoleReference::from_definition_with_control(role, control)
161}
162
163fn resolve_privileges<'a>(
164    owner: RoleIdentity,
165    acl: Option<&[BoundTableAclEntry]>,
166    columns: impl Iterator<Item = (&'a String, &'a Vec<BoundTableAclEntry>)>,
167    roles: &BTreeMap<String, RoleDefinition>,
168) -> Result<TableSecurity, String> {
169    let name = |identity| role_bindings::role_name(roles, identity, "table").map(str::to_owned);
170    let entries = |entries: &[BoundTableAclEntry]| {
171        entries
172            .iter()
173            .map(|entry| {
174                Ok(TableAclEntry {
175                    role: entry
176                        .role
177                        .map(name)
178                        .transpose()?
179                        .map_or(AclGrantee::Public, AclGrantee::Role),
180                    grantor: Some(name(entry.grantor)?),
181                    privileges: entry.privileges,
182                    grant_options: entry.grant_options,
183                })
184            })
185            .collect::<Result<Vec<_>, String>>()
186    };
187    Ok(TableSecurity {
188        role_owner: name(owner)?,
189        acl: acl.map(entries).transpose()?,
190        column_acls: columns
191            .map(|(column, acl)| Ok((column.clone(), entries(acl)?)))
192            .collect::<Result<_, String>>()?,
193    })
194}