Skip to main content

risingwave_meta/controller/
user.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{HashMap, HashSet};
16
17use itertools::Itertools;
18use risingwave_common::catalog::{DEFAULT_SUPER_USER, DEFAULT_SUPER_USER_FOR_PG};
19use risingwave_meta_model::object::ObjectType;
20use risingwave_meta_model::prelude::{Object, User, UserDefaultPrivilege, UserPrivilege};
21use risingwave_meta_model::user_privilege::Action;
22use risingwave_meta_model::{
23    AuthInfo, DatabaseId, DefaultPrivilegeId, PrivilegeId, SchemaId, UserId, object, user,
24    user_default_privilege, user_privilege,
25};
26use risingwave_pb::common::PbObjectType;
27use risingwave_pb::meta::subscribe_response::{
28    Info as NotificationInfo, Operation as NotificationOperation,
29};
30use risingwave_pb::user::update_user_request::PbUpdateField;
31use risingwave_pb::user::{PbAction, PbGrantPrivilege, PbUserInfo};
32use sea_orm::ActiveValue::Set;
33use sea_orm::sea_query::{OnConflict, SimpleExpr, Value};
34use sea_orm::{
35    ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, PaginatorTrait, QueryFilter,
36    QuerySelect, TransactionTrait,
37};
38
39use crate::controller::catalog::CatalogController;
40use crate::controller::utils::{
41    PartialUserPrivilege, check_user_name_duplicate, ensure_object_id,
42    ensure_privileges_not_referred, ensure_user_id, extract_grant_obj_id,
43    get_iceberg_related_object_ids, get_index_state_tables_by_table_id, get_internal_tables_by_id,
44    get_object_owner, get_referring_privileges_cascade, get_user_privilege, list_user_info_by_ids,
45    upsert_user_privileges,
46};
47use crate::manager::{FrontendNotificationBatch, NotificationVersion};
48use crate::{MetaError, MetaResult};
49
50impl CatalogController {
51    pub(crate) fn add_users_update_notifications(
52        notifications: &mut FrontendNotificationBatch<'_>,
53        user_infos: Vec<PbUserInfo>,
54    ) {
55        for info in user_infos {
56            notifications.add(NotificationOperation::Update, NotificationInfo::User(info));
57        }
58    }
59
60    pub(crate) async fn notify_users_update(
61        &self,
62        user_infos: Vec<PbUserInfo>,
63    ) -> Option<NotificationVersion> {
64        let mut notifications = self.frontend_notification_batch();
65        Self::add_users_update_notifications(&mut notifications, user_infos);
66        notifications.publish().await
67    }
68
69    pub async fn create_user(&self, pb_user: PbUserInfo) -> MetaResult<NotificationVersion> {
70        let inner = self.inner.write().await;
71        let txn = inner.db.begin().await?;
72        check_user_name_duplicate(&pb_user.name, &txn).await?;
73
74        let grant_privileges = pb_user.grant_privileges.clone();
75        let user: user::ActiveModel = pb_user.into();
76        let user = user.insert(&txn).await?;
77
78        if !grant_privileges.is_empty() {
79            let mut privileges = vec![];
80            for gp in &grant_privileges {
81                let id = extract_grant_obj_id(gp.get_object()?);
82                for action_with_opt in &gp.action_with_opts {
83                    privileges.push(user_privilege::ActiveModel {
84                        user_id: Set(user.user_id),
85                        oid: Set(id),
86                        granted_by: Set(action_with_opt.granted_by as _),
87                        action: Set(action_with_opt.get_action()?.into()),
88                        with_grant_option: Set(action_with_opt.with_grant_option),
89                        ..Default::default()
90                    });
91                }
92            }
93            UserPrivilege::insert_many(privileges).exec(&txn).await?;
94        }
95        txn.commit().await?;
96
97        let mut user_info: PbUserInfo = user.into();
98        user_info.grant_privileges = grant_privileges;
99        let version = self
100            .notify_frontend(
101                NotificationOperation::Add,
102                NotificationInfo::User(user_info),
103            )
104            .await;
105
106        Ok(version)
107    }
108
109    pub async fn update_user(
110        &self,
111        update_user: PbUserInfo,
112        update_fields: &[PbUpdateField],
113    ) -> MetaResult<NotificationVersion> {
114        let inner = self.inner.write().await;
115        let txn = inner.db.begin().await?;
116        let rename_flag = update_fields.contains(&PbUpdateField::Rename);
117        if rename_flag {
118            check_user_name_duplicate(&update_user.name, &txn).await?;
119        }
120
121        let user = User::find_by_id(update_user.id as UserId)
122            .one(&txn)
123            .await?
124            .ok_or_else(|| MetaError::catalog_id_not_found("user", update_user.id))?;
125        let mut user = user.into_active_model();
126        update_fields.iter().for_each(|&field| match field {
127            PbUpdateField::Unspecified => unreachable!(),
128            PbUpdateField::Super => user.is_super = Set(update_user.is_super),
129            PbUpdateField::Login => user.can_login = Set(update_user.can_login),
130            PbUpdateField::CreateDb => user.can_create_db = Set(update_user.can_create_db),
131            PbUpdateField::CreateUser => user.can_create_user = Set(update_user.can_create_user),
132            PbUpdateField::AuthInfo => {
133                user.auth_info = Set(update_user.auth_info.as_ref().map(AuthInfo::from))
134            }
135            PbUpdateField::Rename => user.name = Set(update_user.name.clone()),
136            PbUpdateField::Admin => user.is_admin = Set(update_user.is_admin),
137        });
138
139        let user = user.update(&txn).await?;
140        let mut user_info: PbUserInfo = user.into();
141        user_info.grant_privileges = get_user_privilege(user_info.id as _, &txn).await?;
142        txn.commit().await?;
143
144        let version = self
145            .notify_frontend(
146                NotificationOperation::Update,
147                NotificationInfo::User(user_info),
148            )
149            .await;
150
151        Ok(version)
152    }
153
154    pub async fn get_user(&self, id: UserId) -> MetaResult<user::Model> {
155        let inner = self.inner.read().await;
156        let user = User::find_by_id(id)
157            .one(&inner.db)
158            .await?
159            .ok_or_else(|| MetaError::catalog_id_not_found("user", id))?;
160        Ok(user)
161    }
162
163    #[cfg(test)]
164    pub async fn get_user_by_name(&self, name: &str) -> MetaResult<user::Model> {
165        let inner = self.inner.read().await;
166        let user = User::find()
167            .filter(user::Column::Name.eq(name))
168            .one(&inner.db)
169            .await?
170            .ok_or_else(|| anyhow::anyhow!("user {name} not found"))?;
171        Ok(user)
172    }
173
174    pub async fn drop_user(&self, user_id: UserId) -> MetaResult<NotificationVersion> {
175        let inner = self.inner.write().await;
176        let txn = inner.db.begin().await?;
177        let user = User::find_by_id(user_id)
178            .one(&txn)
179            .await?
180            .ok_or_else(|| MetaError::catalog_id_not_found("user", user_id))?;
181        if user.name == DEFAULT_SUPER_USER || user.name == DEFAULT_SUPER_USER_FOR_PG {
182            return Err(MetaError::permission_denied(format!(
183                "drop default super user {} is not allowed",
184                user.name
185            )));
186        }
187
188        // check if the user is the owner of any objects.
189        let count = Object::find()
190            .filter(object::Column::OwnerId.eq(user_id))
191            .count(&txn)
192            .await?;
193        if count != 0 {
194            return Err(MetaError::permission_denied(format!(
195                "drop user {} is not allowed, because it owns {} objects",
196                user.name, count
197            )));
198        }
199
200        // check if the user granted any privileges to other users.
201        let count = UserPrivilege::find()
202            .filter(user_privilege::Column::GrantedBy.eq(user_id))
203            .count(&txn)
204            .await?;
205        if count != 0 {
206            return Err(MetaError::permission_denied(format!(
207                "drop user {} is not allowed, because it granted {} privileges to others",
208                user.name, count
209            )));
210        }
211
212        let res = User::delete_by_id(user_id).exec(&txn).await?;
213        if res.rows_affected != 1 {
214            return Err(MetaError::catalog_id_not_found("user", user_id));
215        }
216        txn.commit().await?;
217
218        let version = self
219            .notify_frontend(
220                NotificationOperation::Delete,
221                NotificationInfo::User(PbUserInfo {
222                    id: user_id as _,
223                    ..Default::default()
224                }),
225            )
226            .await;
227
228        Ok(version)
229    }
230
231    pub async fn grant_privilege(
232        &self,
233        user_ids: Vec<UserId>,
234        new_grant_privileges: &[PbGrantPrivilege],
235        grantor: UserId,
236        with_grant_option: bool,
237    ) -> MetaResult<Option<NotificationVersion>> {
238        let inner = self.inner.write().await;
239        let txn = inner.db.begin().await?;
240        for user_id in &user_ids {
241            ensure_user_id(*user_id, &txn).await?;
242        }
243
244        let mut privileges = vec![];
245        for gp in new_grant_privileges {
246            let id = extract_grant_obj_id(gp.get_object()?);
247            let internal_table_ids = get_internal_tables_by_id(id.as_job_id(), &txn).await?;
248            let index_state_table_ids =
249                get_index_state_tables_by_table_id(id.as_table_id(), &txn).await?;
250            for action_with_opt in &gp.action_with_opts {
251                let action = action_with_opt.get_action()?.into();
252                privileges.push(user_privilege::ActiveModel {
253                    oid: Set(id),
254                    granted_by: Set(grantor),
255                    action: Set(action),
256                    with_grant_option: Set(with_grant_option),
257                    ..Default::default()
258                });
259                if action == Action::Select {
260                    privileges.extend(
261                        internal_table_ids
262                            .iter()
263                            .chain(index_state_table_ids.iter())
264                            .map(|&tid| user_privilege::ActiveModel {
265                                oid: Set(tid.as_object_id()),
266                                granted_by: Set(grantor),
267                                action: Set(Action::Select),
268                                with_grant_option: Set(with_grant_option),
269                                ..Default::default()
270                            }),
271                    );
272                    let iceberg_privilege_object_ids =
273                        get_iceberg_related_object_ids(id, &txn).await?;
274                    privileges.extend(iceberg_privilege_object_ids.iter().map(
275                        |&iceberg_object_id| user_privilege::ActiveModel {
276                            oid: Set(iceberg_object_id),
277                            granted_by: Set(grantor),
278                            action: Set(action),
279                            with_grant_option: Set(with_grant_option),
280                            ..Default::default()
281                        },
282                    ));
283                }
284            }
285        }
286
287        // check whether grantor has the privilege to grant the privilege.
288        let user = User::find_by_id(grantor)
289            .one(&txn)
290            .await?
291            .ok_or_else(|| MetaError::catalog_id_not_found("user", grantor))?;
292        let mut filtered_privileges = vec![];
293        if !user.is_super {
294            for mut privilege in privileges {
295                if grantor == get_object_owner(*privilege.oid.as_ref(), &txn).await? {
296                    filtered_privileges.push(privilege);
297                    continue;
298                }
299                let filter = user_privilege::Column::UserId
300                    .eq(grantor)
301                    .and(user_privilege::Column::Oid.eq(*privilege.oid.as_ref()))
302                    .and(user_privilege::Column::Action.eq(*privilege.action.as_ref()))
303                    .and(user_privilege::Column::WithGrantOption.eq(true));
304                let privilege_id: Option<PrivilegeId> = UserPrivilege::find()
305                    .select_only()
306                    .column(user_privilege::Column::Id)
307                    .filter(filter)
308                    .into_tuple()
309                    .one(&txn)
310                    .await?;
311                let Some(privilege_id) = privilege_id else {
312                    tracing::warn!(
313                        "user {} don't have privilege {:?} or grant option",
314                        grantor,
315                        privilege.action
316                    );
317                    continue;
318                };
319                privilege.dependent_id = Set(Some(privilege_id));
320                filtered_privileges.push(privilege);
321            }
322        } else {
323            filtered_privileges = privileges;
324        }
325
326        // insert privileges
327        let user_privileges = user_ids
328            .iter()
329            .flat_map(|user_id| {
330                filtered_privileges.iter().map(|p| {
331                    let mut p = p.clone();
332                    p.user_id = Set(*user_id);
333                    p
334                })
335            })
336            .collect_vec();
337        upsert_user_privileges(&txn, user_privileges).await?;
338
339        let user_infos = list_user_info_by_ids(user_ids, &txn).await?;
340
341        txn.commit().await?;
342
343        let version = self.notify_users_update(user_infos).await;
344        Ok(version)
345    }
346
347    pub async fn revoke_privilege(
348        &self,
349        user_ids: Vec<UserId>,
350        revoke_grant_privileges: &[PbGrantPrivilege],
351        granted_by: UserId,
352        revoke_by: UserId,
353        revoke_grant_option: bool,
354        cascade: bool,
355    ) -> MetaResult<Option<NotificationVersion>> {
356        let inner = self.inner.write().await;
357        let txn = inner.db.begin().await?;
358        for user_id in &user_ids {
359            ensure_user_id(*user_id, &txn).await?;
360        }
361        // check whether revoke has the privilege to grant the privilege.
362        let revoke_user = User::find_by_id(revoke_by)
363            .one(&txn)
364            .await?
365            .ok_or_else(|| MetaError::catalog_id_not_found("user", revoke_by))?;
366
367        // check whether user can revoke the privilege.
368        if !revoke_user.is_super && granted_by != revoke_by {
369            let granted_user_name: String = User::find_by_id(granted_by)
370                .select_only()
371                .column(user::Column::Name)
372                .into_tuple()
373                .one(&txn)
374                .await?
375                .ok_or_else(|| MetaError::catalog_id_not_found("user", granted_by))?;
376            return Err(MetaError::permission_denied(format!(
377                "user {} is not super, can't revoke privileges for {}",
378                revoke_user.name, granted_user_name
379            )));
380        }
381
382        let mut revoke_items = HashMap::new();
383        for privilege in revoke_grant_privileges {
384            let obj = extract_grant_obj_id(privilege.get_object()?);
385            let internal_table_ids = get_internal_tables_by_id(obj.as_job_id(), &txn).await?;
386            let index_state_table_ids =
387                get_index_state_tables_by_table_id(obj.as_table_id(), &txn).await?;
388            let mut include_select = false;
389            let actions = privilege
390                .action_with_opts
391                .iter()
392                .map(|ao| {
393                    let action = Action::from(ao.get_action().unwrap());
394                    if action == Action::Select {
395                        include_select = true;
396                    }
397                    action
398                })
399                .collect_vec();
400            revoke_items.insert(obj, actions);
401            if include_select {
402                revoke_items.extend(
403                    internal_table_ids
404                        .iter()
405                        .chain(index_state_table_ids.iter())
406                        .map(|&tid| (tid.as_object_id(), vec![Action::Select])),
407                );
408                let iceberg_privilege_object_ids =
409                    get_iceberg_related_object_ids(obj, &txn).await?;
410                if !iceberg_privilege_object_ids.is_empty() {
411                    revoke_items.extend(
412                        iceberg_privilege_object_ids
413                            .into_iter()
414                            .map(|iceberg_object_id| (iceberg_object_id, vec![Action::Select])),
415                    );
416                }
417            }
418        }
419
420        let filter = if !revoke_user.is_super {
421            // ensure user have grant options or is owner of the object.
422            for (obj, actions) in &revoke_items {
423                if revoke_by == get_object_owner(*obj, &txn).await? {
424                    continue;
425                }
426                let owned_actions: HashSet<Action> = UserPrivilege::find()
427                    .select_only()
428                    .column(user_privilege::Column::Action)
429                    .filter(
430                        user_privilege::Column::UserId
431                            .eq(granted_by)
432                            .and(user_privilege::Column::Oid.eq(*obj))
433                            .and(user_privilege::Column::WithGrantOption.eq(true)),
434                    )
435                    .into_tuple::<Action>()
436                    .all(&txn)
437                    .await?
438                    .into_iter()
439                    .collect();
440                if actions.iter().any(|ac| !owned_actions.contains(ac)) {
441                    return Err(MetaError::permission_denied(format!(
442                        "user {} don't have privileges {:?} or grant option",
443                        revoke_user.name, actions,
444                    )));
445                }
446            }
447
448            user_privilege::Column::GrantedBy
449                .eq(granted_by)
450                .and(user_privilege::Column::UserId.is_in(user_ids.clone()))
451        } else {
452            user_privilege::Column::UserId.is_in(user_ids.clone())
453        };
454        let mut root_user_privileges: Vec<PartialUserPrivilege> = vec![];
455        for (obj, actions) in revoke_items {
456            let filter = filter
457                .clone()
458                .and(user_privilege::Column::Oid.eq(obj))
459                .and(user_privilege::Column::Action.is_in(actions));
460            root_user_privileges.extend(
461                UserPrivilege::find()
462                    .select_only()
463                    .columns([user_privilege::Column::Id, user_privilege::Column::UserId])
464                    .filter(filter)
465                    .into_partial_model()
466                    .all(&txn)
467                    .await?,
468            );
469        }
470        if root_user_privileges.is_empty() {
471            tracing::warn!("no privilege to revoke, ignore it");
472            return Ok(None);
473        }
474
475        // check if the user granted any privileges to other users.
476        let root_privilege_ids = root_user_privileges.iter().map(|ur| ur.id).collect_vec();
477        let (all_privilege_ids, to_update_user_ids) = if !cascade {
478            ensure_privileges_not_referred(root_privilege_ids.clone(), &txn).await?;
479            (
480                root_privilege_ids.clone(),
481                root_user_privileges
482                    .iter()
483                    .map(|ur| ur.user_id)
484                    .collect_vec(),
485            )
486        } else {
487            let all_user_privileges =
488                get_referring_privileges_cascade(root_privilege_ids.clone(), &txn).await?;
489            (
490                all_user_privileges.iter().map(|ur| ur.id).collect_vec(),
491                all_user_privileges
492                    .iter()
493                    .map(|ur| ur.user_id)
494                    .collect_vec(),
495            )
496        };
497
498        if revoke_grant_option {
499            UserPrivilege::update_many()
500                .col_expr(
501                    user_privilege::Column::WithGrantOption,
502                    SimpleExpr::Value(Value::Bool(Some(false))),
503                )
504                .filter(
505                    user_privilege::Column::Id
506                        .is_in(all_privilege_ids)
507                        .and(user_privilege::Column::WithGrantOption.eq(true)),
508                )
509                .exec(&txn)
510                .await?;
511        } else {
512            // The dependent privileges will be deleted cascade.
513            UserPrivilege::delete_many()
514                .filter(user_privilege::Column::Id.is_in(root_privilege_ids))
515                .exec(&txn)
516                .await?;
517        }
518
519        let user_infos = list_user_info_by_ids(to_update_user_ids, &txn).await?;
520
521        txn.commit().await?;
522
523        Ok(self.notify_users_update(user_infos).await)
524    }
525
526    pub async fn grant_default_privileges(
527        &self,
528        user_ids: Vec<UserId>,
529        database_id: DatabaseId,
530        schema_ids: Vec<SchemaId>,
531        grantor: UserId,
532        actions: Vec<PbAction>,
533        object_type: PbObjectType,
534        grantees: Vec<UserId>,
535        with_grant_option: bool,
536    ) -> MetaResult<()> {
537        tracing::debug!(
538            ?user_ids,
539            %database_id,
540            ?schema_ids,
541            ?actions,
542            ?object_type,
543            ?grantees,
544            with_grant_option,
545            "grant default privileges",
546        );
547        let inner = self.inner.write().await;
548        let txn = inner.db.begin().await?;
549        for user_id in &user_ids {
550            ensure_user_id(*user_id, &txn).await?;
551        }
552        ensure_object_id(ObjectType::Database, database_id, &txn).await?;
553        for schema_id in &schema_ids {
554            ensure_object_id(ObjectType::Schema, *schema_id, &txn).await?;
555        }
556        for grantee in &grantees {
557            ensure_user_id(*grantee, &txn).await?;
558        }
559        if object_type == PbObjectType::Schema {
560            assert!(
561                schema_ids.is_empty(),
562                "schema_ids should be empty when object_type is Schema"
563            );
564
565            // Note that the UNIQUE constraint does not treat NULL values as equal, we cannot rely on conflict check
566            // to update it and have to check existing default privileges manually.
567            let actions = actions.iter().map(|&a| Action::from(a)).collect_vec();
568            let existing_default_privileges: HashMap<_, _> = UserDefaultPrivilege::find()
569                .select_only()
570                .columns([
571                    user_default_privilege::Column::Id,
572                    user_default_privilege::Column::UserId,
573                    user_default_privilege::Column::Grantee,
574                    user_default_privilege::Column::Action,
575                ])
576                .filter(
577                    user_default_privilege::Column::DatabaseId
578                        .eq(database_id)
579                        .and(user_default_privilege::Column::ObjectType.eq(ObjectType::Schema))
580                        .and(user_default_privilege::Column::UserId.is_in(user_ids.clone()))
581                        .and(user_default_privilege::Column::Grantee.is_in(grantees.clone()))
582                        .and(user_default_privilege::Column::Action.is_in(actions.clone())),
583                )
584                .into_tuple::<(DefaultPrivilegeId, UserId, UserId, Action)>()
585                .all(&txn)
586                .await?
587                .into_iter()
588                .map(|(id, user_id, grantee, action)| ((user_id, grantee, action), id))
589                .collect();
590
591            for user_id in user_ids {
592                for grantee in &grantees {
593                    for action in &actions {
594                        if let Some(existing_id) =
595                            existing_default_privileges.get(&(user_id, *grantee, *action))
596                            && with_grant_option
597                        {
598                            // If the default privilege already exists, we should update the grant option.
599                            UserDefaultPrivilege::update(user_default_privilege::ActiveModel {
600                                id: Set(*existing_id),
601                                with_grant_option: Set(true),
602                                granted_by: Set(grantor as _),
603                                ..Default::default()
604                            })
605                            .exec(&txn)
606                            .await?;
607                        } else {
608                            UserDefaultPrivilege::insert(user_default_privilege::ActiveModel {
609                                id: Default::default(),
610                                database_id: Set(database_id),
611                                schema_id: Set(None),
612                                object_type: Set(ObjectType::Schema),
613                                for_materialized_view: Set(false),
614                                user_id: Set(user_id),
615                                grantee: Set(*grantee),
616                                granted_by: Set(grantor as _),
617                                action: Set(*action),
618                                with_grant_option: Set(with_grant_option),
619                            })
620                            .exec(&txn)
621                            .await?;
622                        }
623                    }
624                }
625            }
626        } else {
627            let mut default_privileges = vec![];
628            for user_id in user_ids {
629                for grantee in &grantees {
630                    for action in &actions {
631                        if schema_ids.is_empty() {
632                            default_privileges.push(user_default_privilege::ActiveModel {
633                                id: Default::default(),
634                                database_id: Set(database_id),
635                                schema_id: Set(None),
636                                object_type: Set(object_type.into()),
637                                for_materialized_view: Set(object_type == PbObjectType::Mview),
638                                user_id: Set(user_id),
639                                grantee: Set(*grantee),
640                                granted_by: Set(grantor as _),
641                                action: Set((*action).into()),
642                                with_grant_option: Set(with_grant_option),
643                            });
644                            continue;
645                        }
646                        for schema_id in &schema_ids {
647                            default_privileges.push(user_default_privilege::ActiveModel {
648                                id: Default::default(),
649                                database_id: Set(database_id),
650                                schema_id: Set(Some(*schema_id)),
651                                object_type: Set(object_type.into()),
652                                for_materialized_view: Set(object_type == PbObjectType::Mview),
653                                user_id: Set(user_id),
654                                grantee: Set(*grantee),
655                                granted_by: Set(grantor as _),
656                                action: Set((*action).into()),
657                                with_grant_option: Set(with_grant_option),
658                            });
659                        }
660                    }
661                }
662            }
663
664            let mut on_conflict = OnConflict::columns([
665                user_default_privilege::Column::UserId,
666                user_default_privilege::Column::DatabaseId,
667                user_default_privilege::Column::SchemaId,
668                user_default_privilege::Column::ObjectType,
669                user_default_privilege::Column::ForMaterializedView,
670                user_default_privilege::Column::Grantee,
671                user_default_privilege::Column::Action,
672            ]);
673            if with_grant_option {
674                on_conflict.update_column(user_default_privilege::Column::WithGrantOption);
675            } else {
676                // Workaround to support MYSQL for `DO NOTHING`.
677                on_conflict.update_column(user_default_privilege::Column::UserId);
678            }
679            UserDefaultPrivilege::insert_many(default_privileges)
680                .on_conflict(on_conflict)
681                .do_nothing()
682                .exec(&txn)
683                .await?;
684        }
685
686        txn.commit().await?;
687        Ok(())
688    }
689
690    pub async fn revoke_default_privileges(
691        &self,
692        user_ids: Vec<UserId>,
693        database_id: DatabaseId,
694        schema_ids: Vec<SchemaId>,
695        actions: Vec<PbAction>,
696        object_type: PbObjectType,
697        grantees: Vec<UserId>,
698        revoke_grant_option: bool,
699    ) -> MetaResult<()> {
700        let inner = self.inner.write().await;
701        let txn = inner.db.begin().await?;
702        for user_id in &user_ids {
703            ensure_user_id(*user_id, &txn).await?;
704        }
705
706        let schema_filter = if schema_ids.is_empty() {
707            user_default_privilege::Column::SchemaId.is_null()
708        } else {
709            user_default_privilege::Column::SchemaId.is_in(schema_ids)
710        };
711        let filter = user_default_privilege::Column::DatabaseId
712            .eq(database_id)
713            .and(schema_filter)
714            .and(user_default_privilege::Column::UserId.is_in(user_ids))
715            .and(user_default_privilege::Column::ObjectType.eq(ObjectType::from(object_type)))
716            .and(user_default_privilege::Column::Grantee.is_in(grantees))
717            .and(
718                user_default_privilege::Column::Action
719                    .is_in(actions.iter().map(|&a| Action::from(a))),
720            );
721
722        if revoke_grant_option {
723            // update the `with_grant_option` field to false
724            let res = UserDefaultPrivilege::update_many()
725                .col_expr(
726                    user_default_privilege::Column::WithGrantOption,
727                    SimpleExpr::Value(Value::Bool(Some(false))),
728                )
729                .filter(filter.and(user_default_privilege::Column::WithGrantOption.eq(true)))
730                .exec(&txn)
731                .await?;
732            tracing::info!(
733                "revoke {count} grant option for default privileges",
734                count = res.rows_affected
735            );
736        } else {
737            let res = UserDefaultPrivilege::delete_many()
738                .filter(filter)
739                .exec(&txn)
740                .await?;
741            tracing::info!(
742                "revoke {count} default privileges",
743                count = res.rows_affected
744            );
745        }
746
747        txn.commit().await?;
748        Ok(())
749    }
750}
751
752#[cfg(test)]
753mod tests {
754    use risingwave_pb::user::grant_privilege::{PbActionWithGrantOption, PbObject};
755
756    use super::*;
757    use crate::manager::MetaSrvEnv;
758
759    const TEST_DATABASE_ID: DatabaseId = DatabaseId::new(1);
760    const TEST_ROOT_USER_ID: UserId = UserId::new(1);
761
762    fn make_test_user(name: &str) -> PbUserInfo {
763        PbUserInfo {
764            name: name.to_owned(),
765            ..Default::default()
766        }
767    }
768
769    fn make_privilege(
770        object: PbObject,
771        actions: &[PbAction],
772        with_grant_option: bool,
773    ) -> PbGrantPrivilege {
774        PbGrantPrivilege {
775            object: Some(object),
776            action_with_opts: actions
777                .iter()
778                .map(|&action| PbActionWithGrantOption {
779                    action: action as _,
780                    with_grant_option,
781                    ..Default::default()
782                })
783                .collect(),
784        }
785    }
786
787    #[tokio::test]
788    async fn test_user_and_privilege() -> MetaResult<()> {
789        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
790        assert_eq!(
791            mgr.grant_privilege(vec![], &[], TEST_ROOT_USER_ID, false)
792                .await?,
793            None
794        );
795        mgr.create_user(make_test_user("test_user_1")).await?;
796        mgr.create_user(make_test_user("test_user_2")).await?;
797        let user_1 = mgr.get_user_by_name("test_user_1").await?;
798        let user_2 = mgr.get_user_by_name("test_user_2").await?;
799
800        assert!(
801            mgr.create_user(make_test_user("test_user_1"))
802                .await
803                .is_err(),
804            "user_1 already exists"
805        );
806        mgr.update_user(
807            PbUserInfo {
808                id: user_1.user_id as _,
809                name: "test_user_1_new".to_owned(),
810                ..Default::default()
811            },
812            &[PbUpdateField::Rename],
813        )
814        .await?;
815        let user_1 = mgr.get_user(user_1.user_id).await?;
816        assert_eq!(user_1.name, "test_user_1_new".to_owned());
817
818        let conn_with_option = make_privilege(TEST_DATABASE_ID.into(), &[PbAction::Connect], true);
819        let create_without_option =
820            make_privilege(TEST_DATABASE_ID.into(), &[PbAction::Create], false);
821        // ROOT grant CONN with grant option to user_1.
822        mgr.grant_privilege(
823            vec![user_1.user_id],
824            std::slice::from_ref(&conn_with_option),
825            TEST_ROOT_USER_ID,
826            true,
827        )
828        .await?;
829        // ROOT grant CREATE without grant option to user_1.
830        mgr.grant_privilege(
831            vec![user_1.user_id],
832            std::slice::from_ref(&create_without_option),
833            TEST_ROOT_USER_ID,
834            false,
835        )
836        .await?;
837        // user_1 grant CONN with grant option to user_2.
838        mgr.grant_privilege(
839            vec![user_2.user_id],
840            std::slice::from_ref(&conn_with_option),
841            user_1.user_id,
842            true,
843        )
844        .await?;
845        mgr.grant_privilege(
846            vec![user_2.user_id],
847            std::slice::from_ref(&create_without_option),
848            user_1.user_id,
849            false,
850        )
851        .await?;
852
853        assert!(
854            mgr.drop_user(user_1.user_id).await.is_err(),
855            "user_1 can't be dropped"
856        );
857
858        let privilege_1 = get_user_privilege(user_1.user_id, &mgr.inner.read().await.db).await?;
859        assert_eq!(privilege_1.len(), 2);
860        assert!(
861            privilege_1
862                .iter()
863                .all(|gp| gp.object == Some(TEST_DATABASE_ID.into())
864                    && gp.action_with_opts[0].granted_by == TEST_ROOT_USER_ID)
865        );
866
867        let privilege_2 = get_user_privilege(user_2.user_id, &mgr.inner.read().await.db).await?;
868        assert_eq!(privilege_2.len(), 1);
869        assert!(
870            privilege_2
871                .iter()
872                .all(|gp| gp.object == Some(TEST_DATABASE_ID.into())
873                    && gp.action_with_opts[0].granted_by == user_1.user_id
874                    && gp.action_with_opts[0].with_grant_option)
875        );
876
877        // revoke privilege for others by non-super user.
878        assert!(
879            mgr.revoke_privilege(
880                vec![user_1.user_id],
881                std::slice::from_ref(&conn_with_option),
882                TEST_ROOT_USER_ID,
883                user_2.user_id,
884                false,
885                false
886            )
887            .await
888            .is_err(),
889            "user_2 can't revoke for user_1"
890        );
891
892        // revoke privilege without grant option.
893        assert!(
894            mgr.revoke_privilege(
895                vec![user_2.user_id],
896                std::slice::from_ref(&create_without_option),
897                user_1.user_id,
898                user_1.user_id,
899                false,
900                false
901            )
902            .await
903            .is_err(),
904            "user_2 don't have grant option for CREATE"
905        );
906
907        // revoke referred privilege in restrict mode.
908        assert!(
909            mgr.revoke_privilege(
910                vec![user_1.user_id],
911                std::slice::from_ref(&conn_with_option),
912                TEST_ROOT_USER_ID,
913                TEST_ROOT_USER_ID,
914                false,
915                false
916            )
917            .await
918            .is_err(),
919            "permission deny in restrict mode, CONN granted to user_2"
920        );
921
922        // revoke non-referred privilege in restrict mode.
923        mgr.revoke_privilege(
924            vec![user_1.user_id],
925            std::slice::from_ref(&create_without_option),
926            TEST_ROOT_USER_ID,
927            TEST_ROOT_USER_ID,
928            false,
929            false,
930        )
931        .await?;
932
933        let privilege_1 = get_user_privilege(user_1.user_id, &mgr.inner.read().await.db).await?;
934        assert_eq!(privilege_1.len(), 1);
935        assert!(
936            privilege_1
937                .iter()
938                .all(|gp| gp.object == Some(TEST_DATABASE_ID.into())
939                    && gp.action_with_opts[0].action == PbAction::Connect as i32)
940        );
941
942        // revoke grant option for referred privilege in cascade mode.
943        mgr.revoke_privilege(
944            vec![user_1.user_id],
945            std::slice::from_ref(&conn_with_option),
946            TEST_ROOT_USER_ID,
947            TEST_ROOT_USER_ID,
948            true,
949            true,
950        )
951        .await?;
952        let privilege_1 = get_user_privilege(user_1.user_id, &mgr.inner.read().await.db).await?;
953        assert_eq!(privilege_1.len(), 1);
954        assert!(
955            privilege_1
956                .iter()
957                .all(|gp| gp.object == Some(TEST_DATABASE_ID.into())
958                    && gp.action_with_opts[0].action == PbAction::Connect as i32
959                    && !gp.action_with_opts[0].with_grant_option)
960        );
961        let privilege_2 = get_user_privilege(user_2.user_id, &mgr.inner.read().await.db).await?;
962        assert_eq!(privilege_2.len(), 1);
963        assert!(
964            privilege_2
965                .iter()
966                .all(|gp| gp.object == Some(TEST_DATABASE_ID.into())
967                    && gp.action_with_opts[0].action == PbAction::Connect as i32
968                    && !gp.action_with_opts[0].with_grant_option)
969        );
970
971        // revoke referred privilege in cascade mode.
972        mgr.revoke_privilege(
973            vec![user_1.user_id],
974            std::slice::from_ref(&conn_with_option),
975            TEST_ROOT_USER_ID,
976            TEST_ROOT_USER_ID,
977            false,
978            true,
979        )
980        .await?;
981        let privilege_1 = get_user_privilege(user_1.user_id, &mgr.inner.read().await.db).await?;
982        assert!(privilege_1.is_empty());
983        let privilege_2 = get_user_privilege(user_2.user_id, &mgr.inner.read().await.db).await?;
984        assert!(privilege_2.is_empty());
985
986        mgr.drop_user(user_1.user_id).await?;
987        mgr.drop_user(user_2.user_id).await?;
988        Ok(())
989    }
990}