Skip to content

Commit

Permalink
show grants add show option
Browse files Browse the repository at this point in the history
  • Loading branch information
TCeason committed May 22, 2024
1 parent d48fee7 commit 5c2743f
Show file tree
Hide file tree
Showing 17 changed files with 95 additions and 94 deletions.
18 changes: 17 additions & 1 deletion src/query/ast/src/ast/format/ast_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2236,7 +2236,11 @@ impl<'ast> Visitor<'ast> for AstFormatVisitor {
self.children.push(node);
}

fn visit_show_grant(&mut self, principal: &'ast Option<PrincipalIdentity>) {
fn visit_show_grant(
&mut self,
principal: &'ast Option<PrincipalIdentity>,
show_options: &'ast Option<ShowOptions>,
) {
let mut children = Vec::new();
if let Some(principal) = &principal {
let principal_name = match principal {
Expand All @@ -2246,6 +2250,18 @@ impl<'ast> Visitor<'ast> for AstFormatVisitor {
let principal_format_ctx = AstFormatContext::new(principal_name);
children.push(FormatTreeNode::new(principal_format_ctx));
}
if let Some(show_options) = show_options {
if let Some(show_limit) = &show_options.show_limit {
self.visit_show_limit(show_limit);
children.push(self.children.pop().unwrap());
}
if let Some(limit) = show_options.limit {
let name = format!("Limit {}", limit);
let limit_format_ctx = AstFormatContext::new(name);
let node = FormatTreeNode::new(limit_format_ctx);
children.push(node);
}
}
let name = "ShowGrant".to_string();
let format_ctx = AstFormatContext::with_children(name, children.len());
let node = FormatTreeNode::with_children(format_ctx, children);
Expand Down
9 changes: 8 additions & 1 deletion src/query/ast/src/ast/statements/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ pub enum Statement {
Grant(GrantStmt),
ShowGrants {
principal: Option<PrincipalIdentity>,
show_options: Option<ShowOptions>,
},
Revoke(RevokeStmt),

Expand Down Expand Up @@ -605,12 +606,18 @@ impl Display for Statement {
write!(f, " '{role}'")?;
}
Statement::Grant(stmt) => write!(f, "{stmt}")?,
Statement::ShowGrants { principal } => {
Statement::ShowGrants {
principal,
show_options,
} => {
write!(f, "SHOW GRANTS")?;
if let Some(principal) = principal {
write!(f, " FOR")?;
write!(f, "{principal}")?;
}
if let Some(show_options) = show_options {
write!(f, " {show_options}")?;
}
}
Statement::Revoke(stmt) => write!(f, "{stmt}")?,
Statement::CreateUDF(stmt) => write!(f, "{stmt}")?,
Expand Down
7 changes: 6 additions & 1 deletion src/query/ast/src/ast/visitors/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,12 @@ pub trait Visitor<'ast>: Sized {

fn visit_grant(&mut self, _grant: &'ast GrantStmt) {}

fn visit_show_grant(&mut self, _principal: &'ast Option<PrincipalIdentity>) {}
fn visit_show_grant(
&mut self,
_principal: &'ast Option<PrincipalIdentity>,
_show_options: &'ast Option<ShowOptions>,
) {
}

fn visit_revoke(&mut self, _revoke: &'ast RevokeStmt) {}

Expand Down
7 changes: 6 additions & 1 deletion src/query/ast/src/ast/visitors/visitor_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,12 @@ pub trait VisitorMut: Sized {

fn visit_grant(&mut self, _grant: &mut GrantStmt) {}

fn visit_show_grant(&mut self, _principal: &mut Option<PrincipalIdentity>) {}
fn visit_show_grant(
&mut self,
_principal: &mut Option<PrincipalIdentity>,
_show_options: &mut Option<ShowOptions>,
) {
}

fn visit_revoke(&mut self, _revoke: &mut RevokeStmt) {}

Expand Down
5 changes: 4 additions & 1 deletion src/query/ast/src/ast/visitors/walk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,10 @@ pub fn walk_statement<'a, V: Visitor<'a>>(visitor: &mut V, statement: &'a Statem
role_name,
} => visitor.visit_drop_role(*if_exists, role_name),
Statement::Grant(stmt) => visitor.visit_grant(stmt),
Statement::ShowGrants { principal } => visitor.visit_show_grant(principal),
Statement::ShowGrants {
principal,
show_options,
} => visitor.visit_show_grant(principal, show_options),
Statement::Revoke(stmt) => visitor.visit_revoke(stmt),
Statement::CreateUDF(stmt) => visitor.visit_create_udf(stmt),
Statement::DropUDF {
Expand Down
5 changes: 4 additions & 1 deletion src/query/ast/src/ast/visitors/walk_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,10 @@ pub fn walk_statement_mut<V: VisitorMut>(visitor: &mut V, statement: &mut Statem
role_name,
} => visitor.visit_drop_role(*if_exists, role_name),
Statement::Grant(stmt) => visitor.visit_grant(stmt),
Statement::ShowGrants { principal } => visitor.visit_show_grant(principal),
Statement::ShowGrants {
principal,
show_options,
} => visitor.visit_show_grant(principal, show_options),
Statement::Revoke(stmt) => visitor.visit_revoke(stmt),
Statement::CreateUDF(stmt) => visitor.visit_create_udf(stmt),
Statement::DropUDF {
Expand Down
10 changes: 7 additions & 3 deletions src/query/ast/src/parser/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1278,19 +1278,23 @@ pub fn statement_body(i: Input) -> IResult<Statement> {
);
let show_grants = map(
rule! {
SHOW ~ GRANTS ~ #show_grant_option?
SHOW ~ GRANTS ~ #show_grant_option? ~ #show_limit?
},
|(_, _, show_grant_option)| match show_grant_option {
|(_, _, show_grant_option, opt_limit)| match show_grant_option {
Some(ShowGrantOption::PrincipalIdentity(principal)) => Statement::ShowGrants {
principal: Some(principal),
show_options: opt_limit,
},
Some(ShowGrantOption::ShareGrantObjectName(object)) => {
Statement::ShowObjectGrantPrivileges(ShowObjectGrantPrivilegesStmt { object })
}
Some(ShowGrantOption::ShareName(share_name)) => {
Statement::ShowGrantsOfShare(ShowGrantsOfShareStmt { share_name })
}
None => Statement::ShowGrants { principal: None },
None => Statement::ShowGrants {
principal: None,
show_options: opt_limit,
},
},
);
let revoke = map(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ impl AccessChecker for ManagementModeAccess {
| RewriteKind::ShowUserFunctions
| RewriteKind::ShowTableFunctions
| RewriteKind::ShowUsers
// show grants will access meta, can not true in mm.
// | RewriteKind::ShowGrants
| RewriteKind::ShowStages
| RewriteKind::DescribeStage
| RewriteKind::ListStage
Expand All @@ -66,7 +68,6 @@ impl AccessChecker for ManagementModeAccess {
// Show.
Plan::ShowCreateDatabase(_)
| Plan::ShowCreateTable(_)
| Plan::ShowGrants(_)

// Set
| Plan::SetVariable(_)
Expand Down
26 changes: 0 additions & 26 deletions src/query/service/src/interpreters/access/privilege_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,32 +993,6 @@ impl AccessChecker for PrivilegeAccess {
self.validate_access(&GrantObject::Global, UserPrivilegeType::Super)
.await?;
}
Plan::ShowGrants(plan) => {
let current_user = self.ctx.get_current_user()?;
if let Some(principal) = &plan.principal {
match principal {
PrincipalIdentity::User(user) => {
if current_user.identity() == *user {
return Ok(());
} else {
self.validate_access(&GrantObject::Global, UserPrivilegeType::Grant)
.await?;
}
}
PrincipalIdentity::Role(role) => {
let roles=current_user.grants.roles();
if roles.contains(role) || role.to_lowercase() == "public" {
return Ok(());
} else {
self.validate_access(&GrantObject::Global, UserPrivilegeType::Grant)
.await?;
}
}
}
} else {
return Ok(());
}
}
Plan::AlterUser(_)
| Plan::RenameDatabase(_)
| Plan::RevertTable(_)
Expand Down
4 changes: 0 additions & 4 deletions src/query/service/src/interpreters/interpreter_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,6 @@ impl InterpreterFactory {
ctx,
*grant_role.clone(),
)?)),
Plan::ShowGrants(show_grants) => Ok(Arc::new(ShowGrantsInterpreter::try_create(
ctx,
*show_grants.clone(),
)?)),
Plan::RevokePriv(revoke_priv) => Ok(Arc::new(RevokePrivilegeInterpreter::try_create(
ctx,
*revoke_priv.clone(),
Expand Down
2 changes: 0 additions & 2 deletions src/query/service/src/interpreters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ mod interpreter_share_grant_object;
mod interpreter_share_revoke_object;
mod interpreter_share_show;
mod interpreter_share_show_grant_tenants;
mod interpreter_show_grants;
mod interpreter_show_object_grant_privileges;
mod interpreter_stream_create;
mod interpreter_stream_drop;
Expand Down Expand Up @@ -209,7 +208,6 @@ pub use interpreter_share_grant_object::GrantShareObjectInterpreter;
pub use interpreter_share_revoke_object::RevokeShareObjectInterpreter;
pub use interpreter_share_show::ShowSharesInterpreter;
pub use interpreter_share_show_grant_tenants::ShowGrantTenantsOfShareInterpreter;
pub use interpreter_show_grants::ShowGrantsInterpreter;
pub use interpreter_show_object_grant_privileges::ShowObjectGrantPrivilegesInterpreter;
pub use interpreter_stream_create::CreateStreamInterpreter;
pub use interpreter_stream_drop::DropStreamInterpreter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,38 +118,15 @@ impl ShowGrants {
}))
}

// PipelineBuildResult::from_blocks(vec![DataBlock::new_from_columns(vec![
// StringType::from_data(privileges),
// StringType::from_data(object_name),
// UInt64Type::from_opt_data(object_id),
// StringType::from_data(grant_tos),
// StringType::from_data(names),
// StringType::from_data(grant_list),
// ])])
// show grants for role role1;
// +------------+-------------+-----------+----------+-------+-------------------------------------------------------+
// | Privileges | Object Name | Object Id | Grant To | Name | Grants |
// +------------+-------------+-----------+----------+-------+-------------------------------------------------------+
// | SELECT | default | 1 | ROLE | role1 | GRANT SELECT ON 'default'.'default'.* TO ROLE `role1` |
// +------------+-------------+-----------+----------+-------+-------------------------------------------------------+
//
// SHOW GRANTS ON DATABASE sales;
//
// +-----------+------------+------------+------------+--------------+-------------------------------------------------------+
// | privilege | ObjectType | ObjN | granted_to | GrantName | Grants |
// +-----------+------------+------------+------------+--------------+-------------------------------------------------------+
// | OWNERSHIP | DATABASE | REALESTATE | ROLE | ACCOUNTADMIN | |
// | USAGE | DATABASE | REALESTATE | ROLE | PUBLIC | |
// +-----------+------------+------------+------------+--------------+-------------------------------------------------------+
fn schema() -> Arc<TableSchema> {
TableSchemaRefExt::create(vec![
TableField::new("Privileges", TableDataType::String),
TableField::new("Object Name", TableDataType::String),
TableField::new("ObjectName", TableDataType::String),
TableField::new(
"Object Id",
"ObjectId",
TableDataType::Nullable(Box::from(TableDataType::Number(NumberDataType::UInt64))),
),
TableField::new("Grant To", TableDataType::String),
TableField::new("GrantTo", TableDataType::String),
TableField::new("Name", TableDataType::String),
TableField::new(
"Grants",
Expand Down
7 changes: 3 additions & 4 deletions src/query/sql/src/planner/binder/binder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ use chrono_tz::Tz;
use databend_common_ast::ast::format_statement;
use databend_common_ast::ast::Hint;
use databend_common_ast::ast::Identifier;
use databend_common_ast::ast::PrincipalIdentity;
use databend_common_ast::ast::Statement;
use databend_common_ast::ast::With;
use databend_common_ast::parser::parse_sql;
use databend_common_ast::parser::statement::show_options;
use databend_common_ast::parser::tokenize_sql;
use databend_common_ast::parser::Dialect;
use databend_common_catalog::catalog::CatalogManager;
Expand Down Expand Up @@ -62,7 +64,6 @@ use crate::plans::RelOperator;
use crate::plans::RewriteKind;
use crate::plans::ShowConnectionsPlan;
use crate::plans::ShowFileFormatsPlan;
use crate::plans::ShowGrantsPlan;
use crate::plans::ShowRolesPlan;
use crate::plans::UseDatabasePlan;
use crate::plans::Visitor;
Expand Down Expand Up @@ -446,9 +447,7 @@ impl<'a> Binder {

// Permissions
Statement::Grant(stmt) => self.bind_grant(stmt).await?,
Statement::ShowGrants { principal } => Plan::ShowGrants(Box::new(ShowGrantsPlan {
principal: principal.clone().map(Into::into),
})),
Statement::ShowGrants { principal, show_options } => self.bind_show_account_grants(bind_context, principal, show_options).await?,
Statement::Revoke(stmt) => self.bind_revoke(stmt).await?,

// File Formats
Expand Down
34 changes: 34 additions & 0 deletions src/query/sql/src/planner/binder/ddl/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ use databend_common_ast::ast::AccountMgrSource;
use databend_common_ast::ast::AlterUserStmt;
use databend_common_ast::ast::CreateUserStmt;
use databend_common_ast::ast::GrantStmt;
use databend_common_ast::ast::PrincipalIdentity as AstPrincipalIdentity;
use databend_common_ast::ast::RevokeStmt;
use databend_common_ast::ast::ShowOptions;
use databend_common_exception::ErrorCode;
use databend_common_exception::Result;
use databend_common_meta_app::principal::AuthInfo;
Expand All @@ -28,6 +30,7 @@ use databend_common_meta_app::principal::UserOption;
use databend_common_meta_app::principal::UserPrivilegeSet;
use databend_common_users::UserApiProvider;

use crate::binder::show::get_show_options;
use crate::binder::util::illegal_ident_name;
use crate::plans::AlterUserPlan;
use crate::plans::CreateUserPlan;
Expand All @@ -36,6 +39,8 @@ use crate::plans::GrantRolePlan;
use crate::plans::Plan;
use crate::plans::RevokePrivilegePlan;
use crate::plans::RevokeRolePlan;
use crate::plans::RewriteKind;
use crate::BindContext;
use crate::Binder;

impl Binder {
Expand Down Expand Up @@ -331,4 +336,33 @@ impl Binder {

Ok(Plan::AlterUser(Box::new(plan)))
}

#[async_backtrace::framed]
pub(in crate::planner::binder) async fn bind_show_account_grants(
&mut self,
bind_context: &mut BindContext,
principal: &Option<AstPrincipalIdentity>,
show_options: &Option<ShowOptions>,
) -> Result<Plan> {
let query = if let Some(principal) = principal {
match principal {
AstPrincipalIdentity::User(user) => {
format!("SELECT * FROM show_grants('user', '{}')", user.username)
}
AstPrincipalIdentity::Role(role) => {
format!("SELECT * FROM show_grants('role', '{}')", role)
}
}
} else {
let name = self.ctx.get_current_user()?.name;
format!("SELECT * FROM show_grants('user', '{}')", name)
};

let (show_limit, limit_str) =
get_show_options(show_options, Some("ObjectName".to_string()));
let query = format!("{} {} {}", query, show_limit, limit_str,);

self.bind_rewrite_to_query(bind_context, &query, RewriteKind::ShowGrants)
.await
}
}
1 change: 0 additions & 1 deletion src/query/sql/src/planner/format/display_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,6 @@ impl Plan {
// Account
Plan::GrantRole(_) => Ok("GrantRole".to_string()),
Plan::GrantPriv(_) => Ok("GrantPrivilege".to_string()),
Plan::ShowGrants(_) => Ok("ShowGrants".to_string()),
Plan::RevokePriv(_) => Ok("RevokePrivilege".to_string()),
Plan::RevokeRole(_) => Ok("RevokeRole".to_string()),
Plan::CreateUser(_) => Ok("CreateUser".to_string()),
Expand Down
18 changes: 0 additions & 18 deletions src/query/sql/src/planner/plans/ddl/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,6 @@ pub struct GrantRolePlan {
pub role: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShowGrantsPlan {
pub principal: Option<PrincipalIdentity>,
}

impl ShowGrantsPlan {
pub fn schema(&self) -> DataSchemaRef {
DataSchemaRefExt::create(vec![
DataField::new("Privileges", DataType::String),
DataField::new("Object Name", DataType::String),
DataField::new("Object Id", DataType::Nullable(Box::new(DataType::String))),
DataField::new("Grant To", DataType::String),
DataField::new("Name", DataType::String),
DataField::new("Grants", DataType::String),
])
}
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RevokeRolePlan {
pub principal: PrincipalIdentity,
Expand Down
Loading

0 comments on commit 5c2743f

Please sign in to comment.