1use crate::catalog::roles::identity::RoleSubject;
10use std::collections::{BTreeMap, BTreeSet};
11use uqa_core::catalog_acl::AclGrantee;
12
13use crate::ast::{GrantSchemaStmt, RoleAttribute, SchemaPrivilege, SchemaRevokeBehavior};
14use crate::SQLError;
15use uqa_core::catalog_schema::{SchemaAclEntry, SchemaPrivileges};
16
17use super::SchemaSecurity;
18use crate::catalog::roles::{role_inherits, RoleDefinition, RoleMembership, RoleMembershipKey};
19
20mod production;
21pub use production::{role_has_schema_privilege_with_control, SchemaPrivilegeView};
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24pub enum SchemaAclPrivilege {
25 Usage,
26 Create,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct SchemaPrivilegeCheck {
31 pub privilege: SchemaAclPrivilege,
32 pub grant_option: bool,
33}
34
35impl SchemaAclPrivilege {
36 const fn mask(self) -> SchemaPrivileges {
37 match self {
38 Self::Usage => SchemaPrivileges {
39 usage: true,
40 create: false,
41 },
42 Self::Create => SchemaPrivileges {
43 usage: false,
44 create: true,
45 },
46 }
47 }
48}
49
50pub fn requested_acl_privileges(
51 requested: &[SchemaPrivilege],
52) -> Result<Vec<SchemaAclPrivilege>, SQLError> {
53 requested
54 .iter()
55 .map(|privilege| match privilege {
56 SchemaPrivilege::Usage => Ok(SchemaAclPrivilege::Usage),
57 SchemaPrivilege::Create => Ok(SchemaAclPrivilege::Create),
58 SchemaPrivilege::Unsupported(name) => Err(SQLError::Routine {
59 sqlstate: "0LP01".into(),
60 message: format!("invalid privilege type {name} for schema"),
61 }),
62 })
63 .collect()
64}
65
66pub fn parse_privilege_checks(value: &str) -> Result<Vec<SchemaPrivilegeCheck>, SQLError> {
67 value
68 .split(',')
69 .map(|item| {
70 let item = item.trim();
71 let upper = item.to_ascii_uppercase();
72 let (name, grant_option) = upper
73 .strip_suffix(" WITH GRANT OPTION")
74 .map_or((upper.as_str(), false), |name| (name.trim_end(), true));
75 let privilege = match name {
76 "USAGE" => SchemaAclPrivilege::Usage,
77 "CREATE" => SchemaAclPrivilege::Create,
78 _ => {
79 return Err(SQLError::Routine {
80 sqlstate: "22023".into(),
81 message: format!("unrecognized privilege type: \"{item}\""),
82 })
83 }
84 };
85 Ok(SchemaPrivilegeCheck {
86 privilege,
87 grant_option,
88 })
89 })
90 .collect()
91}
92
93fn acl_grantor<'a>(entry: &'a SchemaAclEntry, owner: &'a str) -> &'a str {
94 entry.grantor.as_deref().unwrap_or(owner)
95}
96
97fn materialize_acl(security: &mut SchemaSecurity) {
98 if security.acl.is_none() {
99 security.acl = Some(vec![SchemaAclEntry {
100 role: security.role_owner.clone().into(),
101 grantor: Some(security.role_owner.clone()),
102 privileges: SchemaPrivileges::ALL,
103 grant_options: SchemaPrivileges::default(),
104 }]);
105 }
106}
107
108fn grant_option_roles(
109 security: &SchemaSecurity,
110 privilege: SchemaAclPrivilege,
111) -> BTreeSet<String> {
112 let mut reachable = BTreeSet::from([security.role_owner.clone()]);
113 let Some(acl) = security.acl.as_ref() else {
114 return reachable;
115 };
116 loop {
117 let mut changed = false;
118 for entry in acl {
119 let Some(role) = entry.role.role_name() else {
120 continue;
121 };
122 if entry.grant_options.intersects(privilege.mask())
123 && reachable.contains(acl_grantor(entry, &security.role_owner))
124 {
125 changed |= reachable.insert(role.to_owned());
126 }
127 }
128 if !changed {
129 return reachable;
130 }
131 }
132}
133
134pub fn select_acl_grantor(
135 security: &SchemaSecurity,
136 privilege: SchemaAclPrivilege,
137 current_user: &(impl RoleSubject + ?Sized),
138 roles: &BTreeMap<String, RoleDefinition>,
139 memberships: &BTreeMap<RoleMembershipKey, RoleMembership>,
140) -> Option<String> {
141 let current_user = current_user.role_name(roles)?;
142 if role_inherits(roles, memberships, current_user, &security.role_owner) {
143 return Some(security.role_owner.clone());
144 }
145 let grant_options = grant_option_roles(security, privilege);
146 if grant_options.contains(current_user) {
147 return Some(current_user.to_string());
148 }
149 security.acl.as_ref().and_then(|acl| {
150 acl.iter()
151 .filter_map(|entry| entry.role.role_name())
152 .filter(|role| grant_options.contains(*role))
153 .find(|role| role_inherits(roles, memberships, current_user, *role))
154 .map(str::to_owned)
155 })
156}
157
158pub fn role_has_schema_privilege(
159 security: &SchemaSecurity,
160 subject: &(impl RoleSubject + ?Sized),
161 privilege: SchemaAclPrivilege,
162 roles: &BTreeMap<String, RoleDefinition>,
163 memberships: &BTreeMap<RoleMembershipKey, RoleMembership>,
164) -> bool {
165 role_has_schema_privilege_check(
166 security,
167 subject,
168 SchemaPrivilegeCheck {
169 privilege,
170 grant_option: false,
171 },
172 roles,
173 memberships,
174 )
175}
176
177pub fn role_has_schema_privilege_check(
178 security: &SchemaSecurity,
179 subject: &(impl RoleSubject + ?Sized),
180 check: SchemaPrivilegeCheck,
181 roles: &BTreeMap<String, RoleDefinition>,
182 memberships: &BTreeMap<RoleMembershipKey, RoleMembership>,
183) -> bool {
184 if subject
185 .role_definition(roles)
186 .is_some_and(|role| role.has(RoleAttribute::Superuser))
187 {
188 return true;
189 }
190 if check.grant_option {
191 return grant_option_roles(security, check.privilege)
192 .iter()
193 .any(|role| role_inherits(roles, memberships, subject, role));
194 }
195 match security.acl.as_ref() {
196 None => role_inherits(roles, memberships, subject, &security.role_owner),
197 Some(acl) => acl.iter().any(|entry| {
198 entry.privileges.intersects(check.privilege.mask())
199 && (entry.role.is_public()
200 || role_inherits(roles, memberships, subject, &entry.role))
201 }),
202 }
203}
204
205pub fn grant_acl(
206 security: &mut SchemaSecurity,
207 privilege: SchemaAclPrivilege,
208 grantees: &[AclGrantee],
209 grantor: &str,
210 grant_option: bool,
211) {
212 materialize_acl(security);
213 let owner = security.role_owner.clone();
214 let acl = security.acl.as_mut().expect("schema ACL was materialized");
215 for grantee in grantees {
216 let position = acl
217 .iter()
218 .position(|entry| entry.role == *grantee && acl_grantor(entry, &owner) == grantor)
219 .unwrap_or_else(|| {
220 acl.push(SchemaAclEntry {
221 role: grantee.clone(),
222 grantor: Some(grantor.to_string()),
223 privileges: SchemaPrivileges::default(),
224 grant_options: SchemaPrivileges::default(),
225 });
226 acl.len() - 1
227 });
228 let entry = &mut acl[position];
229 entry.privileges.insert(privilege.mask());
230 if grant_option && grantee.role_name().is_some_and(|name| name != owner) {
231 entry.grant_options.insert(privilege.mask());
232 }
233 }
234}
235
236pub fn revoke_acl(
237 security: &mut SchemaSecurity,
238 privilege: SchemaAclPrivilege,
239 grantees: &[AclGrantee],
240 grantor: &str,
241 grant_option_only: bool,
242 cascade: bool,
243) -> Result<(), SQLError> {
244 let before = grant_option_roles(security, privilege);
245 materialize_acl(security);
246 let owner = security.role_owner.clone();
247 let acl = security.acl.as_mut().expect("schema ACL was materialized");
248 for entry in acl
249 .iter_mut()
250 .filter(|entry| grantees.contains(&entry.role) && acl_grantor(entry, &owner) == grantor)
251 {
252 entry.grant_options.remove(privilege.mask());
253 if !grant_option_only {
254 entry.privileges.remove(privilege.mask());
255 }
256 }
257 remove_empty_entries(acl);
258 revoke_dependent_acl(security, privilege, &before, cascade)
259}
260
261fn revoke_dependent_acl(
262 security: &mut SchemaSecurity,
263 privilege: SchemaAclPrivilege,
264 before: &BTreeSet<String>,
265 cascade: bool,
266) -> Result<(), SQLError> {
267 loop {
268 let current = grant_option_roles(security, privilege);
269 let lost = before
270 .difference(¤t)
271 .cloned()
272 .collect::<BTreeSet<_>>();
273 if lost.is_empty() {
274 return Ok(());
275 }
276 let owner = security.role_owner.clone();
277 let dependent = security.acl.as_ref().is_some_and(|acl| {
278 acl.iter().any(|entry| {
279 lost.contains(acl_grantor(entry, &owner))
280 && (entry.privileges.intersects(privilege.mask())
281 || entry.grant_options.intersects(privilege.mask()))
282 })
283 });
284 if !dependent {
285 return Ok(());
286 }
287 if !cascade {
288 return Err(SQLError::Routine {
289 sqlstate: "2BP01".into(),
290 message: "dependent privileges exist".into(),
291 });
292 }
293 let acl = security
294 .acl
295 .as_mut()
296 .expect("dependent schema privileges require an explicit ACL");
297 for entry in acl
298 .iter_mut()
299 .filter(|entry| lost.contains(acl_grantor(entry, &owner)))
300 {
301 entry.privileges.remove(privilege.mask());
302 entry.grant_options.remove(privilege.mask());
303 }
304 remove_empty_entries(acl);
305 }
306}
307
308fn remove_empty_entries(acl: &mut Vec<SchemaAclEntry>) {
309 acl.retain(|entry| !entry.privileges.is_empty() || !entry.grant_options.is_empty());
310}
311
312pub fn schema_security_with_public_privileges(create: bool) -> SchemaSecurity {
313 let role_owner = "uqa".to_string();
314 SchemaSecurity {
315 role_owner: role_owner.clone(),
316 acl: Some(vec![
317 SchemaAclEntry {
318 role: role_owner.clone().into(),
319 grantor: Some(role_owner.clone()),
320 privileges: SchemaPrivileges::ALL,
321 grant_options: SchemaPrivileges::default(),
322 },
323 SchemaAclEntry {
324 role: AclGrantee::Public,
325 grantor: Some(role_owner),
326 privileges: SchemaPrivileges {
327 usage: true,
328 create,
329 },
330 grant_options: SchemaPrivileges::default(),
331 },
332 ]),
333 }
334}
335
336pub fn rewrite_schema_acl_owner(security: &mut SchemaSecurity, new_owner: &str) {
337 if let Some(acl) = &mut security.acl {
338 for entry in acl.iter_mut() {
339 if entry.role.role_name() == Some(security.role_owner.as_str()) {
340 entry.role = new_owner.into();
341 }
342 if entry.grantor.as_deref().unwrap_or(&security.role_owner) == security.role_owner {
343 entry.grantor = Some(new_owner.to_string());
344 }
345 }
346 let mut merged: Vec<SchemaAclEntry> = Vec::new();
347 for entry in std::mem::take(acl) {
348 if let Some(previous) = merged
349 .iter_mut()
350 .find(|previous| previous.role == entry.role && previous.grantor == entry.grantor)
351 {
352 previous.privileges.insert(entry.privileges);
353 previous.grant_options.insert(entry.grant_options);
354 } else {
355 merged.push(entry);
356 }
357 }
358 *acl = merged;
359 }
360 security.role_owner = new_owner.to_string();
361}
362
363pub fn apply_schema_acl(
364 statement: &GrantSchemaStmt,
365 grantees: &[AclGrantee],
366 privileges: &[SchemaAclPrivilege],
367 current_user: &(impl RoleSubject + ?Sized),
368 roles: &BTreeMap<String, RoleDefinition>,
369 memberships: &BTreeMap<RoleMembershipKey, RoleMembership>,
370 current: &SchemaSecurity,
371) -> Result<(SchemaSecurity, usize), SQLError> {
372 let grantors = privileges
373 .iter()
374 .map(|privilege| {
375 (
376 *privilege,
377 select_acl_grantor(current, *privilege, current_user, roles, memberships),
378 )
379 })
380 .collect::<Vec<_>>();
381 let grantable = grantors
382 .iter()
383 .filter(|(_, grantor)| grantor.is_some())
384 .count();
385 let mut next = current.clone();
386 for (privilege, grantor) in grantors {
387 let Some(grantor) = grantor else {
388 continue;
389 };
390 if statement.is_grant {
391 grant_acl(
392 &mut next,
393 privilege,
394 grantees,
395 &grantor,
396 statement.grant_option,
397 );
398 } else {
399 revoke_acl(
400 &mut next,
401 privilege,
402 grantees,
403 &grantor,
404 statement.grant_option_only,
405 statement.revoke_behavior == SchemaRevokeBehavior::Cascade,
406 )?;
407 }
408 }
409 Ok((next, grantable))
410}
411
412pub fn validate_schema_acl_roles(
413 statement: &GrantSchemaStmt,
414 grantees: &[AclGrantee],
415 requested_grantor: Option<&str>,
416 current_user: &(impl RoleSubject + ?Sized),
417 roles: &BTreeMap<String, RoleDefinition>,
418) -> Result<(), SQLError> {
419 for role in grantees {
420 if role
421 .role_name()
422 .is_some_and(|name| !roles.contains_key(name))
423 {
424 return Err(SQLError::Routine {
425 sqlstate: "42704".into(),
426 message: format!("role \"{role}\" does not exist"),
427 });
428 }
429 }
430 if statement.is_grant && statement.grant_option && grantees.iter().any(AclGrantee::is_public) {
431 return Err(SQLError::Routine {
432 sqlstate: "0LP01".into(),
433 message: "grant options can only be granted to roles".into(),
434 });
435 }
436 if let Some(requested_grantor) = requested_grantor {
437 if !roles.contains_key(requested_grantor) {
438 return Err(SQLError::Routine {
439 sqlstate: "42704".into(),
440 message: format!("role \"{requested_grantor}\" does not exist"),
441 });
442 }
443 if current_user.role_name(roles) != Some(requested_grantor) {
444 return Err(SQLError::Routine {
445 sqlstate: "0A000".into(),
446 message: "grantor must be current user".into(),
447 });
448 }
449 }
450 Ok(())
451}
452
453pub fn resolve_schema_grant_targets(
454 registry: &BTreeMap<String, super::BoundSchemaSecurity>,
455 schemas: &[String],
456) -> Result<Vec<String>, SQLError> {
457 let mut targets = Vec::with_capacity(schemas.len());
458 for schema in schemas {
459 if !registry.contains_key(schema) {
460 return Err(SQLError::Routine {
461 sqlstate: "3F000".into(),
462 message: format!("schema \"{schema}\" does not exist"),
463 });
464 }
465 if !targets.contains(schema) {
466 targets.push(schema.clone());
467 }
468 }
469 Ok(targets)
470}