Skip to main content

mz_sql/plan/statement/
acl.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
10//! Access control list (ACL).
11//!
12//! This module houses the handlers for statements that modify privileges in the catalog, like
13//! `GRANT`, `REVOKE`, and `REASSIGN OWNED`.
14
15use std::collections::BTreeSet;
16
17use itertools::Itertools;
18use mz_sql_parser::ast::display::AstDisplay;
19
20use crate::ast::{Ident, UnresolvedDatabaseName};
21use crate::catalog::{
22    DefaultPrivilegeAclItem, DefaultPrivilegeObject, ErrorMessageObjectDescription, ObjectType,
23    SystemObjectType,
24};
25use crate::names::{
26    Aug, ObjectId, ResolvedDatabaseSpecifier, ResolvedRoleName, SchemaSpecifier, SystemObjectId,
27};
28use crate::plan::error::PlanError;
29use crate::plan::statement::ddl::{
30    resolve_cluster, resolve_database, resolve_item_or_type, resolve_network_policy, resolve_schema,
31};
32use crate::plan::statement::{StatementContext, StatementDesc};
33use crate::plan::{
34    AlterDefaultPrivilegesPlan, AlterNoopPlan, AlterOwnerPlan, GrantPrivilegesPlan, GrantRolePlan,
35    Plan, PlanNotice, ReassignOwnedPlan, RevokePrivilegesPlan, RevokeRolePlan, UpdatePrivilege,
36};
37use crate::session::user::SYSTEM_USER;
38use mz_ore::str::StrExt;
39use mz_repr::adt::mz_acl_item::AclMode;
40use mz_repr::role_id::RoleId;
41use mz_sql_parser::ast::{
42    AbbreviatedGrantOrRevokeStatement, AlterDefaultPrivilegesStatement, AlterOwnerStatement,
43    GrantPrivilegesStatement, GrantRoleStatement, GrantTargetAllSpecification,
44    GrantTargetSpecification, GrantTargetSpecificationInner, Privilege, PrivilegeSpecification,
45    ReassignOwnedStatement, RevokePrivilegesStatement, RevokeRoleStatement,
46    TargetRoleSpecification, UnresolvedItemName, UnresolvedObjectName, UnresolvedSchemaName,
47};
48
49pub fn describe_alter_owner(
50    _: &StatementContext,
51    _: AlterOwnerStatement<Aug>,
52) -> Result<StatementDesc, PlanError> {
53    Ok(StatementDesc::new(None))
54}
55
56pub fn plan_alter_owner(
57    scx: &StatementContext,
58    AlterOwnerStatement {
59        object_type,
60        if_exists,
61        name,
62        new_owner,
63    }: AlterOwnerStatement<Aug>,
64) -> Result<Plan, PlanError> {
65    let object_type = object_type.into();
66    match (object_type, name) {
67        (ObjectType::Cluster, UnresolvedObjectName::Cluster(name)) => {
68            plan_alter_cluster_owner(scx, if_exists, name, new_owner.id)
69        }
70        (ObjectType::ClusterReplica, UnresolvedObjectName::ClusterReplica(_)) => {
71            bail_never_supported!("altering the owner of a cluster replica");
72        }
73        (ObjectType::Database, UnresolvedObjectName::Database(name)) => {
74            plan_alter_database_owner(scx, if_exists, name, new_owner.id)
75        }
76        (ObjectType::Schema, UnresolvedObjectName::Schema(name)) => {
77            plan_alter_schema_owner(scx, if_exists, name, new_owner.id)
78        }
79        (ObjectType::NetworkPolicy, UnresolvedObjectName::NetworkPolicy(name)) => {
80            plan_alter_network_policy_owner(scx, if_exists, name, new_owner.id)
81        }
82        (ObjectType::QueryPolicy, UnresolvedObjectName::QueryPolicy(name)) => {
83            let policy = scx.catalog.resolve_query_policy(name.as_str())?;
84            Ok(Plan::AlterOwner(AlterOwnerPlan {
85                id: ObjectId::QueryPolicy(policy.id()),
86                object_type,
87                new_owner: new_owner.id,
88            }))
89        }
90        // The parser should have rejected this.
91        (ObjectType::Role, UnresolvedObjectName::Role(_)) => {
92            bail_internal!("cannot ALTER OWNER of a role")
93        }
94        (
95            object_type @ ObjectType::Cluster
96            | object_type @ ObjectType::ClusterReplica
97            | object_type @ ObjectType::Database
98            | object_type @ ObjectType::Schema
99            | object_type @ ObjectType::Role,
100            name,
101        )
102        | (
103            object_type,
104            name @ UnresolvedObjectName::Cluster(_)
105            | name @ UnresolvedObjectName::ClusterReplica(_)
106            | name @ UnresolvedObjectName::Database(_)
107            | name @ UnresolvedObjectName::Schema(_)
108            | name @ UnresolvedObjectName::NetworkPolicy(_)
109            | name @ UnresolvedObjectName::QueryPolicy(_)
110            | name @ UnresolvedObjectName::Role(_),
111        ) => {
112            // The parser should not have produced this combination.
113            bail_internal!("invalid object type '{object_type}' for ALTER OWNER with name {name}")
114        }
115        (object_type, UnresolvedObjectName::Item(name)) => {
116            plan_alter_item_owner(scx, object_type, if_exists, name, new_owner.id)
117        }
118    }
119}
120
121fn plan_alter_cluster_owner(
122    scx: &StatementContext,
123    if_exists: bool,
124    name: Ident,
125    new_owner: RoleId,
126) -> Result<Plan, PlanError> {
127    match resolve_cluster(scx, &name, if_exists)? {
128        Some(cluster) => Ok(Plan::AlterOwner(AlterOwnerPlan {
129            id: ObjectId::Cluster(cluster.id()),
130            object_type: ObjectType::Cluster,
131            new_owner,
132        })),
133        None => {
134            scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
135                name: name.to_ast_string_simple(),
136                object_type: ObjectType::Cluster,
137            });
138            Ok(Plan::AlterNoop(AlterNoopPlan {
139                object_type: ObjectType::Cluster,
140            }))
141        }
142    }
143}
144
145fn plan_alter_database_owner(
146    scx: &StatementContext,
147    if_exists: bool,
148    name: UnresolvedDatabaseName,
149    new_owner: RoleId,
150) -> Result<Plan, PlanError> {
151    match resolve_database(scx, &name, if_exists)? {
152        Some(database) => Ok(Plan::AlterOwner(AlterOwnerPlan {
153            id: ObjectId::Database(database.id()),
154            object_type: ObjectType::Database,
155            new_owner,
156        })),
157        None => {
158            scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
159                name: name.to_ast_string_simple(),
160                object_type: ObjectType::Database,
161            });
162
163            Ok(Plan::AlterNoop(AlterNoopPlan {
164                object_type: ObjectType::Database,
165            }))
166        }
167    }
168}
169
170fn plan_alter_schema_owner(
171    scx: &StatementContext,
172    if_exists: bool,
173    name: UnresolvedSchemaName,
174    new_owner: RoleId,
175) -> Result<Plan, PlanError> {
176    // Special case for mz_temp: with lazy temporary schema creation, the temp
177    // schema may not exist yet, but we still need to return the correct error.
178    // Check the schema name directly against MZ_TEMP_SCHEMA.
179    let normalized = crate::normalize::unresolved_schema_name(name.clone())?;
180    if normalized.database.is_none() && normalized.schema == mz_repr::namespaces::MZ_TEMP_SCHEMA {
181        sql_bail!("cannot alter schema {name} because it is a temporary schema",)
182    }
183
184    match resolve_schema(scx, name.clone(), if_exists)? {
185        Some((database_spec, schema_spec)) => {
186            if let ResolvedDatabaseSpecifier::Ambient = database_spec {
187                sql_bail!(
188                    "cannot alter schema {name} because it is required by the database system",
189                );
190            }
191            if let SchemaSpecifier::Temporary = schema_spec {
192                sql_bail!("cannot alter schema {name} because it is a temporary schema",)
193            }
194            Ok(Plan::AlterOwner(AlterOwnerPlan {
195                id: ObjectId::Schema((database_spec, schema_spec)),
196                object_type: ObjectType::Schema,
197                new_owner,
198            }))
199        }
200        None => {
201            scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
202                name: name.to_ast_string_simple(),
203                object_type: ObjectType::Schema,
204            });
205
206            Ok(Plan::AlterNoop(AlterNoopPlan {
207                object_type: ObjectType::Schema,
208            }))
209        }
210    }
211}
212
213fn plan_alter_item_owner(
214    scx: &StatementContext,
215    object_type: ObjectType,
216    if_exists: bool,
217    name: UnresolvedItemName,
218    new_owner: RoleId,
219) -> Result<Plan, PlanError> {
220    let resolved = match resolve_item_or_type(scx, object_type, name.clone(), if_exists) {
221        Ok(r) => r,
222        // Return a more helpful error on `DROP VIEW <materialized-view>`.
223        Err(PlanError::MismatchedObjectType {
224            name,
225            is_type: ObjectType::MaterializedView,
226            expected_type: ObjectType::View,
227        }) => {
228            return Err(PlanError::AlterViewOnMaterializedView(name.to_string()));
229        }
230        e => e?,
231    };
232
233    match resolved {
234        Some(item) => {
235            if item.id().is_system() {
236                sql_bail!(
237                    "cannot alter item {} because it is required by the database system",
238                    scx.catalog.resolve_full_name(item.name()),
239                );
240            }
241
242            Ok(Plan::AlterOwner(AlterOwnerPlan {
243                id: ObjectId::Item(item.id()),
244                object_type,
245                new_owner,
246            }))
247        }
248        None => {
249            scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
250                name: name.to_ast_string_simple(),
251                object_type,
252            });
253
254            Ok(Plan::AlterNoop(AlterNoopPlan { object_type }))
255        }
256    }
257}
258
259fn plan_alter_network_policy_owner(
260    scx: &StatementContext,
261    if_exists: bool,
262    name: Ident,
263    new_owner: RoleId,
264) -> Result<Plan, PlanError> {
265    match resolve_network_policy(scx, name.clone(), if_exists)? {
266        Some(policy_id) => Ok(Plan::AlterOwner(AlterOwnerPlan {
267            id: ObjectId::NetworkPolicy(policy_id.id),
268            object_type: ObjectType::NetworkPolicy,
269            new_owner,
270        })),
271        None => {
272            scx.catalog.add_notice(PlanNotice::ObjectDoesNotExist {
273                name: name.to_ast_string_simple(),
274                object_type: ObjectType::NetworkPolicy,
275            });
276
277            Ok(Plan::AlterNoop(AlterNoopPlan {
278                object_type: ObjectType::NetworkPolicy,
279            }))
280        }
281    }
282}
283
284pub fn describe_grant_role(
285    _: &StatementContext,
286    _: GrantRoleStatement<Aug>,
287) -> Result<StatementDesc, PlanError> {
288    Ok(StatementDesc::new(None))
289}
290
291pub fn plan_grant_role(
292    scx: &StatementContext,
293    GrantRoleStatement {
294        role_names,
295        member_names,
296    }: GrantRoleStatement<Aug>,
297) -> Result<Plan, PlanError> {
298    // In PostgreSQL, the grantor must either be a role with ADMIN OPTION on the role being granted,
299    // or the bootstrap superuser. We do not have ADMIN OPTION implemented and 'mz_system' is our
300    // equivalent of the bootstrap superuser. Therefore the grantor is always 'mz_system'.
301    // For more details see:
302    // https://github.com/postgres/postgres/blob/064eb89e83ea0f59426c92906329f1e6c423dfa4/src/backend/commands/user.c#L2180-L2238
303    let grantor_id = scx
304        .catalog
305        .resolve_role(&SYSTEM_USER.name)
306        .expect("system user must exist")
307        .id();
308    Ok(Plan::GrantRole(GrantRolePlan {
309        role_ids: role_names
310            .into_iter()
311            .map(|role_name| role_name.id)
312            .collect(),
313        member_ids: member_names
314            .into_iter()
315            .map(|member_name| member_name.id)
316            .collect(),
317        grantor_id,
318    }))
319}
320
321pub fn describe_revoke_role(
322    _: &StatementContext,
323    _: RevokeRoleStatement<Aug>,
324) -> Result<StatementDesc, PlanError> {
325    Ok(StatementDesc::new(None))
326}
327
328pub fn plan_revoke_role(
329    scx: &StatementContext,
330    RevokeRoleStatement {
331        role_names,
332        member_names,
333    }: RevokeRoleStatement<Aug>,
334) -> Result<Plan, PlanError> {
335    // In PostgreSQL, the same role membership can be granted multiple times by different grantors.
336    // When revoking a role membership, only the membership granted by the specified grantor is
337    // revoked. The grantor must either be a role with ADMIN OPTION on the role being granted,
338    // or the bootstrap superuser. We do not have ADMIN OPTION implemented and 'mz_system' is our
339    // equivalent of the bootstrap superuser. Therefore the grantor is always 'mz_system'.
340    // For more details see:
341    // https://github.com/postgres/postgres/blob/064eb89e83ea0f59426c92906329f1e6c423dfa4/src/backend/commands/user.c#L2180-L2238
342    let grantor_id = scx
343        .catalog
344        .resolve_role(&SYSTEM_USER.name)
345        .expect("system user must exist")
346        .id();
347    Ok(Plan::RevokeRole(RevokeRolePlan {
348        role_ids: role_names
349            .into_iter()
350            .map(|role_name| role_name.id)
351            .collect(),
352        member_ids: member_names
353            .into_iter()
354            .map(|member_name| member_name.id)
355            .collect(),
356        grantor_id,
357    }))
358}
359
360pub fn describe_grant_privileges(
361    _: &StatementContext,
362    _: GrantPrivilegesStatement<Aug>,
363) -> Result<StatementDesc, PlanError> {
364    Ok(StatementDesc::new(None))
365}
366
367pub fn plan_grant_privileges(
368    scx: &StatementContext,
369    GrantPrivilegesStatement {
370        privileges,
371        target,
372        roles,
373    }: GrantPrivilegesStatement<Aug>,
374) -> Result<Plan, PlanError> {
375    if matches!(
376        &target,
377        GrantTargetSpecification::Object {
378            object_type: crate::ast::ObjectType::QueryPolicy,
379            ..
380        }
381    ) {
382        scx.require_feature_flag(&crate::session::vars::ENABLE_QUERY_POLICIES)?;
383    }
384    let plan = plan_update_privilege(scx, privileges, target, roles)?;
385    Ok(Plan::GrantPrivileges(plan.into()))
386}
387
388pub fn describe_revoke_privileges(
389    _: &StatementContext,
390    _: RevokePrivilegesStatement<Aug>,
391) -> Result<StatementDesc, PlanError> {
392    Ok(StatementDesc::new(None))
393}
394
395pub fn plan_revoke_privileges(
396    scx: &StatementContext,
397    RevokePrivilegesStatement {
398        privileges,
399        target,
400        roles,
401    }: RevokePrivilegesStatement<Aug>,
402) -> Result<Plan, PlanError> {
403    let plan = plan_update_privilege(scx, privileges, target, roles)?;
404    Ok(Plan::RevokePrivileges(plan.into()))
405}
406
407struct UpdatePrivilegesPlan {
408    update_privileges: Vec<UpdatePrivilege>,
409    grantees: Vec<RoleId>,
410}
411
412impl From<UpdatePrivilegesPlan> for GrantPrivilegesPlan {
413    fn from(
414        UpdatePrivilegesPlan {
415            update_privileges,
416            grantees,
417        }: UpdatePrivilegesPlan,
418    ) -> GrantPrivilegesPlan {
419        GrantPrivilegesPlan {
420            update_privileges,
421            grantees,
422        }
423    }
424}
425
426impl From<UpdatePrivilegesPlan> for RevokePrivilegesPlan {
427    fn from(
428        UpdatePrivilegesPlan {
429            update_privileges,
430            grantees,
431        }: UpdatePrivilegesPlan,
432    ) -> RevokePrivilegesPlan {
433        RevokePrivilegesPlan {
434            update_privileges,
435            revokees: grantees,
436        }
437    }
438}
439
440fn plan_update_privilege(
441    scx: &StatementContext,
442    privileges: PrivilegeSpecification,
443    target: GrantTargetSpecification<Aug>,
444    roles: Vec<ResolvedRoleName>,
445) -> Result<UpdatePrivilegesPlan, PlanError> {
446    let (object_type, target_ids) = match target {
447        GrantTargetSpecification::Object {
448            object_type,
449            object_spec_inner,
450        } => {
451            fn object_type_filter(
452                object_id: &ObjectId,
453                object_type: &ObjectType,
454                scx: &StatementContext,
455            ) -> bool {
456                if object_type == &ObjectType::Table {
457                    scx.get_object_type(object_id).is_relation()
458                } else {
459                    object_type == &scx.get_object_type(object_id)
460                }
461            }
462            let object_type = object_type.into();
463            let object_ids: Vec<ObjectId> = match object_spec_inner {
464                GrantTargetSpecificationInner::All(GrantTargetAllSpecification::All) => {
465                    let cluster_ids = scx
466                        .catalog
467                        .get_clusters()
468                        .into_iter()
469                        .map(|cluster| cluster.id().into());
470                    let database_ids = scx
471                        .catalog
472                        .get_databases()
473                        .into_iter()
474                        .map(|database| database.id().into());
475                    let schema_ids = scx
476                        .catalog
477                        .get_schemas()
478                        .into_iter()
479                        .filter(|schema| !schema.id().is_temporary())
480                        .map(|schema| (schema.database().clone(), schema.id().clone()).into());
481                    let item_ids = scx
482                        .catalog
483                        .get_items()
484                        .into_iter()
485                        .map(|item| item.id().into());
486                    let network_policy_ids = scx
487                        .catalog
488                        .get_network_policies()
489                        .into_iter()
490                        .map(|network_policy| ObjectId::NetworkPolicy(network_policy.id()));
491                    let query_policy_ids = scx
492                        .catalog
493                        .get_query_policies()
494                        .into_iter()
495                        .map(|policy| ObjectId::QueryPolicy(policy.id()));
496                    cluster_ids
497                        .chain(database_ids)
498                        .chain(schema_ids)
499                        .chain(item_ids)
500                        .chain(network_policy_ids)
501                        .chain(query_policy_ids)
502                        .filter(|object_id| object_type_filter(object_id, &object_type, scx))
503                        .filter(|object_id| object_id.is_user())
504                        .collect()
505                }
506                GrantTargetSpecificationInner::All(GrantTargetAllSpecification::AllDatabases {
507                    databases,
508                }) => {
509                    let schema_ids = databases
510                        .iter()
511                        .map(|database| scx.get_database(database.database_id()))
512                        .flat_map(|database| database.schemas().into_iter())
513                        .filter(|schema| !schema.id().is_temporary())
514                        .map(|schema| (schema.database().clone(), schema.id().clone()).into());
515
516                    let item_ids = databases
517                        .iter()
518                        .map(|database| scx.get_database(database.database_id()))
519                        .flat_map(|database| database.schemas().into_iter())
520                        .flat_map(|schema| schema.item_ids())
521                        .map(|item_id| item_id.into());
522
523                    item_ids
524                        .chain(schema_ids)
525                        .filter(|object_id| object_type_filter(object_id, &object_type, scx))
526                        .collect()
527                }
528                GrantTargetSpecificationInner::All(GrantTargetAllSpecification::AllSchemas {
529                    schemas,
530                }) => {
531                    let mut ids = Vec::new();
532                    for schema in schemas {
533                        let schema = match schema.schema_spec() {
534                            // The temporary schema is created lazily on the connection's
535                            // first temporary item, and `get_schema` panics until then.
536                            SchemaSpecifier::Temporary => scx.catalog.resolve_schema_in_database(
537                                &ResolvedDatabaseSpecifier::Ambient,
538                                mz_repr::namespaces::MZ_TEMP_SCHEMA,
539                            )?,
540                            SchemaSpecifier::Id(_) => {
541                                scx.get_schema(schema.database_spec(), schema.schema_spec())
542                            }
543                        };
544                        ids.extend(
545                            schema.item_ids().map(ObjectId::from).filter(|object_id| {
546                                object_type_filter(object_id, &object_type, scx)
547                            }),
548                        );
549                    }
550                    ids
551                }
552                GrantTargetSpecificationInner::Objects { names } => {
553                    let mut ids = Vec::with_capacity(names.len());
554                    for name in names {
555                        ids.push(
556                            // Name resolution should have rejected invalid objects.
557                            name.try_into()
558                                .map_err(|e| internal_err!("invalid object name: {}", e))?,
559                        );
560                    }
561                    ids
562                }
563            };
564            let target_ids = object_ids.into_iter().map(|id| id.into()).collect();
565            (SystemObjectType::Object(object_type), target_ids)
566        }
567        GrantTargetSpecification::System => {
568            (SystemObjectType::System, vec![SystemObjectId::System])
569        }
570    };
571
572    let mut update_privileges = Vec::with_capacity(target_ids.len());
573
574    for target_id in target_ids {
575        // Temporary schemas cannot have privileges granted or revoked - they are
576        // connection-specific and transient. With lazy temporary schema creation,
577        // the temp schema may not exist yet, but we still need to return the correct error.
578        if let SystemObjectId::Object(ObjectId::Schema((_, SchemaSpecifier::Temporary))) =
579            &target_id
580        {
581            sql_bail!(
582                "cannot grant or revoke privileges on schema {} because it is a temporary schema",
583                mz_repr::namespaces::MZ_TEMP_SCHEMA
584            );
585        }
586
587        // The actual type of the object.
588        let actual_object_type = scx.get_system_object_type(&target_id);
589        // The type used for privileges, for example if the actual type is a view, the reference
590        // type is table.
591        let mut reference_object_type = actual_object_type.clone();
592
593        if let SystemObjectId::Object(ObjectId::Item(id)) = &target_id {
594            let item = scx.get_item(id);
595            let item_type: ObjectType = item.item_type().into();
596            if (item_type == ObjectType::View
597                || item_type == ObjectType::MaterializedView
598                || item_type == ObjectType::Source)
599                && object_type == SystemObjectType::Object(ObjectType::Table)
600            {
601                // This is an expected mis-match to match PostgreSQL semantics.
602                reference_object_type = SystemObjectType::Object(ObjectType::Table);
603            } else if SystemObjectType::Object(item_type) != object_type {
604                let object_name = scx.catalog.resolve_full_name(item.name()).to_string();
605                return Err(PlanError::InvalidObjectType {
606                    expected_type: object_type,
607                    actual_type: actual_object_type,
608                    object_name,
609                });
610            }
611        }
612
613        // Compute the ACL mode against the reference type so that, for example,
614        // `REVOKE ALL ON TABLE <view>` expands to the full TABLE privilege set
615        // (SELECT|INSERT|UPDATE|DELETE) rather than only the privileges valid
616        // for a view on its own (SELECT).
617        let acl_mode = privilege_spec_to_acl_mode(scx, &privileges, reference_object_type);
618        let acl_from_all = matches!(privileges, PrivilegeSpecification::All);
619
620        let all_object_privileges = scx.catalog.all_object_privileges(reference_object_type);
621        let invalid_privileges = acl_mode.difference(all_object_privileges);
622        if !invalid_privileges.is_empty() {
623            let object_description =
624                ErrorMessageObjectDescription::from_sys_id(&target_id, scx.catalog);
625            return Err(PlanError::InvalidPrivilegeTypes {
626                invalid_privileges,
627                object_description,
628            });
629        }
630
631        // In PostgreSQL, the grantor must always be either the object owner or some role that has been
632        // been explicitly granted grant options. In Materialize, we haven't implemented grant options
633        // so the grantor is always the object owner.
634        //
635        // For more details see:
636        // https://github.com/postgres/postgres/blob/78d5952dd0e66afc4447eec07f770991fa406cce/src/backend/utils/adt/acl.c#L5154-L5246
637        let grantor = match &target_id {
638            SystemObjectId::Object(object_id) => scx
639                .catalog
640                .get_owner_id(object_id)
641                .ok_or_else(|| sql_err!("cannot revoke privileges on objects without owners"))?,
642            SystemObjectId::System => scx.catalog.mz_system_role_id(),
643        };
644
645        update_privileges.push(UpdatePrivilege {
646            acl_mode,
647            target_id,
648            grantor,
649            acl_from_all,
650        });
651    }
652
653    let grantees = roles.into_iter().map(|role| role.id).collect();
654
655    Ok(UpdatePrivilegesPlan {
656        update_privileges,
657        grantees,
658    })
659}
660
661fn privilege_spec_to_acl_mode(
662    scx: &StatementContext,
663    privilege_spec: &PrivilegeSpecification,
664    object_type: SystemObjectType,
665) -> AclMode {
666    match privilege_spec {
667        PrivilegeSpecification::All => scx.catalog.all_object_privileges(object_type),
668        PrivilegeSpecification::Privileges(privileges) => privileges
669            .into_iter()
670            .map(|privilege| privilege_to_acl_mode(privilege.clone()))
671            // PostgreSQL doesn't care about duplicate privileges, so we don't either.
672            .fold(AclMode::empty(), |accum, acl_mode| accum.union(acl_mode)),
673    }
674}
675
676fn privilege_to_acl_mode(privilege: Privilege) -> AclMode {
677    match privilege {
678        Privilege::SELECT => AclMode::SELECT,
679        Privilege::INSERT => AclMode::INSERT,
680        Privilege::UPDATE => AclMode::UPDATE,
681        Privilege::DELETE => AclMode::DELETE,
682        Privilege::USAGE => AclMode::USAGE,
683        Privilege::CREATE => AclMode::CREATE,
684        Privilege::CREATEROLE => AclMode::CREATE_ROLE,
685        Privilege::CREATEDB => AclMode::CREATE_DB,
686        Privilege::CREATECLUSTER => AclMode::CREATE_CLUSTER,
687        Privilege::CREATENETWORKPOLICY => AclMode::CREATE_NETWORK_POLICY,
688        Privilege::CREATEQUERYPOLICY => AclMode::CREATE_QUERY_POLICY,
689    }
690}
691
692pub fn describe_alter_default_privileges(
693    _: &StatementContext,
694    _: AlterDefaultPrivilegesStatement<Aug>,
695) -> Result<StatementDesc, PlanError> {
696    Ok(StatementDesc::new(None))
697}
698
699pub fn plan_alter_default_privileges(
700    scx: &StatementContext,
701    AlterDefaultPrivilegesStatement {
702        target_roles,
703        target_objects,
704        grant_or_revoke,
705    }: AlterDefaultPrivilegesStatement<Aug>,
706) -> Result<Plan, PlanError> {
707    let object_type: ObjectType = (*grant_or_revoke.object_type()).into();
708    if object_type == ObjectType::QueryPolicy
709        && matches!(grant_or_revoke, AbbreviatedGrantOrRevokeStatement::Grant(_))
710    {
711        scx.require_feature_flag(&crate::session::vars::ENABLE_QUERY_POLICIES)?;
712    }
713    match object_type {
714        ObjectType::View | ObjectType::MaterializedView | ObjectType::Source => sql_bail!(
715            "{object_type}S is not valid for ALTER DEFAULT PRIVILEGES, use TABLES instead"
716        ),
717        ObjectType::Sink
718        | ObjectType::MetricSink
719        | ObjectType::ClusterReplica
720        | ObjectType::Role
721        | ObjectType::Func => {
722            sql_bail!("{object_type}S do not have privileges")
723        }
724        ObjectType::Cluster
725        | ObjectType::Database
726        | ObjectType::NetworkPolicy
727        | ObjectType::QueryPolicy
728            if matches!(
729                target_objects,
730                GrantTargetAllSpecification::AllDatabases { .. }
731            ) =>
732        {
733            sql_bail!("cannot specify {object_type}S and IN DATABASE")
734        }
735
736        ObjectType::Cluster
737        | ObjectType::Database
738        | ObjectType::Schema
739        | ObjectType::NetworkPolicy
740        | ObjectType::QueryPolicy
741            if matches!(
742                target_objects,
743                GrantTargetAllSpecification::AllSchemas { .. }
744            ) =>
745        {
746            sql_bail!("cannot specify {object_type}S and IN SCHEMA")
747        }
748        ObjectType::Table
749        | ObjectType::Index
750        | ObjectType::Type
751        | ObjectType::Secret
752        | ObjectType::Connection
753        | ObjectType::Cluster
754        | ObjectType::Database
755        | ObjectType::Schema
756        | ObjectType::NetworkPolicy
757        | ObjectType::QueryPolicy => {}
758    }
759
760    let acl_mode = privilege_spec_to_acl_mode(
761        scx,
762        grant_or_revoke.privileges(),
763        SystemObjectType::Object(object_type),
764    );
765    let all_object_privileges = scx
766        .catalog
767        .all_object_privileges(SystemObjectType::Object(object_type));
768    let invalid_privileges = acl_mode.difference(all_object_privileges);
769    if !invalid_privileges.is_empty() {
770        let object_description =
771            ErrorMessageObjectDescription::from_object_type(SystemObjectType::Object(object_type));
772        return Err(PlanError::InvalidPrivilegeTypes {
773            invalid_privileges,
774            object_description,
775        });
776    }
777
778    let target_roles = match target_roles {
779        TargetRoleSpecification::Roles(roles) => roles.into_iter().map(|role| role.id).collect(),
780        TargetRoleSpecification::AllRoles => vec![RoleId::Public],
781    };
782    let mut privilege_objects = Vec::with_capacity(target_roles.len() * target_objects.len());
783    for target_role in target_roles {
784        match &target_objects {
785            GrantTargetAllSpecification::All => privilege_objects.push(DefaultPrivilegeObject {
786                role_id: target_role,
787                database_id: None,
788                schema_id: None,
789                object_type,
790            }),
791            GrantTargetAllSpecification::AllDatabases { databases } => {
792                for database in databases {
793                    privilege_objects.push(DefaultPrivilegeObject {
794                        role_id: target_role,
795                        database_id: Some(*database.database_id()),
796                        schema_id: None,
797                        object_type,
798                    });
799                }
800            }
801            GrantTargetAllSpecification::AllSchemas { schemas } => {
802                for schema in schemas {
803                    privilege_objects.push(DefaultPrivilegeObject {
804                        role_id: target_role,
805                        database_id: schema.database_spec().id(),
806                        schema_id: Some(schema.schema_spec().into()),
807                        object_type,
808                    });
809                }
810            }
811        }
812    }
813
814    let privilege_acl_items = grant_or_revoke
815        .roles()
816        .into_iter()
817        .map(|grantee| DefaultPrivilegeAclItem {
818            grantee: grantee.id,
819            acl_mode,
820        })
821        .collect();
822
823    let is_grant = match grant_or_revoke {
824        AbbreviatedGrantOrRevokeStatement::Grant(_) => true,
825        AbbreviatedGrantOrRevokeStatement::Revoke(_) => false,
826    };
827
828    Ok(Plan::AlterDefaultPrivileges(AlterDefaultPrivilegesPlan {
829        privilege_objects,
830        privilege_acl_items,
831        is_grant,
832    }))
833}
834
835pub fn describe_reassign_owned(
836    _: &StatementContext,
837    _: ReassignOwnedStatement<Aug>,
838) -> Result<StatementDesc, PlanError> {
839    Ok(StatementDesc::new(None))
840}
841
842pub fn plan_reassign_owned(
843    scx: &StatementContext,
844    ReassignOwnedStatement {
845        old_roles,
846        new_role,
847    }: ReassignOwnedStatement<Aug>,
848) -> Result<Plan, PlanError> {
849    let old_roles: BTreeSet<_> = old_roles.into_iter().map(|role| role.id).collect();
850    let mut reassign_ids: Vec<ObjectId> = Vec::new();
851
852    // Replicas
853    for replica in scx.catalog.get_cluster_replicas() {
854        if old_roles.contains(&replica.owner_id()) {
855            reassign_ids.push((replica.cluster_id(), replica.replica_id()).into());
856        }
857    }
858    // Clusters
859    for cluster in scx.catalog.get_clusters() {
860        if old_roles.contains(&cluster.owner_id()) {
861            reassign_ids.push(cluster.id().into());
862        }
863    }
864    // Items
865    for item in scx.catalog.get_items() {
866        if old_roles.contains(&item.owner_id()) {
867            reassign_ids.push(item.id().into());
868        }
869    }
870    // Schemas
871    for schema in scx.catalog.get_schemas() {
872        if !schema.id().is_temporary() {
873            if old_roles.contains(&schema.owner_id()) {
874                reassign_ids.push((*schema.database(), *schema.id()).into())
875            }
876        }
877    }
878    // Databases
879    for database in scx.catalog.get_databases() {
880        if old_roles.contains(&database.owner_id()) {
881            reassign_ids.push(database.id().into());
882        }
883    }
884    // Network policies
885    for network_policy in scx.catalog.get_network_policies() {
886        if old_roles.contains(&network_policy.owner_id()) {
887            reassign_ids.push(ObjectId::NetworkPolicy(network_policy.id()));
888        }
889    }
890    for policy in scx.catalog.get_query_policies() {
891        if old_roles.contains(&policy.owner_id()) {
892            reassign_ids.push(ObjectId::QueryPolicy(policy.id()));
893        }
894    }
895
896    let system_ids: Vec<_> = reassign_ids.iter().filter(|id| id.is_system()).collect();
897    if !system_ids.is_empty() {
898        let mut owners = system_ids
899            .into_iter()
900            .filter_map(|object_id| scx.catalog.get_owner_id(object_id))
901            .collect::<BTreeSet<_>>()
902            .into_iter()
903            .map(|role_id| scx.catalog.get_role(&role_id).name().quoted());
904        sql_bail!(
905            "cannot reassign objects owned by role {} because they are required by the database system",
906            owners.join(", "),
907        );
908    }
909
910    Ok(Plan::ReassignOwned(ReassignOwnedPlan {
911        old_roles: old_roles.into_iter().collect(),
912        new_role: new_role.id,
913        reassign_ids,
914    }))
915}