Skip to main content

mz_sql/
rbac.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::{BTreeMap, BTreeSet, VecDeque};
11use std::iter;
12use std::sync::LazyLock;
13
14use itertools::Itertools;
15use maplit::btreeset;
16use mz_controller_types::ClusterId;
17use mz_expr::CollectionPlan;
18use mz_ore::str::StrExt;
19use mz_repr::CatalogItemId;
20use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
21use mz_repr::role_id::RoleId;
22use mz_sql_parser::ast::{Ident, QualifiedReplica};
23use tracing::debug;
24
25use crate::catalog::{
26    CatalogItemType, ErrorMessageObjectDescription, ObjectType, SessionCatalog, SystemObjectType,
27};
28use crate::names::{
29    CommentObjectId, ObjectId, QualifiedItemName, ResolvedDatabaseSpecifier, ResolvedIds,
30    SchemaSpecifier, SystemObjectId,
31};
32use crate::plan::{self, PlanKind};
33use crate::plan::{
34    DataSourceDesc, Explainee, MutationKind, Plan, SideEffectingFunc, TableDataSource,
35    UpdatePrivilege,
36};
37use crate::pure::StatementSource;
38use crate::session::metadata::SessionMetadata;
39use crate::session::user::{MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID, SUPPORT_USER, SYSTEM_USER};
40use crate::session::vars::SystemVars;
41
42/// Checks that the session's current, session, and authenticated roles still exist.
43pub fn check_session_roles(
44    catalog: &impl SessionCatalog,
45    session_meta: &dyn SessionMetadata,
46) -> Result<(), UnauthorizedError> {
47    // PostgreSQL allows users that have their role dropped to perform some actions,
48    // such as `SET ROLE` and certain `SELECT` queries. We haven't implemented
49    // `SET ROLE` and feel it's safer to force to user to re-authenticate if their
50    // role is dropped.
51    if catalog
52        .try_get_role(&session_meta.role_metadata().current_role)
53        .is_none()
54    {
55        return Err(UnauthorizedError::ConcurrentRoleDrop(
56            session_meta.role_metadata().current_role.clone(),
57        ));
58    };
59    if catalog
60        .try_get_role(&session_meta.role_metadata().session_role)
61        .is_none()
62    {
63        return Err(UnauthorizedError::ConcurrentRoleDrop(
64            session_meta.role_metadata().session_role.clone(),
65        ));
66    };
67    if catalog
68        .try_get_role(&session_meta.role_metadata().authenticated_role)
69        .is_none()
70    {
71        return Err(UnauthorizedError::ConcurrentRoleDrop(
72            session_meta.role_metadata().authenticated_role.clone(),
73        ));
74    };
75
76    Ok(())
77}
78
79/// Filters `RbacRequirements` based on the session role metadata and RBAC related feature flags.
80fn filter_requirements(
81    catalog: &impl SessionCatalog,
82    session_meta: &dyn SessionMetadata,
83    rbac_requirements: RbacRequirements,
84) -> RbacRequirements {
85    // Skip RBAC non-mandatory checks if RBAC is disabled. However, we never skip RBAC checks for
86    // system roles. This allows us to limit access of system users even when RBAC is off.
87    let is_rbac_disabled = !is_rbac_enabled_for_session(catalog.system_vars(), session_meta)
88        && !session_meta.role_metadata().current_role.is_system()
89        && !session_meta.role_metadata().session_role.is_system();
90    // Skip RBAC checks on user items if the session is a superuser.
91    let is_superuser = session_meta.is_superuser();
92    if is_rbac_disabled || is_superuser {
93        return rbac_requirements.filter_to_mandatory_requirements();
94    }
95
96    rbac_requirements
97}
98
99// The default item types that most statements require USAGE privileges for.
100static DEFAULT_ITEM_USAGE: LazyLock<BTreeSet<CatalogItemType>> = LazyLock::new(|| {
101    btreeset! {CatalogItemType::Secret, CatalogItemType::Connection}
102});
103// CREATE statements require USAGE privileges on the default item types and USAGE privileges on
104// Types.
105pub static CREATE_ITEM_USAGE: LazyLock<BTreeSet<CatalogItemType>> = LazyLock::new(|| {
106    let mut items = DEFAULT_ITEM_USAGE.clone();
107    items.insert(CatalogItemType::Type);
108    items
109});
110pub static EMPTY_ITEM_USAGE: LazyLock<BTreeSet<CatalogItemType>> = LazyLock::new(BTreeSet::new);
111
112/// System catalog objects exempted from `check_restrict_to_user_objects`.
113///
114/// The `mz_mcp_data_product*` views are how the MCP agent endpoint
115/// discovers data products; blocking them defeats the isolation model.
116/// `mz_show_my_cluster_privileges` is referenced by those views to null the
117/// advertised cluster unless the role has USAGE on it (it uses
118/// `mz_session_role_memberships()` rather than a `has_cluster_privilege`
119/// body that referenced `mz_roles`), and is itself useful for a restricted
120/// session to inspect its own privileges.
121static RESTRICT_TO_USER_OBJECTS_ALLOWED_OIDS: LazyLock<BTreeSet<u32>> = LazyLock::new(|| {
122    use mz_pgrepr::oid;
123    btreeset! {
124        oid::VIEW_MZ_MCP_DATA_PRODUCTS_OID,
125        oid::VIEW_MZ_MCP_DATA_PRODUCT_DETAILS_OID,
126        oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
127    }
128});
129
130/// Errors that can occur due to an unauthorized action.
131#[derive(Debug, thiserror::Error)]
132pub enum UnauthorizedError {
133    /// The action can only be performed by a superuser.
134    #[error("permission denied to {action}")]
135    Superuser { action: String },
136    /// The action requires ownership of an object.
137    #[error("must be owner of {}", objects.iter().map(|(object_type, object_name)| format!("{object_type} {object_name}")).join(", "))]
138    Ownership { objects: Vec<(ObjectType, String)> },
139    /// Altering an owner requires membership of the new owner role.
140    #[error("must be a member of {}", role_names.iter().map(|role| role.quoted()).join(", "))]
141    RoleMembership { role_names: Vec<String> },
142    /// The action requires one or more privileges.
143    #[error("permission denied for {object_description}")]
144    Privilege {
145        object_description: ErrorMessageObjectDescription,
146        role_name: String,
147        privileges: String,
148    },
149    // TODO(jkosh44) When we implement parameter privileges, this can be replaced with a regular
150    //  privilege error.
151    /// The action can only be performed by the mz_system role.
152    #[error("permission denied to {action}")]
153    MzSystem { action: String },
154    /// The action cannot be performed by the mz_support role.
155    #[error("permission denied to {action}")]
156    MzSupport { action: String },
157    /// The active role was dropped while a user was logged in.
158    #[error("role {0} was concurrently dropped")]
159    ConcurrentRoleDrop(RoleId),
160    /// Access to system objects is restricted by the restrict_to_user_objects session variable.
161    #[error("access to system object {object_name} is restricted")]
162    RestrictedSystemObject { object_name: String },
163}
164
165impl UnauthorizedError {
166    pub fn detail(&self) -> Option<String> {
167        match &self {
168            UnauthorizedError::Superuser { action } => {
169                Some(format!("You must be a superuser to {}", action))
170            }
171            UnauthorizedError::Privilege {
172                object_description,
173                role_name,
174                privileges,
175            } => Some(format!(
176                "The '{role_name}' role needs {privileges} privileges on {object_description}"
177            )),
178            UnauthorizedError::MzSystem { .. } => {
179                Some(format!("You must be the '{}' role", SYSTEM_USER.name))
180            }
181            UnauthorizedError::MzSupport { .. } => Some(format!(
182                "The '{}' role has very limited privileges",
183                SUPPORT_USER.name
184            )),
185            UnauthorizedError::ConcurrentRoleDrop(_) => {
186                Some("Please disconnect and re-connect with a valid role.".into())
187            }
188            UnauthorizedError::RestrictedSystemObject { .. } => Some(
189                "Access to system catalog objects is restricted for this role. \
190                Contact your administrator if you need access."
191                    .into(),
192            ),
193            UnauthorizedError::Ownership { .. } | UnauthorizedError::RoleMembership { .. } => None,
194        }
195    }
196}
197
198/// RBAC requirements for executing a given plan.
199#[derive(Debug)]
200struct RbacRequirements {
201    /// The role memberships required.
202    role_membership: BTreeSet<RoleId>,
203    /// The object ownerships required.
204    ownership: Vec<ObjectId>,
205    /// The privileges required. The tuples are of the form:
206    /// (What object the privilege is on, What privilege is required, Who must possess the privilege).
207    privileges: Vec<(SystemObjectId, AclMode, RoleId)>,
208    /// The types of catalog items that this plan requires USAGE privileges on.
209    ///
210    /// Most plans will require USAGE on secrets and connections but some plans, like SHOW CREATE,
211    /// can reference an item without requiring any privileges on that item.
212    item_usage: &'static BTreeSet<CatalogItemType>,
213    /// Some action if superuser is required to perform that action, None otherwise.
214    superuser_action: Option<String>,
215}
216
217impl RbacRequirements {
218    fn empty() -> RbacRequirements {
219        RbacRequirements {
220            role_membership: BTreeSet::new(),
221            ownership: Vec::new(),
222            privileges: Vec::new(),
223            item_usage: &EMPTY_ITEM_USAGE,
224            superuser_action: None,
225        }
226    }
227
228    fn validate(
229        self,
230        catalog: &impl SessionCatalog,
231        session: &dyn SessionMetadata,
232        resolved_ids: &ResolvedIds,
233    ) -> Result<(), UnauthorizedError> {
234        // Obtain all roles that the current session is a member of.
235        let role_membership =
236            catalog.collect_role_membership(&session.role_metadata().current_role);
237
238        check_usage(catalog, session, resolved_ids, self.item_usage)?;
239
240        // Validate that the current session has the required role membership to execute the provided
241        // plan.
242        let unheld_membership: Vec<_> = self.role_membership.difference(&role_membership).collect();
243        if !unheld_membership.is_empty() {
244            let role_names = unheld_membership
245                .into_iter()
246                .map(|role_id| {
247                    // Some role references may no longer exist due to concurrent drops.
248                    catalog
249                        .try_get_role(role_id)
250                        .map(|role| role.name().to_string())
251                        .unwrap_or_else(|| role_id.to_string())
252                })
253                .collect();
254            return Err(UnauthorizedError::RoleMembership { role_names });
255        }
256
257        // Validate that the current session has the required object ownership to execute the provided
258        // plan.
259        let unheld_ownership = self
260            .ownership
261            .into_iter()
262            .filter(|ownership| !check_owner_roles(ownership, &role_membership, catalog))
263            .collect();
264        ownership_err(unheld_ownership, catalog)?;
265
266        check_object_privileges(
267            catalog,
268            self.privileges,
269            role_membership,
270            session.role_metadata().current_role,
271        )?;
272
273        if let Some(action) = self.superuser_action {
274            return Err(UnauthorizedError::Superuser { action });
275        }
276
277        Ok(())
278    }
279
280    fn filter_to_mandatory_requirements(self) -> RbacRequirements {
281        let RbacRequirements {
282            role_membership,
283            ownership,
284            privileges,
285            item_usage,
286            superuser_action: _,
287        } = self;
288        let role_membership = role_membership
289            .into_iter()
290            .filter(|id| id.is_system())
291            .collect();
292        let ownership = ownership.into_iter().filter(|id| id.is_system()).collect();
293        let privileges = privileges
294            .into_iter()
295            .filter(|(id, _, _)| matches!(id, SystemObjectId::Object(oid) if oid.is_system()))
296            // We allow reading objects for superusers and when RBAC is off.
297            .update(|(_, acl_mode, _)| acl_mode.remove(AclMode::SELECT))
298            .filter(|(_, acl_mode, _)| !acl_mode.is_empty())
299            .collect();
300        let superuser_action = None;
301        RbacRequirements {
302            role_membership,
303            ownership,
304            privileges,
305            item_usage,
306            superuser_action,
307        }
308    }
309}
310
311impl Default for RbacRequirements {
312    fn default() -> Self {
313        RbacRequirements {
314            role_membership: BTreeSet::new(),
315            ownership: Vec::new(),
316            privileges: Vec::new(),
317            item_usage: &DEFAULT_ITEM_USAGE,
318            superuser_action: None,
319        }
320    }
321}
322
323/// When `restrict_to_user_objects` is active, rejects access to system catalog objects.
324///
325/// Functions and types are allowed through because they are needed for query execution.
326/// All other system items (tables, views, sources, sinks, etc.) are blocked. This is an
327/// allow-list — new catalog item types are blocked by default.
328///
329/// See: doc/developer/design/20260508_restrict_to_user_objects.md
330fn check_restrict_to_user_objects(
331    catalog: &impl SessionCatalog,
332    session: &dyn SessionMetadata,
333    resolved_ids: &ResolvedIds,
334) -> Result<(), UnauthorizedError> {
335    if !session.restrict_to_user_objects() {
336        return Ok(());
337    }
338    for item_id in resolved_ids.items() {
339        if item_id.is_system() {
340            if let Some(item) = catalog.try_get_item(item_id) {
341                match item.item_type() {
342                    CatalogItemType::Func | CatalogItemType::Type => {}
343                    _ => {
344                        if RESTRICT_TO_USER_OBJECTS_ALLOWED_OIDS.contains(&item.oid()) {
345                            continue;
346                        }
347                        return Err(UnauthorizedError::RestrictedSystemObject {
348                            object_name: item.name().item.clone(),
349                        });
350                    }
351                }
352            }
353        }
354    }
355    Ok(())
356}
357
358/// Checks if a `session` is authorized to use `resolved_ids`. If not, an error is returned.
359pub fn check_usage(
360    catalog: &impl SessionCatalog,
361    session: &dyn SessionMetadata,
362    resolved_ids: &ResolvedIds,
363    item_types: &BTreeSet<CatalogItemType>,
364) -> Result<(), UnauthorizedError> {
365    check_session_roles(catalog, session)?;
366
367    // See: doc/developer/design/20260508_restrict_to_user_objects.md
368    check_restrict_to_user_objects(catalog, session, resolved_ids)?;
369
370    // Obtain all roles that the current session is a member of.
371    let role_membership = catalog.collect_role_membership(&session.role_metadata().current_role);
372
373    // Certain statements depend on objects that haven't been created yet, like sub-sources, so we
374    // need to filter those out.
375    let existing_resolved_ids =
376        resolved_ids.retain_items(|item_id| catalog.try_get_item(item_id).is_some());
377
378    let required_privileges = generate_usage_privileges(
379        catalog,
380        &existing_resolved_ids,
381        session.role_metadata().current_role,
382        item_types,
383    )
384    .into_iter()
385    .collect();
386
387    let mut rbac_requirements = RbacRequirements::empty();
388    rbac_requirements.privileges = required_privileges;
389    let rbac_requirements = filter_requirements(catalog, session, rbac_requirements);
390    let required_privileges = rbac_requirements.privileges;
391
392    check_object_privileges(
393        catalog,
394        required_privileges,
395        role_membership,
396        session.role_metadata().current_role,
397    )?;
398
399    Ok(())
400}
401
402/// Authorizes a statement for purification, which runs before planning and so
403/// escapes the [`check_plan`] gate. `source` is the existing source the
404/// statement would drive, as resolved by [`crate::pure::statement_source`].
405///
406/// The requirements are the same ones planning enforces later, so a statement
407/// that passes here can still be rejected by [`check_plan`], never the reverse.
408pub fn check_purification(
409    catalog: &impl SessionCatalog,
410    session: &dyn SessionMetadata,
411    source: Option<StatementSource>,
412    resolved_ids: &ResolvedIds,
413) -> Result<(), UnauthorizedError> {
414    // Like `check_plan`: `validate` reads the current role's membership through
415    // the panicking `get_role`, so the concurrent-role-drop case must be turned
416    // into a clean error before anything else runs.
417    check_session_roles(catalog, session)?;
418
419    let role_id = session.role_metadata().current_role;
420    let mut requirements = RbacRequirements {
421        item_usage: &CREATE_ITEM_USAGE,
422        ..Default::default()
423    };
424    match source {
425        Some(StatementSource::Altered(id)) => {
426            requirements.ownership = vec![ObjectId::Item(id)];
427        }
428        Some(StatementSource::Read(id)) => {
429            requirements.privileges = generate_read_privileges(catalog, iter::once(id), role_id);
430        }
431        // Statements that name their connection are covered by `item_usage`.
432        None => {}
433    }
434
435    let requirements = filter_requirements(catalog, session, requirements);
436    requirements.validate(catalog, session, resolved_ids)
437}
438
439/// Checks if a session is authorized to execute a plan. If not, an error is returned.
440///
441/// `sql_impl_resolved_ids` contains resolved IDs discovered inside SQL-implemented function
442/// bodies during planning. These are kept separate from `resolved_ids` because they are
443/// implementation details of the functions, not dependencies of the statement. They are
444/// only checked by the `restrict_to_user_objects` restriction.
445pub fn check_plan(
446    catalog: &impl SessionCatalog,
447    // The authenticated role of the connection targeted by the plan, if the plan is a
448    // Plan::SideEffectingFunc that targets an existing connection. The role may have been
449    // dropped concurrently. Ignored for other plan types.
450    target_conn_role: Option<RoleId>,
451    session: &dyn SessionMetadata,
452    plan: &Plan,
453    target_cluster_id: Option<ClusterId>,
454    resolved_ids: &ResolvedIds,
455    sql_impl_resolved_ids: &ResolvedIds,
456) -> Result<(), UnauthorizedError> {
457    check_session_roles(catalog, session)?;
458
459    // Check sql_impl function body dependencies against restrict_to_user_objects.
460    // These are checked separately from the main resolved_ids because they are
461    // implementation details that should not affect dependency tracking.
462    check_restrict_to_user_objects(catalog, session, sql_impl_resolved_ids)?;
463
464    let rbac_requirements = generate_rbac_requirements(
465        catalog,
466        plan,
467        target_conn_role,
468        target_cluster_id,
469        session.role_metadata().current_role,
470    );
471    let rbac_requirements = filter_requirements(catalog, session, rbac_requirements);
472    debug!(
473        "rbac requirements {rbac_requirements:?} for plan {:?}",
474        PlanKind::from(plan)
475    );
476    rbac_requirements.validate(catalog, session, resolved_ids)
477}
478
479/// Returns true if RBAC is turned on for a session, false otherwise.
480pub fn is_rbac_enabled_for_session(
481    system_vars: &SystemVars,
482    session: &dyn SessionMetadata,
483) -> bool {
484    let server_enabled = system_vars.enable_rbac_checks();
485    let session_enabled = session.enable_session_rbac_checks();
486
487    // The session flag allows users to turn RBAC on for just their session while the server flag
488    // allows users to turn RBAC on for everyone.
489    server_enabled || session_enabled
490}
491
492/// Generates all requirements needed to execute a given plan.
493fn generate_rbac_requirements(
494    catalog: &impl SessionCatalog,
495    plan: &Plan,
496    target_conn_role: Option<RoleId>,
497    target_cluster_id: Option<ClusterId>,
498    role_id: RoleId,
499) -> RbacRequirements {
500    match plan {
501        Plan::CreateConnection(plan::CreateConnectionPlan {
502            name,
503            if_not_exists: _,
504            connection: _,
505            validate: _,
506        }) => RbacRequirements {
507            privileges: vec![(
508                SystemObjectId::Object(name.qualifiers.clone().into()),
509                AclMode::CREATE,
510                role_id,
511            )],
512            item_usage: &CREATE_ITEM_USAGE,
513            ..Default::default()
514        },
515        Plan::CreateDatabase(plan::CreateDatabasePlan {
516            name: _,
517            if_not_exists: _,
518        }) => RbacRequirements {
519            privileges: vec![(SystemObjectId::System, AclMode::CREATE_DB, role_id)],
520            item_usage: &CREATE_ITEM_USAGE,
521            ..Default::default()
522        },
523        Plan::CreateSchema(plan::CreateSchemaPlan {
524            database_spec,
525            schema_name: _,
526            if_not_exists: _,
527        }) => {
528            let privileges = match database_spec {
529                ResolvedDatabaseSpecifier::Ambient => Vec::new(),
530                ResolvedDatabaseSpecifier::Id(database_id) => {
531                    vec![(
532                        SystemObjectId::Object(database_id.into()),
533                        AclMode::CREATE,
534                        role_id,
535                    )]
536                }
537            };
538            RbacRequirements {
539                privileges,
540                item_usage: &CREATE_ITEM_USAGE,
541                ..Default::default()
542            }
543        }
544        Plan::CreateRole(plan::CreateRolePlan {
545            name: _,
546            attributes,
547        }) => {
548            if attributes.superuser.unwrap_or(false) {
549                RbacRequirements {
550                    superuser_action: Some("create superuser role".to_string()),
551                    ..Default::default()
552                }
553            } else {
554                RbacRequirements {
555                    privileges: vec![(SystemObjectId::System, AclMode::CREATE_ROLE, role_id)],
556                    item_usage: &CREATE_ITEM_USAGE,
557                    ..Default::default()
558                }
559            }
560        }
561        Plan::CreateQueryPolicy(plan::CreateQueryPolicyPlan { .. }) => RbacRequirements {
562            privileges: vec![(
563                SystemObjectId::System,
564                AclMode::CREATE_QUERY_POLICY,
565                role_id,
566            )],
567            item_usage: &CREATE_ITEM_USAGE,
568            ..Default::default()
569        },
570        Plan::CreateNetworkPolicy(plan::CreateNetworkPolicyPlan { .. }) => RbacRequirements {
571            privileges: vec![(
572                SystemObjectId::System,
573                AclMode::CREATE_NETWORK_POLICY,
574                role_id,
575            )],
576            item_usage: &CREATE_ITEM_USAGE,
577            ..Default::default()
578        },
579        Plan::CreateCluster(plan::CreateClusterPlan {
580            name: _,
581            variant: _,
582            workload_class: _,
583            if_not_exists: _,
584            query_policy,
585        }) => {
586            let mut privileges = vec![(SystemObjectId::System, AclMode::CREATE_CLUSTER, role_id)];
587            if let Some(id) = query_policy {
588                privileges.push((
589                    SystemObjectId::Object(ObjectId::QueryPolicy(*id)),
590                    AclMode::USAGE,
591                    role_id,
592                ));
593            }
594            RbacRequirements {
595                privileges,
596                item_usage: &CREATE_ITEM_USAGE,
597                ..Default::default()
598            }
599        }
600        Plan::CreateClusterReplica(plan::CreateClusterReplicaPlan {
601            cluster_id,
602            name: _,
603            config: _,
604            if_not_exists: _,
605        }) => RbacRequirements {
606            ownership: vec![ObjectId::Cluster(*cluster_id)],
607            item_usage: &CREATE_ITEM_USAGE,
608            ..Default::default()
609        },
610        Plan::CreateSource(plan::CreateSourcePlan {
611            name,
612            source,
613            if_not_exists: _,
614            timeline: _,
615            in_cluster,
616        }) => RbacRequirements {
617            privileges: generate_required_source_privileges(
618                name,
619                &source.data_source,
620                *in_cluster,
621                role_id,
622            ),
623            item_usage: &CREATE_ITEM_USAGE,
624            ..Default::default()
625        },
626        Plan::CreateSources(plans) => RbacRequirements {
627            privileges: plans
628                .iter()
629                .flat_map(
630                    |plan::CreateSourcePlanBundle {
631                         item_id: _,
632                         global_id: _,
633                         plan:
634                             plan::CreateSourcePlan {
635                                 name,
636                                 source,
637                                 if_not_exists: _,
638                                 timeline: _,
639                                 in_cluster,
640                             },
641                         resolved_ids: _,
642                         available_source_references: _,
643                     }| {
644                        generate_required_source_privileges(
645                            name,
646                            &source.data_source,
647                            *in_cluster,
648                            role_id,
649                        )
650                        .into_iter()
651                    },
652                )
653                .collect(),
654            item_usage: &CREATE_ITEM_USAGE,
655            ..Default::default()
656        },
657        Plan::CreateSecret(plan::CreateSecretPlan {
658            name,
659            secret: _,
660            if_not_exists: _,
661        }) => RbacRequirements {
662            privileges: vec![(
663                SystemObjectId::Object(name.qualifiers.clone().into()),
664                AclMode::CREATE,
665                role_id,
666            )],
667            item_usage: &CREATE_ITEM_USAGE,
668            ..Default::default()
669        },
670        Plan::CreateSink(plan::CreateSinkPlan {
671            name,
672            sink,
673            with_snapshot: _,
674            if_not_exists: _,
675            in_cluster,
676        }) => {
677            let mut privileges = vec![(
678                SystemObjectId::Object(name.qualifiers.clone().into()),
679                AclMode::CREATE,
680                role_id,
681            )];
682            let items = iter::once(sink.from).map(|gid| catalog.resolve_item_id(&gid));
683            privileges.extend_from_slice(&generate_read_privileges(catalog, items, role_id));
684            privileges.push((
685                SystemObjectId::Object(in_cluster.into()),
686                AclMode::CREATE,
687                role_id,
688            ));
689            RbacRequirements {
690                privileges,
691                item_usage: &CREATE_ITEM_USAGE,
692                ..Default::default()
693            }
694        }
695        Plan::CreateTable(plan::CreateTablePlan {
696            name,
697            table,
698            if_not_exists: _,
699        }) => {
700            let mut privileges = vec![(
701                SystemObjectId::Object(name.qualifiers.clone().into()),
702                AclMode::CREATE,
703                role_id,
704            )];
705            // `CREATE TABLE ... FROM SOURCE` reads the source's data, so it
706            // requires `SELECT` on the source. `check_purification` enforces
707            // the same read requirement before purification; keep them in sync
708            // or its subset invariant inverts.
709            if let TableDataSource::DataSource {
710                desc: DataSourceDesc::IngestionExport { ingestion_id, .. },
711                timeline: _,
712            } = &table.data_source
713            {
714                privileges.extend(generate_read_privileges(
715                    catalog,
716                    iter::once(*ingestion_id),
717                    role_id,
718                ));
719            }
720            RbacRequirements {
721                privileges,
722                item_usage: &CREATE_ITEM_USAGE,
723                ..Default::default()
724            }
725        }
726        Plan::CreateView(plan::CreateViewPlan {
727            name,
728            view: _,
729            replace,
730            drop_ids: _,
731            if_not_exists: _,
732            ambiguous_columns: _,
733        }) => RbacRequirements {
734            ownership: replace
735                .map(|id| vec![ObjectId::Item(id)])
736                .unwrap_or_default(),
737            privileges: vec![(
738                SystemObjectId::Object(name.qualifiers.clone().into()),
739                AclMode::CREATE,
740                role_id,
741            )],
742            item_usage: &CREATE_ITEM_USAGE,
743            ..Default::default()
744        },
745        Plan::CreateMaterializedView(plan::CreateMaterializedViewPlan {
746            name,
747            materialized_view,
748            replace,
749            drop_ids: _,
750            if_not_exists: _,
751            ambiguous_columns: _,
752        }) => RbacRequirements {
753            // `CREATE REPLACEMENT MATERIALIZED VIEW ... FOR <target>` requires ownership of the
754            // target, mirroring `ALTER ... APPLY REPLACEMENT` and `CREATE INDEX`, which require
755            // ownership of the item they act on. `replace` is the separate `CREATE OR REPLACE`
756            // target. Both are optional and independent, so require ownership of whichever are set.
757            ownership: replace
758                .iter()
759                .chain(materialized_view.replacement_target.iter())
760                .map(|id| ObjectId::Item(*id))
761                .collect(),
762            privileges: vec![
763                (
764                    SystemObjectId::Object(name.qualifiers.clone().into()),
765                    AclMode::CREATE,
766                    role_id,
767                ),
768                (
769                    SystemObjectId::Object(materialized_view.cluster_id.into()),
770                    AclMode::CREATE,
771                    role_id,
772                ),
773            ],
774            item_usage: &CREATE_ITEM_USAGE,
775            ..Default::default()
776        },
777        Plan::CreateIndex(plan::CreateIndexPlan {
778            name,
779            index,
780            if_not_exists: _,
781        }) => {
782            let index_on_item = catalog.resolve_item_id(&index.on);
783            RbacRequirements {
784                ownership: vec![ObjectId::Item(index_on_item)],
785                privileges: vec![
786                    (
787                        SystemObjectId::Object(name.qualifiers.clone().into()),
788                        AclMode::CREATE,
789                        role_id,
790                    ),
791                    (
792                        SystemObjectId::Object(index.cluster_id.into()),
793                        AclMode::CREATE,
794                        role_id,
795                    ),
796                ],
797                item_usage: &CREATE_ITEM_USAGE,
798                ..Default::default()
799            }
800        }
801        Plan::CreateMetricSink(plan::CreateMetricSinkPlan {
802            name,
803            metric_sink,
804            if_not_exists: _,
805        }) => {
806            // A metric sink republishes the FROM relation's rows on the replica's scrape
807            // endpoint, so it is an egress path for that relation's contents, exactly like
808            // CREATE SINK. The guard is therefore read privileges on the source, not
809            // ownership of it.
810            let mut privileges = vec![(
811                SystemObjectId::Object(name.qualifiers.clone().into()),
812                AclMode::CREATE,
813                role_id,
814            )];
815            let items = iter::once(metric_sink.from).map(|gid| catalog.resolve_item_id(&gid));
816            privileges.extend_from_slice(&generate_read_privileges(catalog, items, role_id));
817            privileges.push((
818                SystemObjectId::Object(metric_sink.cluster_id.into()),
819                AclMode::CREATE,
820                role_id,
821            ));
822            RbacRequirements {
823                privileges,
824                item_usage: &CREATE_ITEM_USAGE,
825                ..Default::default()
826            }
827        }
828        Plan::CreateType(plan::CreateTypePlan { name, typ: _ }) => RbacRequirements {
829            privileges: vec![(
830                SystemObjectId::Object(name.qualifiers.clone().into()),
831                AclMode::CREATE,
832                role_id,
833            )],
834            item_usage: &CREATE_ITEM_USAGE,
835            ..Default::default()
836        },
837        Plan::Comment(plan::CommentPlan {
838            object_id,
839            sub_component: _,
840            comment: _,
841        }) => {
842            let (ownership, privileges) = match object_id {
843                // Roles don't have owners, instead we require the current session to have the
844                // `CREATEROLE` privilege.
845                CommentObjectId::Role(_) => (
846                    Vec::new(),
847                    vec![(SystemObjectId::System, AclMode::CREATE_ROLE, role_id)],
848                ),
849                _ => (vec![ObjectId::from(*object_id)], Vec::new()),
850            };
851            RbacRequirements {
852                ownership,
853                privileges,
854                ..Default::default()
855            }
856        }
857        Plan::DropObjects(plan::DropObjectsPlan {
858            cascade: _,
859            referenced_ids,
860            drop_ids: _,
861            object_type,
862        }) => {
863            let privileges = if object_type == &ObjectType::Role {
864                vec![(SystemObjectId::System, AclMode::CREATE_ROLE, role_id)]
865            } else {
866                referenced_ids
867                    .iter()
868                    .filter_map(|id| match id {
869                        ObjectId::ClusterReplica((cluster_id, _)) => Some((
870                            SystemObjectId::Object(cluster_id.into()),
871                            AclMode::USAGE,
872                            role_id,
873                        )),
874                        ObjectId::Schema((database_spec, _)) => match database_spec {
875                            ResolvedDatabaseSpecifier::Ambient => None,
876                            ResolvedDatabaseSpecifier::Id(database_id) => Some((
877                                SystemObjectId::Object(database_id.into()),
878                                AclMode::USAGE,
879                                role_id,
880                            )),
881                        },
882                        ObjectId::Item(item_id) => {
883                            let item = catalog.get_item(item_id);
884                            Some((
885                                SystemObjectId::Object(item.name().qualifiers.clone().into()),
886                                AclMode::USAGE,
887                                role_id,
888                            ))
889                        }
890                        ObjectId::Cluster(_)
891                        | ObjectId::Database(_)
892                        | ObjectId::Role(_)
893                        | ObjectId::NetworkPolicy(_)
894                        | ObjectId::QueryPolicy(_) => None,
895                    })
896                    .collect()
897            };
898            RbacRequirements {
899                // Do not need ownership of descendant objects.
900                ownership: referenced_ids.clone(),
901                privileges,
902                ..Default::default()
903            }
904        }
905        Plan::DropOwned(plan::DropOwnedPlan {
906            cascade: _,
907            role_ids,
908            drop_ids: _,
909            privilege_revokes: _,
910            default_privilege_revokes: _,
911        }) => RbacRequirements {
912            role_membership: role_ids.into_iter().cloned().collect(),
913            ..Default::default()
914        },
915        Plan::ShowCreate(plan::ShowCreatePlan { id, row: _ }) => {
916            let container_id = match id {
917                ObjectId::Item(id) => Some(SystemObjectId::Object(
918                    catalog.get_item(id).name().qualifiers.clone().into(),
919                )),
920                ObjectId::Schema((database_id, _schema_id)) => match database_id {
921                    ResolvedDatabaseSpecifier::Ambient => None,
922                    ResolvedDatabaseSpecifier::Id(id) => Some(SystemObjectId::Object(id.into())),
923                },
924                ObjectId::Cluster(_)
925                | ObjectId::ClusterReplica(_)
926                | ObjectId::Database(_)
927                | ObjectId::Role(_)
928                | ObjectId::NetworkPolicy(_)
929                | ObjectId::QueryPolicy(_) => None,
930            };
931            let privileges = match container_id {
932                Some(id) => vec![(id, AclMode::USAGE, role_id)],
933                None => Vec::new(),
934            };
935            RbacRequirements {
936                privileges,
937                item_usage: &EMPTY_ITEM_USAGE,
938                ..Default::default()
939            }
940        }
941        Plan::ShowColumns(plan::ShowColumnsPlan {
942            id,
943            select_plan,
944            new_resolved_ids: _,
945        }) => {
946            let mut privileges = vec![(
947                SystemObjectId::Object(catalog.get_item(id).name().qualifiers.clone().into()),
948                AclMode::USAGE,
949                role_id,
950            )];
951
952            for privilege in generate_rbac_requirements(
953                catalog,
954                &Plan::Select(select_plan.clone()),
955                target_conn_role,
956                target_cluster_id,
957                role_id,
958            )
959            .privileges
960            {
961                privileges.push(privilege);
962            }
963            RbacRequirements {
964                privileges,
965                ..Default::default()
966            }
967        }
968        Plan::Select(plan::SelectPlan {
969            source,
970            select: _,
971            when: _,
972            finishing: _,
973            copy_to: _,
974        }) => {
975            let items = source
976                .depends_on()
977                .into_iter()
978                .map(|gid| catalog.resolve_item_id(&gid));
979            let mut privileges = generate_read_privileges(catalog, items, role_id);
980            if let Some(privilege) = generate_cluster_usage_privileges(
981                source.as_const().is_some(),
982                target_cluster_id,
983                role_id,
984            ) {
985                privileges.push(privilege);
986            }
987            RbacRequirements {
988                privileges,
989                ..Default::default()
990            }
991        }
992        Plan::Subscribe(plan::SubscribePlan {
993            from,
994            with_snapshot: _,
995            when: _,
996            up_to: _,
997            copy_to: _,
998            emit_progress: _,
999            output: _,
1000        }) => {
1001            let items = from
1002                .depends_on()
1003                .into_iter()
1004                .map(|gid| catalog.resolve_item_id(&gid));
1005            let mut privileges = generate_read_privileges(catalog, items, role_id);
1006            if let Some(cluster_id) = target_cluster_id {
1007                privileges.push((
1008                    SystemObjectId::Object(cluster_id.into()),
1009                    AclMode::USAGE,
1010                    role_id,
1011                ));
1012            }
1013            RbacRequirements {
1014                privileges,
1015                ..Default::default()
1016            }
1017        }
1018        Plan::CopyFrom(plan::CopyFromPlan {
1019            target_name: _,
1020            target_id,
1021            source: _,
1022            columns: _,
1023            source_desc: _,
1024            mfp: _,
1025            params: _,
1026            filter: _,
1027        }) => RbacRequirements {
1028            privileges: vec![
1029                (
1030                    SystemObjectId::Object(
1031                        catalog.get_item(target_id).name().qualifiers.clone().into(),
1032                    ),
1033                    AclMode::USAGE,
1034                    role_id,
1035                ),
1036                (
1037                    SystemObjectId::Object(target_id.into()),
1038                    AclMode::INSERT,
1039                    role_id,
1040                ),
1041            ],
1042            ..Default::default()
1043        },
1044        Plan::CopyTo(plan::CopyToPlan {
1045            select_plan,
1046            desc: _,
1047            to: _,
1048            connection: _,
1049            connection_id: _,
1050            format: _,
1051            max_file_size: _,
1052        }) => {
1053            let items = select_plan
1054                .source
1055                .depends_on()
1056                .into_iter()
1057                .map(|gid| catalog.resolve_item_id(&gid));
1058            let mut privileges = generate_read_privileges(catalog, items, role_id);
1059            if let Some(cluster_id) = target_cluster_id {
1060                privileges.push((
1061                    SystemObjectId::Object(cluster_id.into()),
1062                    AclMode::USAGE,
1063                    role_id,
1064                ));
1065            }
1066            RbacRequirements {
1067                privileges,
1068                ..Default::default()
1069            }
1070        }
1071        Plan::ExplainPlan(plan::ExplainPlanPlan {
1072            stage: _,
1073            format: _,
1074            config: _,
1075            explainee,
1076        })
1077        | Plan::ExplainPushdown(plan::ExplainPushdownPlan { explainee }) => RbacRequirements {
1078            privileges: match explainee {
1079                Explainee::View(id)
1080                | Explainee::MaterializedView(id)
1081                | Explainee::Index(id)
1082                | Explainee::ReplanView(id)
1083                | Explainee::ReplanMaterializedView(id)
1084                | Explainee::ReplanIndex(id) => {
1085                    let item = catalog.get_item(id);
1086                    let schema_id: ObjectId = item.name().qualifiers.clone().into();
1087                    vec![(SystemObjectId::Object(schema_id), AclMode::USAGE, role_id)]
1088                }
1089                Explainee::Statement(stmt) => stmt
1090                    .depends_on()
1091                    .into_iter()
1092                    .map(|id| {
1093                        let item = catalog.get_item_by_global_id(&id);
1094                        let schema_id: ObjectId = item.name().qualifiers.clone().into();
1095                        (SystemObjectId::Object(schema_id), AclMode::USAGE, role_id)
1096                    })
1097                    .collect(),
1098            },
1099            item_usage: match explainee {
1100                Explainee::View(..)
1101                | Explainee::MaterializedView(..)
1102                | Explainee::Index(..)
1103                | Explainee::ReplanView(..)
1104                | Explainee::ReplanMaterializedView(..)
1105                | Explainee::ReplanIndex(..) => &EMPTY_ITEM_USAGE,
1106                Explainee::Statement(_) => &DEFAULT_ITEM_USAGE,
1107            },
1108            ..Default::default()
1109        },
1110        Plan::ExplainSinkSchema(plan::ExplainSinkSchemaPlan { sink_from, .. }) => {
1111            RbacRequirements {
1112                privileges: {
1113                    let item = catalog.get_item_by_global_id(sink_from);
1114                    let schema_id: ObjectId = item.name().qualifiers.clone().into();
1115                    vec![(SystemObjectId::Object(schema_id), AclMode::USAGE, role_id)]
1116                },
1117                item_usage: &EMPTY_ITEM_USAGE,
1118                ..Default::default()
1119            }
1120        }
1121        Plan::ExplainTimestamp(plan::ExplainTimestampPlan {
1122            format: _,
1123            raw_plan,
1124            when: _,
1125        }) => RbacRequirements {
1126            privileges: raw_plan
1127                .depends_on()
1128                .into_iter()
1129                .map(|id| {
1130                    let item = catalog.get_item_by_global_id(&id);
1131                    let schema_id: ObjectId = item.name().qualifiers.clone().into();
1132                    (SystemObjectId::Object(schema_id), AclMode::USAGE, role_id)
1133                })
1134                .collect(),
1135            ..Default::default()
1136        },
1137        Plan::Insert(plan::InsertPlan {
1138            id,
1139            values,
1140            returning,
1141        }) => {
1142            let schema_id: ObjectId = catalog.get_item(id).name().qualifiers.clone().into();
1143            let mut privileges = vec![
1144                (
1145                    SystemObjectId::Object(schema_id.clone()),
1146                    AclMode::USAGE,
1147                    role_id,
1148                ),
1149                (SystemObjectId::Object(id.into()), AclMode::INSERT, role_id),
1150            ];
1151            let mut seen = BTreeSet::from([(schema_id, role_id)]);
1152
1153            // We don't allow arbitrary sub-queries in `returning`. So either it
1154            // contains a column reference to the outer table or it's constant.
1155            if returning
1156                .iter()
1157                .any(|assignment| assignment.contains_column())
1158            {
1159                privileges.push((SystemObjectId::Object(id.into()), AclMode::SELECT, role_id));
1160                seen.insert((id.into(), role_id));
1161            }
1162
1163            let items = values
1164                .depends_on()
1165                .into_iter()
1166                .map(|gid| catalog.resolve_item_id(&gid));
1167            privileges.extend_from_slice(&generate_read_privileges_inner(
1168                catalog, items, role_id, &mut seen,
1169            ));
1170
1171            if let Some(privilege) = generate_cluster_usage_privileges(
1172                values.as_const().is_some(),
1173                target_cluster_id,
1174                role_id,
1175            ) {
1176                privileges.push(privilege);
1177            } else if !returning.is_empty() {
1178                // TODO(jkosh44) returning may be a constant, but for now we are overly protective
1179                //  and require cluster privileges for all returning.
1180                if let Some(cluster_id) = target_cluster_id {
1181                    privileges.push((
1182                        SystemObjectId::Object(cluster_id.into()),
1183                        AclMode::USAGE,
1184                        role_id,
1185                    ));
1186                }
1187            }
1188            RbacRequirements {
1189                privileges,
1190                ..Default::default()
1191            }
1192        }
1193        Plan::AlterCluster(plan::AlterClusterPlan {
1194            id,
1195            name: _,
1196            options,
1197            strategy: _,
1198        }) => {
1199            use plan::AlterOptionParameter::{Reset, Set, Unchanged};
1200            // New cluster options must explicitly participate in this ownership exemption.
1201            let attachment_only = matches!(
1202                options,
1203                plan::PlanClusterOption {
1204                    availability_zones: Unchanged,
1205                    introspection_debugging: Unchanged,
1206                    introspection_interval: Unchanged,
1207                    arrangement_compression: Unchanged,
1208                    managed: Unchanged,
1209                    replicas: Unchanged,
1210                    replication_factor: Unchanged,
1211                    size: Unchanged,
1212                    schedule: Unchanged,
1213                    workload_class: Unchanged,
1214                    auto_scaling_strategy: Unchanged,
1215                    query_policy: Set(_) | Reset,
1216                }
1217            );
1218            let mut privileges = Vec::new();
1219            if !matches!(options.query_policy, Unchanged) {
1220                privileges.push((
1221                    SystemObjectId::Object(ObjectId::Cluster(*id)),
1222                    AclMode::CREATE,
1223                    role_id,
1224                ));
1225            }
1226            if let Set(Some(policy)) = options.query_policy {
1227                privileges.push((
1228                    SystemObjectId::Object(ObjectId::QueryPolicy(policy)),
1229                    AclMode::USAGE,
1230                    role_id,
1231                ));
1232            }
1233            RbacRequirements {
1234                ownership: if attachment_only {
1235                    vec![]
1236                } else {
1237                    vec![ObjectId::Cluster(*id)]
1238                },
1239                privileges,
1240                item_usage: &CREATE_ITEM_USAGE,
1241                ..Default::default()
1242            }
1243        }
1244        Plan::AlterSetCluster(plan::AlterSetClusterPlan { id, set_cluster }) => RbacRequirements {
1245            ownership: vec![ObjectId::Item(*id)],
1246            privileges: vec![(
1247                SystemObjectId::Object(set_cluster.into()),
1248                AclMode::CREATE,
1249                role_id,
1250            )],
1251            item_usage: &CREATE_ITEM_USAGE,
1252            ..Default::default()
1253        },
1254        Plan::AlterRetainHistory(plan::AlterRetainHistoryPlan {
1255            id,
1256            window: _,
1257            value: _,
1258            object_type: _,
1259        }) => RbacRequirements {
1260            ownership: vec![ObjectId::Item(*id)],
1261            item_usage: &CREATE_ITEM_USAGE,
1262            ..Default::default()
1263        },
1264        Plan::AlterSourceTimestampInterval(plan::AlterSourceTimestampIntervalPlan {
1265            id,
1266            value: _,
1267            interval: _,
1268        }) => RbacRequirements {
1269            ownership: vec![ObjectId::Item(*id)],
1270            item_usage: &CREATE_ITEM_USAGE,
1271            ..Default::default()
1272        },
1273        Plan::AlterConnection(plan::AlterConnectionPlan { id, action: _ }) => RbacRequirements {
1274            ownership: vec![ObjectId::Item(*id)],
1275            ..Default::default()
1276        },
1277        // `check_purification` enforces the same ownership requirement before
1278        // purification; keep them in sync or its subset invariant inverts.
1279        Plan::AlterSource(plan::AlterSourcePlan {
1280            item_id,
1281            ingestion_id: _,
1282            action: _,
1283        }) => RbacRequirements {
1284            ownership: vec![ObjectId::Item(*item_id)],
1285            item_usage: &CREATE_ITEM_USAGE,
1286            ..Default::default()
1287        },
1288        Plan::AlterSink(plan::AlterSinkPlan {
1289            item_id,
1290            global_id: _,
1291            sink,
1292            with_snapshot: _,
1293            in_cluster,
1294            set_options: _,
1295            reset_options: _,
1296        }) => {
1297            let items = iter::once(sink.from).map(|gid| catalog.resolve_item_id(&gid));
1298            let mut privileges = generate_read_privileges(catalog, items, role_id);
1299            privileges.push((
1300                SystemObjectId::Object(in_cluster.into()),
1301                AclMode::CREATE,
1302                role_id,
1303            ));
1304            RbacRequirements {
1305                ownership: vec![ObjectId::Item(*item_id)],
1306                privileges,
1307                item_usage: &CREATE_ITEM_USAGE,
1308                ..Default::default()
1309            }
1310        }
1311        Plan::AlterClusterRename(plan::AlterClusterRenamePlan {
1312            id,
1313            name: _,
1314            to_name: _,
1315        }) => RbacRequirements {
1316            ownership: vec![ObjectId::Cluster(*id)],
1317            ..Default::default()
1318        },
1319        Plan::AlterClusterSwap(plan::AlterClusterSwapPlan {
1320            id_a,
1321            id_b,
1322            name_a: _,
1323            name_b: _,
1324            name_temp: _,
1325        }) => RbacRequirements {
1326            ownership: vec![ObjectId::Cluster(*id_a), ObjectId::Cluster(*id_b)],
1327            ..Default::default()
1328        },
1329        Plan::AlterClusterReplicaRename(plan::AlterClusterReplicaRenamePlan {
1330            cluster_id,
1331            replica_id,
1332            name: _,
1333            to_name: _,
1334        }) => RbacRequirements {
1335            ownership: vec![ObjectId::ClusterReplica((*cluster_id, *replica_id))],
1336            ..Default::default()
1337        },
1338        Plan::AlterItemRename(plan::AlterItemRenamePlan {
1339            id,
1340            current_full_name: _,
1341            to_name: _,
1342            object_type: _,
1343        }) => RbacRequirements {
1344            ownership: vec![ObjectId::Item(*id)],
1345            ..Default::default()
1346        },
1347        Plan::AlterSchemaRename(plan::AlterSchemaRenamePlan {
1348            cur_schema_spec,
1349            new_schema_name: _,
1350        }) => {
1351            let privileges = match cur_schema_spec.0 {
1352                ResolvedDatabaseSpecifier::Id(db_id) => vec![(
1353                    SystemObjectId::Object(ObjectId::Database(db_id)),
1354                    AclMode::CREATE,
1355                    role_id,
1356                )],
1357                ResolvedDatabaseSpecifier::Ambient => vec![],
1358            };
1359
1360            RbacRequirements {
1361                ownership: vec![ObjectId::Schema(*cur_schema_spec)],
1362                privileges,
1363                ..Default::default()
1364            }
1365        }
1366        Plan::AlterSchemaSwap(plan::AlterSchemaSwapPlan {
1367            schema_a_spec,
1368            schema_a_name: _,
1369            schema_b_spec,
1370            schema_b_name: _,
1371            name_temp: _,
1372        }) => {
1373            let mut privileges = vec![];
1374            if let ResolvedDatabaseSpecifier::Id(id_a) = schema_a_spec.0 {
1375                privileges.push((
1376                    SystemObjectId::Object(ObjectId::Database(id_a)),
1377                    AclMode::CREATE,
1378                    role_id,
1379                ));
1380            }
1381            if let ResolvedDatabaseSpecifier::Id(id_b) = schema_b_spec.0 {
1382                privileges.push((
1383                    SystemObjectId::Object(ObjectId::Database(id_b)),
1384                    AclMode::CREATE,
1385                    role_id,
1386                ));
1387            }
1388
1389            RbacRequirements {
1390                ownership: vec![
1391                    ObjectId::Schema(*schema_a_spec),
1392                    ObjectId::Schema(*schema_b_spec),
1393                ],
1394                privileges,
1395                ..Default::default()
1396            }
1397        }
1398        Plan::AlterSecret(plan::AlterSecretPlan { id, secret_as: _ }) => RbacRequirements {
1399            ownership: vec![ObjectId::Item(*id)],
1400            item_usage: &CREATE_ITEM_USAGE,
1401            ..Default::default()
1402        },
1403        Plan::AlterRole(plan::AlterRolePlan {
1404            id,
1405            name: _,
1406            option,
1407        }) => match option {
1408            // Only superusers can alter the superuserness of a role.
1409            plan::PlannedAlterRoleOption::Attributes(attributes)
1410                if attributes.superuser.is_some() =>
1411            {
1412                RbacRequirements {
1413                    superuser_action: Some("alter superuser role".to_string()),
1414                    ..Default::default()
1415                }
1416            }
1417            // Roles are allowed to change their own password, but only if
1418            // password is the sole attribute being changed.
1419            plan::PlannedAlterRoleOption::Attributes(plan::PlannedRoleAttributes {
1420                password,
1421                // scram_iterations and nopassword are password-related, so
1422                // they're fine to change alongside the password.
1423                scram_iterations: _,
1424                nopassword: _,
1425                // superuser is already handled by the match arm above, so it
1426                // will always be None here.
1427                superuser: None,
1428                inherit: None,
1429                login: None,
1430            }) if password.is_some() && role_id == *id => RbacRequirements::default(),
1431            // But no one elses...
1432            plan::PlannedAlterRoleOption::Attributes(attributes)
1433                if attributes.password.is_some() && role_id != *id =>
1434            {
1435                RbacRequirements {
1436                    superuser_action: Some("alter password of role".to_string()),
1437                    ..Default::default()
1438                }
1439            }
1440            // restrict_to_user_objects can only be set by superuser.
1441            // SECURITY: This must use case-insensitive comparison because
1442            // var.name() comes from Ident::to_string() which preserves the
1443            // original casing for quoted identifiers.
1444            plan::PlannedAlterRoleOption::Variable(var)
1445                if var.name().eq_ignore_ascii_case("restrict_to_user_objects") =>
1446            {
1447                RbacRequirements {
1448                    superuser_action: Some("set restrict_to_user_objects".to_string()),
1449                    ..Default::default()
1450                }
1451            }
1452            // Roles are allowed to change their own other variables.
1453            plan::PlannedAlterRoleOption::Variable(_) if role_id == *id => {
1454                RbacRequirements::default()
1455            }
1456            // Otherwise to ALTER a role, you need to have the CREATE_ROLE privilege.
1457            _ => RbacRequirements {
1458                privileges: vec![(SystemObjectId::System, AclMode::CREATE_ROLE, role_id)],
1459                item_usage: &CREATE_ITEM_USAGE,
1460                ..Default::default()
1461            },
1462        },
1463        Plan::AlterOwner(plan::AlterOwnerPlan {
1464            id,
1465            object_type: _,
1466            new_owner,
1467        }) => {
1468            let privileges = match id {
1469                ObjectId::ClusterReplica((cluster_id, _)) => {
1470                    vec![(
1471                        SystemObjectId::Object(cluster_id.into()),
1472                        AclMode::CREATE,
1473                        role_id,
1474                    )]
1475                }
1476                ObjectId::Schema((database_spec, _)) => match database_spec {
1477                    ResolvedDatabaseSpecifier::Ambient => Vec::new(),
1478                    ResolvedDatabaseSpecifier::Id(database_id) => {
1479                        vec![(
1480                            SystemObjectId::Object(database_id.into()),
1481                            AclMode::CREATE,
1482                            role_id,
1483                        )]
1484                    }
1485                },
1486                ObjectId::Item(item_id) => {
1487                    let item = catalog.get_item(item_id);
1488                    vec![(
1489                        SystemObjectId::Object(item.name().qualifiers.clone().into()),
1490                        AclMode::CREATE,
1491                        role_id,
1492                    )]
1493                }
1494                ObjectId::Cluster(_)
1495                | ObjectId::Database(_)
1496                | ObjectId::Role(_)
1497                | ObjectId::NetworkPolicy(_)
1498                | ObjectId::QueryPolicy(_) => Vec::new(),
1499            };
1500            RbacRequirements {
1501                role_membership: BTreeSet::from([*new_owner]),
1502                ownership: vec![id.clone()],
1503                privileges,
1504                ..Default::default()
1505            }
1506        }
1507        Plan::AlterTableAddColumn(plan::AlterTablePlan { relation_id, .. }) => RbacRequirements {
1508            ownership: vec![ObjectId::Item(*relation_id)],
1509            item_usage: &CREATE_ITEM_USAGE,
1510            ..Default::default()
1511        },
1512        Plan::AlterMaterializedViewApplyReplacement(
1513            plan::AlterMaterializedViewApplyReplacementPlan { id, replacement_id },
1514        ) => RbacRequirements {
1515            ownership: vec![ObjectId::Item(*id), ObjectId::Item(*replacement_id)],
1516            item_usage: &CREATE_ITEM_USAGE,
1517            ..Default::default()
1518        },
1519        Plan::AlterQueryPolicy(plan::AlterQueryPolicyPlan { id, .. }) => RbacRequirements {
1520            ownership: vec![ObjectId::QueryPolicy(*id)],
1521            ..Default::default()
1522        },
1523        Plan::AlterNetworkPolicy(plan::AlterNetworkPolicyPlan { id, .. }) => RbacRequirements {
1524            ownership: vec![ObjectId::NetworkPolicy(*id)],
1525            item_usage: &CREATE_ITEM_USAGE,
1526            ..Default::default()
1527        },
1528        Plan::ReadThenWrite(plan::ReadThenWritePlan {
1529            id,
1530            selection,
1531            finishing: _,
1532            assignments,
1533            kind,
1534            returning,
1535        }) => {
1536            let acl_mode = match kind {
1537                MutationKind::Insert => AclMode::INSERT,
1538                MutationKind::Update => AclMode::UPDATE,
1539                MutationKind::Delete => AclMode::DELETE,
1540            };
1541            let schema_id: ObjectId = catalog.get_item(id).name().qualifiers.clone().into();
1542            let mut privileges = vec![
1543                (
1544                    SystemObjectId::Object(schema_id.clone()),
1545                    AclMode::USAGE,
1546                    role_id,
1547                ),
1548                (SystemObjectId::Object(id.into()), acl_mode, role_id),
1549            ];
1550            let mut seen = BTreeSet::from([(schema_id, role_id)]);
1551
1552            // We don't allow arbitrary sub-queries in `assignments` or `returning`. So either they
1553            // contains a column reference to the outer table or it's constant.
1554            if assignments
1555                .values()
1556                .chain(returning.iter())
1557                .any(|assignment| assignment.contains_column())
1558            {
1559                privileges.push((SystemObjectId::Object(id.into()), AclMode::SELECT, role_id));
1560                seen.insert((id.into(), role_id));
1561            }
1562
1563            // TODO(jkosh44) It's fairly difficult to determine what part of `selection` is from a
1564            //  user specified read and what part is from the implementation of the read then write.
1565            //  instead we are overly protective and always require SELECT privileges even though
1566            //  PostgreSQL doesn't always do this.
1567            //  As a concrete example, we require SELECT and UPDATE privileges to execute
1568            //  `UPDATE t SET a = 42;`, while PostgreSQL only requires UPDATE privileges.
1569            let items = selection
1570                .depends_on()
1571                .into_iter()
1572                .map(|gid| catalog.resolve_item_id(&gid));
1573            privileges.extend_from_slice(&generate_read_privileges_inner(
1574                catalog, items, role_id, &mut seen,
1575            ));
1576
1577            if let Some(privilege) = generate_cluster_usage_privileges(
1578                selection.as_const().is_some(),
1579                target_cluster_id,
1580                role_id,
1581            ) {
1582                privileges.push(privilege);
1583            }
1584            RbacRequirements {
1585                privileges,
1586                ..Default::default()
1587            }
1588        }
1589        Plan::GrantRole(plan::GrantRolePlan {
1590            role_ids: _,
1591            member_ids: _,
1592            grantor_id: _,
1593        })
1594        | Plan::RevokeRole(plan::RevokeRolePlan {
1595            role_ids: _,
1596            member_ids: _,
1597            grantor_id: _,
1598        }) => RbacRequirements {
1599            privileges: vec![(SystemObjectId::System, AclMode::CREATE_ROLE, role_id)],
1600            ..Default::default()
1601        },
1602        Plan::GrantPrivileges(plan::GrantPrivilegesPlan {
1603            update_privileges,
1604            grantees: _,
1605        })
1606        | Plan::RevokePrivileges(plan::RevokePrivilegesPlan {
1607            update_privileges,
1608            revokees: _,
1609        }) => {
1610            let mut privileges = Vec::with_capacity(update_privileges.len());
1611            for UpdatePrivilege { target_id, .. } in update_privileges {
1612                match target_id {
1613                    SystemObjectId::Object(object_id) => match object_id {
1614                        ObjectId::ClusterReplica((cluster_id, _)) => {
1615                            privileges.push((
1616                                SystemObjectId::Object(cluster_id.into()),
1617                                AclMode::USAGE,
1618                                role_id,
1619                            ));
1620                        }
1621                        ObjectId::Schema((database_spec, _)) => match database_spec {
1622                            ResolvedDatabaseSpecifier::Ambient => {}
1623                            ResolvedDatabaseSpecifier::Id(database_id) => {
1624                                privileges.push((
1625                                    SystemObjectId::Object(database_id.into()),
1626                                    AclMode::USAGE,
1627                                    role_id,
1628                                ));
1629                            }
1630                        },
1631                        ObjectId::Item(item_id) => {
1632                            let item = catalog.get_item(item_id);
1633                            privileges.push((
1634                                SystemObjectId::Object(item.name().qualifiers.clone().into()),
1635                                AclMode::USAGE,
1636                                role_id,
1637                            ))
1638                        }
1639                        ObjectId::Cluster(_)
1640                        | ObjectId::Database(_)
1641                        | ObjectId::Role(_)
1642                        | ObjectId::NetworkPolicy(_)
1643                        | ObjectId::QueryPolicy(_) => {}
1644                    },
1645                    SystemObjectId::System => {}
1646                }
1647            }
1648            RbacRequirements {
1649                ownership: update_privileges
1650                    .iter()
1651                    .filter_map(|update_privilege| update_privilege.target_id.object_id())
1652                    .cloned()
1653                    .collect(),
1654                privileges,
1655                // To grant/revoke a privilege on some object, generally the grantor/revoker must be the
1656                // owner of that object (or have a grant option on that object which isn't implemented in
1657                // Materialize yet). There is no owner of the entire system, so it's only reasonable to
1658                // restrict granting/revoking system privileges to superusers.
1659                superuser_action: if update_privileges
1660                    .iter()
1661                    .any(|update_privilege| update_privilege.target_id.is_system())
1662                {
1663                    Some("GRANT/REVOKE SYSTEM PRIVILEGES".to_string())
1664                } else {
1665                    None
1666                },
1667                ..Default::default()
1668            }
1669        }
1670        Plan::AlterDefaultPrivileges(plan::AlterDefaultPrivilegesPlan {
1671            privilege_objects,
1672            privilege_acl_items: _,
1673            is_grant: _,
1674        }) => RbacRequirements {
1675            role_membership: privilege_objects
1676                .iter()
1677                .map(|privilege_object| privilege_object.role_id)
1678                .collect(),
1679            privileges: privilege_objects
1680                .into_iter()
1681                .filter_map(|privilege_object| {
1682                    if let (Some(database_id), Some(_)) =
1683                        (privilege_object.database_id, privilege_object.schema_id)
1684                    {
1685                        Some((
1686                            SystemObjectId::Object(database_id.into()),
1687                            AclMode::USAGE,
1688                            role_id,
1689                        ))
1690                    } else {
1691                        None
1692                    }
1693                })
1694                .collect(),
1695            // Altering the default privileges for the PUBLIC role (aka ALL ROLES) will affect all roles
1696            // that currently exist and roles that will exist in the future. It's impossible for an exising
1697            // role to be a member of a role that doesn't exist yet, so no current role could possibly have
1698            // the privileges required to alter default privileges for the PUBLIC role. Therefore we
1699            // only superusers can alter default privileges for the PUBLIC role.
1700            superuser_action: if privilege_objects
1701                .iter()
1702                .any(|privilege_object| privilege_object.role_id.is_public())
1703            {
1704                Some("ALTER DEFAULT PRIVILEGES FOR ALL ROLES".to_string())
1705            } else {
1706                None
1707            },
1708            ..Default::default()
1709        },
1710        Plan::ReassignOwned(plan::ReassignOwnedPlan {
1711            old_roles,
1712            new_role,
1713            reassign_ids: _,
1714        }) => RbacRequirements {
1715            role_membership: old_roles
1716                .into_iter()
1717                .cloned()
1718                .chain(iter::once(*new_role))
1719                .collect(),
1720            ..Default::default()
1721        },
1722        Plan::SideEffectingFunc(func) => {
1723            let role_membership = match func {
1724                // A `NULL` argument cancels no connection (the function returns
1725                // `NULL`), so there is no role membership to require.
1726                SideEffectingFunc::PgCancelBackend {
1727                    connection_id: None,
1728                } => BTreeSet::new(),
1729                SideEffectingFunc::PgCancelBackend {
1730                    connection_id: Some(_),
1731                } => target_conn_role.map(|x| [x].into()).unwrap_or_default(),
1732            };
1733            RbacRequirements {
1734                role_membership,
1735                ..Default::default()
1736            }
1737        }
1738        Plan::ValidateConnection(plan::ValidateConnectionPlan { id, connection: _ }) => {
1739            let schema_id: ObjectId = catalog.get_item(id).name().qualifiers.clone().into();
1740            RbacRequirements {
1741                privileges: vec![
1742                    (SystemObjectId::Object(schema_id), AclMode::USAGE, role_id),
1743                    (SystemObjectId::Object(id.into()), AclMode::USAGE, role_id),
1744                ],
1745                ..Default::default()
1746            }
1747        }
1748        Plan::DiscardTemp
1749        | Plan::DiscardAll
1750        | Plan::EmptyQuery
1751        | Plan::ShowAllVariables
1752        | Plan::ShowVariable(plan::ShowVariablePlan { name: _ })
1753        | Plan::InspectShard(plan::InspectShardPlan { id: _ })
1754        | Plan::SetVariable(plan::SetVariablePlan {
1755            name: _,
1756            value: _,
1757            local: _,
1758        })
1759        | Plan::ResetVariable(plan::ResetVariablePlan { name: _ })
1760        | Plan::SetTransaction(plan::SetTransactionPlan { local: _, modes: _ })
1761        | Plan::StartTransaction(plan::StartTransactionPlan {
1762            access: _,
1763            isolation_level: _,
1764        })
1765        | Plan::CommitTransaction(plan::CommitTransactionPlan {
1766            transaction_type: _,
1767        })
1768        | Plan::AbortTransaction(plan::AbortTransactionPlan {
1769            transaction_type: _,
1770        })
1771        | Plan::AlterNoop(plan::AlterNoopPlan { object_type: _ })
1772        | Plan::AlterSystemSet(plan::AlterSystemSetPlan { name: _, value: _ })
1773        | Plan::AlterSystemReset(plan::AlterSystemResetPlan { name: _ })
1774        | Plan::AlterSystemResetAll(plan::AlterSystemResetAllPlan {})
1775        | Plan::Declare(plan::DeclarePlan {
1776            name: _,
1777            stmt: _,
1778            sql: _,
1779            params: _,
1780        })
1781        | Plan::Fetch(plan::FetchPlan {
1782            name: _,
1783            count: _,
1784            timeout: _,
1785        })
1786        | Plan::Close(plan::ClosePlan { name: _ })
1787        | Plan::Prepare(plan::PreparePlan {
1788            name: _,
1789            stmt: _,
1790            desc: _,
1791            sql: _,
1792        })
1793        | Plan::Execute(plan::ExecutePlan { name: _, params: _ })
1794        | Plan::Deallocate(plan::DeallocatePlan { name: _ })
1795        | Plan::Raise(plan::RaisePlan { severity: _ }) => Default::default(),
1796    }
1797}
1798
1799/// Reports whether any role has ownership over an object.
1800fn check_owner_roles(
1801    object_id: &ObjectId,
1802    role_ids: &BTreeSet<RoleId>,
1803    catalog: &impl SessionCatalog,
1804) -> bool {
1805    if let Some(owner_id) = catalog.get_owner_id(object_id) {
1806        role_ids.contains(&owner_id)
1807    } else {
1808        true
1809    }
1810}
1811
1812fn ownership_err(
1813    unheld_ownership: Vec<ObjectId>,
1814    catalog: &impl SessionCatalog,
1815) -> Result<(), UnauthorizedError> {
1816    if !unheld_ownership.is_empty() {
1817        let objects = unheld_ownership
1818            .into_iter()
1819            .map(|ownership| match ownership {
1820                ObjectId::Cluster(id) => (
1821                    ObjectType::Cluster,
1822                    catalog.get_cluster(id).name().to_string(),
1823                ),
1824                ObjectId::ClusterReplica((cluster_id, replica_id)) => {
1825                    let cluster = catalog.get_cluster(cluster_id);
1826                    let replica = catalog.get_cluster_replica(cluster_id, replica_id);
1827                    // Note: using unchecked here is okay because the values are coming from an
1828                    // already existing name.
1829                    let name = QualifiedReplica {
1830                        cluster: Ident::new_unchecked(cluster.name()),
1831                        replica: Ident::new_unchecked(replica.name()),
1832                    };
1833                    (ObjectType::ClusterReplica, name.to_string())
1834                }
1835                ObjectId::Database(id) => (
1836                    ObjectType::Database,
1837                    catalog.get_database(&id).name().to_string(),
1838                ),
1839                ObjectId::Schema((database_spec, schema_spec)) => {
1840                    let schema = catalog.get_schema(&database_spec, &schema_spec);
1841                    let name = catalog.resolve_full_schema_name(schema.name());
1842                    (ObjectType::Schema, name.to_string())
1843                }
1844                ObjectId::Item(id) => {
1845                    let item = catalog.get_item(&id);
1846                    let name = catalog.resolve_full_name(item.name());
1847                    (item.item_type().into(), name.to_string())
1848                }
1849                ObjectId::NetworkPolicy(id) => (
1850                    ObjectType::NetworkPolicy,
1851                    catalog.get_network_policy(&id).name().to_string(),
1852                ),
1853                ObjectId::QueryPolicy(id) => (
1854                    ObjectType::QueryPolicy,
1855                    catalog.get_query_policy(&id).name().to_string(),
1856                ),
1857                ObjectId::Role(_) => unreachable!("roles have no owner"),
1858            })
1859            .collect();
1860        Err(UnauthorizedError::Ownership { objects })
1861    } else {
1862        Ok(())
1863    }
1864}
1865
1866fn generate_required_source_privileges(
1867    name: &QualifiedItemName,
1868    data_source: &DataSourceDesc,
1869    in_cluster: Option<ClusterId>,
1870    role_id: RoleId,
1871) -> Vec<(SystemObjectId, AclMode, RoleId)> {
1872    let mut privileges = vec![(
1873        SystemObjectId::Object(name.qualifiers.clone().into()),
1874        AclMode::CREATE,
1875        role_id,
1876    )];
1877    match (data_source, in_cluster) {
1878        (_, Some(id)) => {
1879            privileges.push((SystemObjectId::Object(id.into()), AclMode::CREATE, role_id))
1880        }
1881        (DataSourceDesc::Ingestion(_), None) => {
1882            privileges.push((SystemObjectId::System, AclMode::CREATE_CLUSTER, role_id))
1883        }
1884        // Non-ingestion data-sources have meaningless cluster config's (for now...) and they need
1885        // to be ignored.
1886        // This feels very brittle, but there's not much we can do until the UNDEFINED cluster
1887        // config is removed.
1888        (_, None) => {}
1889    }
1890    privileges
1891}
1892
1893/// Generates all the privileges required to execute a read that includes the objects in `ids`.
1894///
1895/// Not only do we need to validate that `role_id` has read privileges on all relations in `ids`,
1896/// but if any object is a view or materialized view then we need to validate that the owner of
1897/// that view has all of the privileges required to execute the query within the view.
1898///
1899/// For more details see: <https://www.postgresql.org/docs/15/rules-privileges.html>
1900fn generate_read_privileges(
1901    catalog: &impl SessionCatalog,
1902    ids: impl Iterator<Item = CatalogItemId>,
1903    role_id: RoleId,
1904) -> Vec<(SystemObjectId, AclMode, RoleId)> {
1905    generate_read_privileges_inner(catalog, ids, role_id, &mut BTreeSet::new())
1906}
1907
1908fn generate_read_privileges_inner(
1909    catalog: &impl SessionCatalog,
1910    ids: impl Iterator<Item = CatalogItemId>,
1911    role_id: RoleId,
1912    seen: &mut BTreeSet<(ObjectId, RoleId)>,
1913) -> Vec<(SystemObjectId, AclMode, RoleId)> {
1914    let mut privileges = Vec::new();
1915
1916    // Iterative worklist traversal rather than recursion. View dependency
1917    // chains are user controlled and can be arbitrarily deep.
1918    let mut queue: VecDeque<(CatalogItemId, RoleId)> = ids.map(|id| (id, role_id)).collect();
1919    while let Some((id, role_id)) = queue.pop_front() {
1920        if seen.insert((id.into(), role_id)) {
1921            let item = catalog.get_item(&id);
1922            let schema_id: ObjectId = item.name().qualifiers.clone().into();
1923            if seen.insert((schema_id.clone(), role_id)) {
1924                privileges.push((SystemObjectId::Object(schema_id), AclMode::USAGE, role_id))
1925            }
1926            match item.item_type() {
1927                CatalogItemType::View | CatalogItemType::MaterializedView => {
1928                    privileges.push((SystemObjectId::Object(id.into()), AclMode::SELECT, role_id));
1929                    let view_owner = item.owner_id();
1930                    queue.extend(item.references().items().map(|id| (*id, view_owner)));
1931                }
1932                CatalogItemType::Table | CatalogItemType::Source => {
1933                    privileges.push((SystemObjectId::Object(id.into()), AclMode::SELECT, role_id));
1934                }
1935                CatalogItemType::Type | CatalogItemType::Secret | CatalogItemType::Connection => {
1936                    privileges.push((SystemObjectId::Object(id.into()), AclMode::USAGE, role_id));
1937                }
1938                CatalogItemType::Sink
1939                | CatalogItemType::MetricSink
1940                | CatalogItemType::Index
1941                | CatalogItemType::Func => {}
1942            }
1943        }
1944    }
1945
1946    privileges
1947}
1948
1949fn generate_usage_privileges(
1950    catalog: &impl SessionCatalog,
1951    ids: &ResolvedIds,
1952    role_id: RoleId,
1953    item_types: &BTreeSet<CatalogItemType>,
1954) -> BTreeSet<(SystemObjectId, AclMode, RoleId)> {
1955    // Use a `BTreeSet` to remove duplicate privileges.
1956    ids.items()
1957        .filter_map(move |id| {
1958            let item = catalog.get_item(id);
1959            if item_types.contains(&item.item_type()) {
1960                let schema_id = item.name().qualifiers.clone().into();
1961                Some([
1962                    (SystemObjectId::Object(schema_id), AclMode::USAGE, role_id),
1963                    (SystemObjectId::Object(id.into()), AclMode::USAGE, role_id),
1964                ])
1965            } else {
1966                None
1967            }
1968        })
1969        .flatten()
1970        .collect()
1971}
1972
1973fn generate_cluster_usage_privileges(
1974    expr_is_const: bool,
1975    target_cluster_id: Option<ClusterId>,
1976    role_id: RoleId,
1977) -> Option<(SystemObjectId, AclMode, RoleId)> {
1978    // TODO(jkosh44) expr hasn't been fully optimized yet, so it might actually be a constant,
1979    //  but we mistakenly think that it's not. For now it's ok to be overly protective.
1980    if !expr_is_const {
1981        if let Some(cluster_id) = target_cluster_id {
1982            return Some((
1983                SystemObjectId::Object(cluster_id.into()),
1984                AclMode::USAGE,
1985                role_id,
1986            ));
1987        }
1988    }
1989
1990    None
1991}
1992
1993fn check_object_privileges(
1994    catalog: &impl SessionCatalog,
1995    privileges: Vec<(SystemObjectId, AclMode, RoleId)>,
1996    role_membership: BTreeSet<RoleId>,
1997    current_role_id: RoleId,
1998) -> Result<(), UnauthorizedError> {
1999    let mut role_memberships: BTreeMap<RoleId, BTreeSet<RoleId>> = BTreeMap::new();
2000    role_memberships.insert(current_role_id, role_membership);
2001    for (object_id, acl_mode, role_id) in privileges {
2002        // Temporary schemas are owned by the connection that created them,
2003        // so users implicitly have all privileges on their own temp schema.
2004        // The schema may not exist yet (lazy creation), so we skip the check.
2005        if matches!(
2006            &object_id,
2007            SystemObjectId::Object(ObjectId::Schema((_, SchemaSpecifier::Temporary)))
2008        ) {
2009            continue;
2010        }
2011
2012        let role_membership = role_memberships
2013            .entry(role_id)
2014            .or_insert_with_key(|role_id| catalog.collect_role_membership(role_id));
2015        let object_privileges = catalog
2016            .get_privileges(&object_id)
2017            .expect("only object types with privileges will generate required privileges");
2018        let role_privileges = role_membership
2019            .iter()
2020            .flat_map(|role_id| object_privileges.get_acl_items_for_grantee(role_id))
2021            .map(|mz_acl_item| mz_acl_item.acl_mode)
2022            .fold(AclMode::empty(), |accum, acl_mode| accum.union(acl_mode));
2023        if !role_privileges.contains(acl_mode) {
2024            let role_name = catalog.get_role(&role_id).name().to_string();
2025            let privileges = acl_mode.to_error_string();
2026            return Err(UnauthorizedError::Privilege {
2027                object_description: ErrorMessageObjectDescription::from_sys_id(&object_id, catalog),
2028                role_name,
2029                privileges,
2030            });
2031        }
2032    }
2033
2034    Ok(())
2035}
2036
2037pub const fn all_object_privileges(object_type: SystemObjectType) -> AclMode {
2038    const TABLE_ACL_MODE: AclMode = AclMode::INSERT
2039        .union(AclMode::SELECT)
2040        .union(AclMode::UPDATE)
2041        .union(AclMode::DELETE);
2042    const USAGE_CREATE_ACL_MODE: AclMode = AclMode::USAGE.union(AclMode::CREATE);
2043    const ALL_SYSTEM_PRIVILEGES: AclMode = AclMode::CREATE_ROLE
2044        .union(AclMode::CREATE_DB)
2045        .union(AclMode::CREATE_CLUSTER)
2046        .union(AclMode::CREATE_NETWORK_POLICY)
2047        .union(AclMode::CREATE_QUERY_POLICY);
2048
2049    const EMPTY_ACL_MODE: AclMode = AclMode::empty();
2050    match object_type {
2051        SystemObjectType::Object(ObjectType::Table) => TABLE_ACL_MODE,
2052        SystemObjectType::Object(ObjectType::View) => AclMode::SELECT,
2053        SystemObjectType::Object(ObjectType::MaterializedView) => AclMode::SELECT,
2054        SystemObjectType::Object(ObjectType::Source) => AclMode::SELECT,
2055        SystemObjectType::Object(ObjectType::Sink) => EMPTY_ACL_MODE,
2056        SystemObjectType::Object(ObjectType::MetricSink) => EMPTY_ACL_MODE,
2057        SystemObjectType::Object(ObjectType::Index) => EMPTY_ACL_MODE,
2058        SystemObjectType::Object(ObjectType::Type) => AclMode::USAGE,
2059        SystemObjectType::Object(ObjectType::Role) => EMPTY_ACL_MODE,
2060        SystemObjectType::Object(ObjectType::Cluster) => USAGE_CREATE_ACL_MODE,
2061        SystemObjectType::Object(ObjectType::ClusterReplica) => EMPTY_ACL_MODE,
2062        SystemObjectType::Object(ObjectType::Secret) => AclMode::USAGE,
2063        SystemObjectType::Object(ObjectType::NetworkPolicy) => AclMode::USAGE,
2064        SystemObjectType::Object(ObjectType::QueryPolicy) => AclMode::USAGE,
2065        SystemObjectType::Object(ObjectType::Connection) => AclMode::USAGE,
2066        SystemObjectType::Object(ObjectType::Database) => USAGE_CREATE_ACL_MODE,
2067        SystemObjectType::Object(ObjectType::Schema) => USAGE_CREATE_ACL_MODE,
2068        SystemObjectType::Object(ObjectType::Func) => EMPTY_ACL_MODE,
2069        SystemObjectType::System => ALL_SYSTEM_PRIVILEGES,
2070    }
2071}
2072
2073pub const fn owner_privilege(object_type: ObjectType, owner_id: RoleId) -> MzAclItem {
2074    MzAclItem {
2075        grantee: owner_id,
2076        grantor: owner_id,
2077        acl_mode: all_object_privileges(SystemObjectType::Object(object_type)),
2078    }
2079}
2080
2081const fn default_builtin_object_acl_mode(object_type: ObjectType) -> AclMode {
2082    match object_type {
2083        ObjectType::Table
2084        | ObjectType::View
2085        | ObjectType::MaterializedView
2086        | ObjectType::Source => AclMode::SELECT,
2087        ObjectType::Type | ObjectType::Schema => AclMode::USAGE,
2088        ObjectType::Sink
2089        | ObjectType::MetricSink
2090        | ObjectType::Index
2091        | ObjectType::Role
2092        | ObjectType::Cluster
2093        | ObjectType::ClusterReplica
2094        | ObjectType::Secret
2095        | ObjectType::Connection
2096        | ObjectType::Database
2097        | ObjectType::Func
2098        | ObjectType::NetworkPolicy
2099        | ObjectType::QueryPolicy => AclMode::empty(),
2100    }
2101}
2102
2103pub const fn support_builtin_object_privilege(object_type: ObjectType) -> MzAclItem {
2104    let acl_mode = default_builtin_object_acl_mode(object_type);
2105    MzAclItem {
2106        grantee: MZ_SUPPORT_ROLE_ID,
2107        grantor: MZ_SYSTEM_ROLE_ID,
2108        acl_mode,
2109    }
2110}
2111
2112pub const fn default_builtin_object_privilege(object_type: ObjectType) -> MzAclItem {
2113    let acl_mode = default_builtin_object_acl_mode(object_type);
2114    MzAclItem {
2115        grantee: RoleId::Public,
2116        grantor: MZ_SYSTEM_ROLE_ID,
2117        acl_mode,
2118    }
2119}