mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-01 07:04:09 +00:00
feat(auth): make table permission checks schema-aware and guard flow … (#10708)
feat(auth): make table permission checks schema-aware and guard flow sink creation Signed-off-by: shuiyisong <xixing.sys@gmail.com>
This commit is contained in:
+49
-11
@@ -306,6 +306,7 @@ pub trait PermissionChecker: Send + Sync {
|
||||
_user_info: UserInfoRef,
|
||||
_req: PermissionReq,
|
||||
targets: &PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> Result<TableTargetPrecheck> {
|
||||
if !self.uses_table_targets() {
|
||||
return Ok(TableTargetPrecheck::NeedsPhysicalResolution(Vec::new()));
|
||||
@@ -340,6 +341,7 @@ pub trait PermissionChecker: Send + Sync {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
current_schema: Option<&str>,
|
||||
) -> Result<PermissionResp>;
|
||||
}
|
||||
|
||||
@@ -400,12 +402,15 @@ impl PermissionChecker for Option<&PermissionCheckerRef> {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: &PermissionTableTargets,
|
||||
current_schema: Option<&str>,
|
||||
) -> Result<TableTargetPrecheck> {
|
||||
match self {
|
||||
Some(checker) => match checker.precheck_table_targets(user_info, req, targets)? {
|
||||
TableTargetPrecheck::Reject => PermissionDeniedSnafu.fail(),
|
||||
other => Ok(other),
|
||||
},
|
||||
Some(checker) => {
|
||||
match checker.precheck_table_targets(user_info, req, targets, current_schema)? {
|
||||
TableTargetPrecheck::Reject => PermissionDeniedSnafu.fail(),
|
||||
other => Ok(other),
|
||||
}
|
||||
}
|
||||
None => Ok(TableTargetPrecheck::Allow),
|
||||
}
|
||||
}
|
||||
@@ -415,11 +420,15 @@ impl PermissionChecker for Option<&PermissionCheckerRef> {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
current_schema: Option<&str>,
|
||||
) -> Result<PermissionResp> {
|
||||
match self {
|
||||
Some(checker) => check_permission_result(
|
||||
checker.check_permission_with_table_targets(user_info, req, targets),
|
||||
),
|
||||
Some(checker) => check_permission_result(checker.check_permission_with_table_targets(
|
||||
user_info,
|
||||
req,
|
||||
targets,
|
||||
current_schema,
|
||||
)),
|
||||
None => Ok(PermissionResp::Allow),
|
||||
}
|
||||
}
|
||||
@@ -477,6 +486,7 @@ impl PermissionChecker for DefaultPermissionChecker {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
_targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> Result<PermissionResp> {
|
||||
self.check_permission(user_info, req)
|
||||
}
|
||||
@@ -519,6 +529,7 @@ mod tests {
|
||||
_user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> Result<PermissionResp> {
|
||||
if !matches!(req, PermissionReq::Action(PROM_STORE_READ)) {
|
||||
return Ok(PermissionResp::Reject);
|
||||
@@ -737,6 +748,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
resolved_targets("allowed"),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(allowed, PermissionResp::Allow));
|
||||
@@ -746,6 +758,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
PermissionTableTargets::resolved(Vec::new()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(empty, PermissionResp::Allow));
|
||||
@@ -754,6 +767,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_WRITE),
|
||||
PermissionTableTargets::resolved(Vec::new()),
|
||||
None,
|
||||
);
|
||||
assert!(matches!(
|
||||
rejected_operation,
|
||||
@@ -764,6 +778,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
resolved_targets("denied"),
|
||||
None,
|
||||
);
|
||||
assert!(matches!(rejected, Err(Error::PermissionDenied { .. })));
|
||||
|
||||
@@ -774,6 +789,7 @@ mod tests {
|
||||
PermissionTableTarget::new("greptime", "public", "allowed"),
|
||||
PermissionTableTarget::new("greptime", "public", "denied"),
|
||||
]),
|
||||
None,
|
||||
);
|
||||
assert!(matches!(mixed, Err(Error::PermissionDenied { .. })));
|
||||
|
||||
@@ -781,6 +797,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
resolved_targets("error"),
|
||||
None,
|
||||
);
|
||||
assert!(matches!(error, Err(Error::InternalState { msg }) if msg == "testing"));
|
||||
|
||||
@@ -810,6 +827,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
PermissionTableTargets::Unresolved,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(allowed, PermissionResp::Allow));
|
||||
@@ -841,7 +859,7 @@ mod tests {
|
||||
let user = DefaultUserInfo::with_name_and_permission("test_user", permission);
|
||||
let direct = checker.check_permission(user.clone(), req.clone()).unwrap();
|
||||
let targeted = checker
|
||||
.check_permission_with_table_targets(user, req, resolved_targets("metrics"))
|
||||
.check_permission_with_table_targets(user, req, resolved_targets("metrics"), None)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
@@ -863,20 +881,31 @@ mod tests {
|
||||
.precheck_table_targets(
|
||||
ro_user.clone(),
|
||||
PermissionReq::Action(PROMQL_QUERY),
|
||||
&targets
|
||||
&targets,
|
||||
None
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(Vec::new())
|
||||
);
|
||||
assert_eq!(
|
||||
default_checker
|
||||
.precheck_table_targets(ro_user, PermissionReq::Action(PROM_STORE_WRITE), &targets)
|
||||
.precheck_table_targets(
|
||||
ro_user,
|
||||
PermissionReq::Action(PROM_STORE_WRITE),
|
||||
&targets,
|
||||
None
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(Vec::new())
|
||||
);
|
||||
assert_eq!(
|
||||
default_checker
|
||||
.precheck_table_targets(rw_user, PermissionReq::Action(PROM_STORE_WRITE), &targets)
|
||||
.precheck_table_targets(
|
||||
rw_user,
|
||||
PermissionReq::Action(PROM_STORE_WRITE),
|
||||
&targets,
|
||||
None
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(Vec::new())
|
||||
);
|
||||
@@ -896,6 +925,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> Result<PermissionResp> {
|
||||
Ok(PermissionResp::Reject)
|
||||
}
|
||||
@@ -906,6 +936,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_WRITE),
|
||||
&targets,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(Vec::new())
|
||||
@@ -924,6 +955,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
&mixed_targets,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(vec![0, 2])
|
||||
@@ -934,6 +966,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
&PermissionTableTargets::Unresolved,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(Vec::new())
|
||||
@@ -946,6 +979,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_READ),
|
||||
&mixed_targets,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::NeedsPhysicalResolution(vec![0, 2])
|
||||
@@ -962,6 +996,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> Result<TableTargetPrecheck> {
|
||||
Ok(TableTargetPrecheck::Reject)
|
||||
}
|
||||
@@ -971,6 +1006,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> Result<PermissionResp> {
|
||||
Ok(PermissionResp::Reject)
|
||||
}
|
||||
@@ -981,6 +1017,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_WRITE),
|
||||
&targets,
|
||||
None,
|
||||
);
|
||||
assert!(matches!(rejected, Err(Error::PermissionDenied { .. })));
|
||||
|
||||
@@ -991,6 +1028,7 @@ mod tests {
|
||||
crate::userinfo_by_name(None),
|
||||
PermissionReq::Action(PROM_STORE_WRITE),
|
||||
&PermissionTableTargets::Unresolved,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
TableTargetPrecheck::Allow
|
||||
|
||||
@@ -51,6 +51,7 @@ impl PermissionChecker for DummyPermissionChecker {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
_targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.check_permission(user_info, req)
|
||||
}
|
||||
|
||||
@@ -503,6 +503,7 @@ mod tests {
|
||||
catchup_max_runs: 3,
|
||||
catchup_max_lag_secs: 300,
|
||||
}),
|
||||
allow_sink_create: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,7 @@ mod tests {
|
||||
created_time: chrono::Utc::now(),
|
||||
updated_time: chrono::Utc::now(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
},
|
||||
(1..=3)
|
||||
.map(|i| {
|
||||
|
||||
@@ -482,6 +482,11 @@ pub const INTERNAL_EVAL_OFFSET_KEY: &str = "__greptime_internal_eval_offset_secs
|
||||
/// field in the flow create request.
|
||||
pub const INTERNAL_EVAL_SCHEDULE_KEY: &str = "__greptime_internal_eval_schedule";
|
||||
|
||||
/// Internal transient key used to pass `CreateFlowTask.allow_sink_create`
|
||||
/// between frontend, meta, and flownode without persisting it in
|
||||
/// `FlowInfoValue.options`.
|
||||
pub const INTERNAL_ALLOW_SINK_CREATE_KEY: &str = "__greptime_internal_allow_sink_create";
|
||||
|
||||
const FLOW_SCHEDULED_TIME_MILLIS_EXTENSION_KEY: &str = "flow.scheduled_time_millis";
|
||||
|
||||
fn without_scheduled_time_extension(mut query_context: QueryContext) -> QueryContext {
|
||||
@@ -524,7 +529,11 @@ pub fn validate_flow_options(flow_task: &CreateFlowTask) -> Result<()> {
|
||||
.fail();
|
||||
}
|
||||
|
||||
for key in [INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY] {
|
||||
for key in [
|
||||
INTERNAL_EVAL_OFFSET_KEY,
|
||||
INTERNAL_EVAL_SCHEDULE_KEY,
|
||||
INTERNAL_ALLOW_SINK_CREATE_KEY,
|
||||
] {
|
||||
if flow_task.flow_options.contains_key(key) {
|
||||
return UnexpectedSnafu {
|
||||
err_msg: format!("flow option '{key}' is reserved for internal use"),
|
||||
@@ -757,6 +766,7 @@ fn user_runtime_flow_options(options: &HashMap<String, String>) -> HashMap<Strin
|
||||
options.remove(DEFER_ON_MISSING_SOURCE_KEY);
|
||||
options.remove(INTERNAL_EVAL_SCHEDULE_KEY);
|
||||
options.remove(INTERNAL_EVAL_OFFSET_KEY);
|
||||
options.remove(INTERNAL_ALLOW_SINK_CREATE_KEY);
|
||||
options
|
||||
}
|
||||
|
||||
@@ -873,6 +883,12 @@ impl From<&CreateFlowData> for CreateRequest {
|
||||
req.flow_options
|
||||
.insert(INTERNAL_EVAL_SCHEDULE_KEY.to_string(), json);
|
||||
}
|
||||
if !value.task.allow_sink_create {
|
||||
req.flow_options.insert(
|
||||
INTERNAL_ALLOW_SINK_CREATE_KEY.to_string(),
|
||||
"false".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
req
|
||||
}
|
||||
@@ -897,7 +913,12 @@ impl From<&CreateFlowData> for (FlowInfoValue, Vec<(FlowPartitionId, FlowRouteVa
|
||||
.flow_options
|
||||
.iter()
|
||||
.filter(|(k, _)| {
|
||||
k.as_str() != INTERNAL_EVAL_SCHEDULE_KEY && k.as_str() != INTERNAL_EVAL_OFFSET_KEY
|
||||
!matches!(
|
||||
k.as_str(),
|
||||
INTERNAL_EVAL_SCHEDULE_KEY
|
||||
| INTERNAL_EVAL_OFFSET_KEY
|
||||
| INTERNAL_ALLOW_SINK_CREATE_KEY
|
||||
)
|
||||
})
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
@@ -953,6 +974,7 @@ impl From<&CreateFlowData> for (FlowInfoValue, Vec<(FlowPartitionId, FlowRouteVa
|
||||
created_time: create_time,
|
||||
updated_time: chrono::Utc::now(),
|
||||
eval_schedule: eval_schedule.clone(),
|
||||
allow_sink_create: value.task.allow_sink_create,
|
||||
};
|
||||
|
||||
(flow_info, flow_routes)
|
||||
|
||||
@@ -74,6 +74,7 @@ pub(crate) fn test_create_flow_task(
|
||||
sql: "select 1".to_string(),
|
||||
flow_options: Default::default(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +108,7 @@ fn flow_info_for_schedule_test(
|
||||
created_time,
|
||||
updated_time: created_time,
|
||||
eval_schedule,
|
||||
allow_sink_create: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1303,6 +1305,7 @@ fn create_test_flow_task_for_serialization() -> CreateFlowTask {
|
||||
sql: "SELECT * FROM source_table".to_string(),
|
||||
flow_options: HashMap::new(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1877,6 +1877,7 @@ mod tests {
|
||||
sql: "select 1".to_string(),
|
||||
flow_options: Default::default(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -564,6 +564,7 @@ mod tests {
|
||||
created_time: chrono::Utc::now(),
|
||||
updated_time: chrono::Utc::now(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -898,6 +899,7 @@ mod tests {
|
||||
created_time: chrono::Utc::now(),
|
||||
updated_time: chrono::Utc::now(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
};
|
||||
let err = flow_metadata_manager
|
||||
.create_flow_metadata(flow_id, flow_value, flow_routes.clone())
|
||||
@@ -1279,6 +1281,7 @@ mod tests {
|
||||
created_time: chrono::Utc::now(),
|
||||
updated_time: chrono::Utc::now(),
|
||||
eval_schedule: None,
|
||||
allow_sink_create: true,
|
||||
};
|
||||
let err = flow_metadata_manager
|
||||
.update_flow_metadata(
|
||||
|
||||
@@ -269,6 +269,14 @@ pub struct FlowInfoValue {
|
||||
/// limits). Absent for flows without `EVAL INTERVAL`.
|
||||
#[serde(default)]
|
||||
pub eval_schedule: Option<FlowScheduleConfig>,
|
||||
/// Whether the flow creator was authorized to auto-create the sink table
|
||||
/// (and incremental flow state table/result view) when missing.
|
||||
#[serde(default = "default_allow_sink_create")]
|
||||
pub allow_sink_create: bool,
|
||||
}
|
||||
|
||||
fn default_allow_sink_create() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl FlowInfoValue {
|
||||
@@ -354,6 +362,10 @@ impl FlowInfoValue {
|
||||
pub fn updated_time(&self) -> &DateTime<Utc> {
|
||||
&self.updated_time
|
||||
}
|
||||
|
||||
pub fn allow_sink_create(&self) -> bool {
|
||||
self.allow_sink_create
|
||||
}
|
||||
}
|
||||
|
||||
pub type FlowInfoManagerRef = Arc<FlowInfoManager>;
|
||||
|
||||
@@ -1332,6 +1332,14 @@ pub struct CreateFlowTask {
|
||||
/// defaults are resolved.
|
||||
#[serde(default)]
|
||||
pub eval_schedule: Option<crate::key::flow::flow_info::FlowScheduleConfig>,
|
||||
/// Whether the flow creator was authorized to auto-create the sink table
|
||||
/// (and incremental flow state table/result view) when missing.
|
||||
#[serde(default = "default_allow_sink_create")]
|
||||
pub allow_sink_create: bool,
|
||||
}
|
||||
|
||||
fn default_allow_sink_create() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl TryFrom<PbCreateFlowTask> for CreateFlowTask {
|
||||
@@ -1370,6 +1378,19 @@ impl TryFrom<PbCreateFlowTask> for CreateFlowTask {
|
||||
None => None,
|
||||
};
|
||||
|
||||
let allow_sink_create =
|
||||
match flow_options.remove(crate::ddl::create_flow::INTERNAL_ALLOW_SINK_CREATE_KEY) {
|
||||
Some(value) => value.parse::<bool>().map_err(|_| {
|
||||
error::UnexpectedSnafu {
|
||||
err_msg: format!(
|
||||
"Invalid internal allow sink create payload '{value}': expected boolean"
|
||||
),
|
||||
}
|
||||
.build()
|
||||
})?,
|
||||
None => true,
|
||||
};
|
||||
|
||||
Ok(CreateFlowTask {
|
||||
catalog_name,
|
||||
flow_name,
|
||||
@@ -1388,6 +1409,7 @@ impl TryFrom<PbCreateFlowTask> for CreateFlowTask {
|
||||
sql,
|
||||
flow_options,
|
||||
eval_schedule: None,
|
||||
allow_sink_create,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1407,6 +1429,7 @@ impl From<CreateFlowTask> for PbCreateFlowTask {
|
||||
comment,
|
||||
sql,
|
||||
mut flow_options,
|
||||
allow_sink_create,
|
||||
..
|
||||
}: CreateFlowTask,
|
||||
) -> Self {
|
||||
@@ -1418,6 +1441,12 @@ impl From<CreateFlowTask> for PbCreateFlowTask {
|
||||
offset_secs.to_string(),
|
||||
);
|
||||
}
|
||||
if !allow_sink_create {
|
||||
flow_options.insert(
|
||||
crate::ddl::create_flow::INTERNAL_ALLOW_SINK_CREATE_KEY.to_string(),
|
||||
"false".to_string(),
|
||||
);
|
||||
}
|
||||
PbCreateFlowTask {
|
||||
create_flow: Some(CreateFlowExpr {
|
||||
catalog_name,
|
||||
|
||||
@@ -864,8 +864,21 @@ impl StreamingEngine {
|
||||
&source_primary_key_indices,
|
||||
&flow_plan,
|
||||
);
|
||||
let allow_sink_create = args
|
||||
.flow_options
|
||||
.get(common_meta::ddl::create_flow::INTERNAL_ALLOW_SINK_CREATE_KEY)
|
||||
.map(String::as_str)
|
||||
!= Some("false");
|
||||
let sink_exists = self.fetch_table_pk_schema(sink_table_name).await?.is_some();
|
||||
if !sink_exists {
|
||||
if create_sink && !allow_sink_create {
|
||||
return crate::error::PermissionDeniedSnafu {
|
||||
reason: format!(
|
||||
"Permission denied to auto-create missing flow sink table `{sink_table_name:?}`"
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
validate_auto_column_names(&inferred_schema)?;
|
||||
}
|
||||
if !sink_exists
|
||||
|
||||
@@ -368,7 +368,17 @@ impl FlowDualEngine {
|
||||
eval_interval: info.eval_interval(),
|
||||
comment: Some(info.comment().clone()),
|
||||
sql: info.raw_sql().clone(),
|
||||
flow_options: info.options().clone(),
|
||||
flow_options: {
|
||||
let mut flow_options = info.options().clone();
|
||||
if !info.allow_sink_create() {
|
||||
flow_options.insert(
|
||||
common_meta::ddl::create_flow::INTERNAL_ALLOW_SINK_CREATE_KEY
|
||||
.to_string(),
|
||||
"false".to_string(),
|
||||
);
|
||||
}
|
||||
flow_options
|
||||
},
|
||||
eval_schedule: effective_eval_schedule_from_flow_info(&info)
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?,
|
||||
|
||||
@@ -732,10 +732,15 @@ impl BatchingEngine {
|
||||
eval_schedule,
|
||||
};
|
||||
|
||||
let allow_sink_create = flow_options
|
||||
.get(common_meta::ddl::create_flow::INTERNAL_ALLOW_SINK_CREATE_KEY)
|
||||
.map(String::as_str)
|
||||
!= Some("false");
|
||||
let task = BatchingTask::try_new_with_exact_sequence_range_required(
|
||||
task_args,
|
||||
exact_sequence_range_required,
|
||||
)?;
|
||||
)?
|
||||
.with_allow_sink_create(allow_sink_create);
|
||||
|
||||
if task.config.exact_sequence_range_required {
|
||||
ensure!(
|
||||
|
||||
@@ -163,6 +163,8 @@ pub struct TaskConfig {
|
||||
pub flow_eval_interval: Option<Duration>,
|
||||
/// Typed schedule configuration, pre-parsed at task creation time.
|
||||
pub eval_schedule: Option<EvalSchedule>,
|
||||
/// Whether the flow creator was authorized to auto-create the sink table when missing.
|
||||
pub allow_sink_create: bool,
|
||||
}
|
||||
|
||||
fn determine_query_type(query: &str, query_ctx: &QueryContextRef) -> Result<QueryType, Error> {
|
||||
@@ -446,6 +448,7 @@ impl BatchingTask {
|
||||
batch_opts,
|
||||
flow_eval_interval,
|
||||
eval_schedule,
|
||||
allow_sink_create: true,
|
||||
}),
|
||||
state: Arc::new(RwLock::new(state)),
|
||||
execution_lock: Arc::new(Mutex::new(())),
|
||||
@@ -461,6 +464,11 @@ impl BatchingTask {
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_allow_sink_create(mut self, allow_sink_create: bool) -> Self {
|
||||
Arc::make_mut(&mut self.config).allow_sink_create = allow_sink_create;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn stop_execution(&self) {
|
||||
if let Some(execution) = &self.execution {
|
||||
execution.stop();
|
||||
@@ -529,6 +537,15 @@ impl BatchingTask {
|
||||
frontend_client: &Arc<FrontendClient>,
|
||||
) -> Result<TableRef, Error> {
|
||||
if !self.is_table_exist(&self.config.sink_table_name).await? {
|
||||
snafu::ensure!(
|
||||
self.config.allow_sink_create,
|
||||
crate::error::PermissionDeniedSnafu {
|
||||
reason: format!(
|
||||
"Permission denied to auto-create missing flow sink table `{}`",
|
||||
self.config.sink_table_name.join(".")
|
||||
),
|
||||
}
|
||||
);
|
||||
let create_table = self.gen_create_table_expr(engine.clone()).await?;
|
||||
info!(
|
||||
"Try creating sink table(if not exists) with expr: {:?}",
|
||||
|
||||
+18
-4
@@ -166,6 +166,13 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Permission denied: {reason}"))]
|
||||
PermissionDenied {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Datatypes error: {source} with extra message: {extra}"))]
|
||||
Datatypes {
|
||||
source: datatypes::Error,
|
||||
@@ -318,10 +325,17 @@ impl ErrorExt for Error {
|
||||
| Self::ListFlows { .. } => StatusCode::TableNotFound,
|
||||
Self::FlowNotFound { .. } => StatusCode::FlowNotFound,
|
||||
Self::Plan { .. } | Self::Datatypes { .. } => StatusCode::PlanQuery,
|
||||
Self::CreateFlow { .. }
|
||||
| Self::CreateSinkTable { .. }
|
||||
| Self::Arrow { .. }
|
||||
| Self::Time { .. } => StatusCode::EngineExecuteQuery,
|
||||
Self::PermissionDenied { .. } => StatusCode::PermissionDenied,
|
||||
Self::CreateFlow { source, .. } => {
|
||||
if source.status_code() == StatusCode::PermissionDenied {
|
||||
StatusCode::PermissionDenied
|
||||
} else {
|
||||
StatusCode::EngineExecuteQuery
|
||||
}
|
||||
}
|
||||
Self::CreateSinkTable { .. } | Self::Arrow { .. } | Self::Time { .. } => {
|
||||
StatusCode::EngineExecuteQuery
|
||||
}
|
||||
Self::Unexpected { .. }
|
||||
| Self::SyncCheckTask { .. }
|
||||
| Self::IllegalCheckTaskState { .. } => StatusCode::Unexpected,
|
||||
|
||||
@@ -453,6 +453,29 @@ impl Instance {
|
||||
if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy)) = &stmt {
|
||||
return self.copy_database(copy.clone(), &stmt, query_ctx).await;
|
||||
}
|
||||
if let Statement::CreateFlow(stmt) = stmt {
|
||||
let (catalog, schema, table) = session::table_name::table_idents_to_full_name(
|
||||
&stmt.sink_table_name,
|
||||
&query_ctx,
|
||||
)
|
||||
.map_err(BoxedError::new)
|
||||
.context(crate::error::ExternalSnafu)?;
|
||||
let allow_sink_create = self
|
||||
.can_create_flow_sinks(
|
||||
&query_ctx,
|
||||
catalog,
|
||||
schema,
|
||||
table,
|
||||
stmt.flow_options.get("incremental"),
|
||||
stmt.flow_options.get("incremental_result_view"),
|
||||
)
|
||||
.await?;
|
||||
return self
|
||||
.statement_executor
|
||||
.create_flow_with_sink_create_permission(stmt, allow_sink_create, query_ctx)
|
||||
.await
|
||||
.context(TableOperationSnafu);
|
||||
}
|
||||
self.statement_executor
|
||||
.execute_sql(stmt, query_ctx)
|
||||
.await
|
||||
@@ -603,6 +626,15 @@ impl Instance {
|
||||
stmt: &Statement,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
self.plugins
|
||||
.get::<PermissionCheckerRef>()
|
||||
.as_ref()
|
||||
.check_permission_with_context(
|
||||
ctx.current_user(),
|
||||
PermissionReq::SqlStatement(stmt),
|
||||
Some(&ctx.current_schema()),
|
||||
)
|
||||
.context(PermissionSnafu)?;
|
||||
match copy {
|
||||
CopyDatabase::To(arg) => {
|
||||
let req = operator::statement::to_copy_database_request(arg, &ctx)?;
|
||||
@@ -1374,6 +1406,73 @@ impl Instance {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn can_create_flow_sink(
|
||||
&self,
|
||||
ctx: &QueryContextRef,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> Result<bool> {
|
||||
let req = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
||||
expr: Some(api::v1::ddl_request::Expr::CreateTable(
|
||||
api::v1::CreateTableExpr {
|
||||
catalog_name: catalog.clone(),
|
||||
schema_name: schema.clone(),
|
||||
table_name: table.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
});
|
||||
let targets = PermissionTableTargets::Resolved(vec![PermissionTableTarget {
|
||||
catalog,
|
||||
schema,
|
||||
table,
|
||||
is_physical_metric_table: false,
|
||||
}]);
|
||||
match self
|
||||
.check_resolved_table_permission(ctx, PermissionReq::GrpcRequest(&req), targets)
|
||||
.await
|
||||
{
|
||||
Ok(()) => Ok(true),
|
||||
Err(Error::Permission { source, .. })
|
||||
if source.status_code()
|
||||
== common_error::status_code::StatusCode::PermissionDenied =>
|
||||
{
|
||||
Ok(false)
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn can_create_flow_sinks(
|
||||
&self,
|
||||
ctx: &QueryContextRef,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
sink_table: String,
|
||||
incremental_flag: Option<&str>,
|
||||
incremental_result_view: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
if !self
|
||||
.can_create_flow_sink(ctx, catalog.clone(), schema.clone(), sink_table.clone())
|
||||
.await?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let is_incremental =
|
||||
incremental_flag.is_some_and(|value| value.trim().eq_ignore_ascii_case("true"));
|
||||
if !is_incremental {
|
||||
return Ok(true);
|
||||
}
|
||||
let result_view = incremental_result_view
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_else(|| format!("{sink_table}_result"));
|
||||
self.can_create_flow_sink(ctx, catalog, schema, result_view)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn check_resolved_table_permissions<const N: usize>(
|
||||
&self,
|
||||
ctx: &QueryContextRef,
|
||||
@@ -1392,16 +1491,27 @@ impl Instance {
|
||||
};
|
||||
|
||||
let user = ctx.current_user();
|
||||
let current_schema = ctx.current_schema();
|
||||
let check = |req, targets| {
|
||||
checker
|
||||
.check_permission_with_table_targets(user.clone(), req, targets)
|
||||
.check_permission_with_table_targets(
|
||||
user.clone(),
|
||||
req,
|
||||
targets,
|
||||
Some(current_schema.as_str()),
|
||||
)
|
||||
.map(|_| ())
|
||||
.context(PermissionSnafu)
|
||||
};
|
||||
let mut looked_up = HashSet::new();
|
||||
for (i, req) in requests.into_iter().enumerate() {
|
||||
match checker
|
||||
.precheck_table_targets(user.clone(), req.clone(), &targets)
|
||||
.precheck_table_targets(
|
||||
user.clone(),
|
||||
req.clone(),
|
||||
&targets,
|
||||
Some(current_schema.as_str()),
|
||||
)
|
||||
.context(PermissionSnafu)?
|
||||
{
|
||||
TableTargetPrecheck::Allow => continue,
|
||||
@@ -1692,6 +1802,7 @@ impl Instance {
|
||||
query_ctx.current_user(),
|
||||
PermissionReq::Action(PROMQL_QUERY),
|
||||
PermissionTableTargets::resolved(vec![target.clone()]),
|
||||
Some(schema.as_str()),
|
||||
)
|
||||
.context(AuthSnafu)
|
||||
{
|
||||
@@ -1950,6 +2061,7 @@ impl PrometheusHandler for Instance {
|
||||
query_ctx.current_user(),
|
||||
PermissionReq::Action(PROMQL_QUERY),
|
||||
PermissionTableTargets::resolved(vec![target]),
|
||||
Some(schema),
|
||||
)
|
||||
.context(AuthSnafu);
|
||||
return match result {
|
||||
@@ -1974,6 +2086,7 @@ impl PrometheusHandler for Instance {
|
||||
query_ctx.current_user(),
|
||||
PermissionReq::Action(PROMQL_QUERY),
|
||||
PermissionTableTargets::resolved(vec![target]),
|
||||
Some(schema),
|
||||
)
|
||||
.context(AuthSnafu)
|
||||
{
|
||||
@@ -2651,6 +2764,7 @@ mod tests {
|
||||
_user_info: UserInfoRef,
|
||||
_req: PermissionReq,
|
||||
_targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.table_target_checks
|
||||
.fetch_add(1, atomic::Ordering::Relaxed);
|
||||
@@ -2678,6 +2792,7 @@ mod tests {
|
||||
_user_info: UserInfoRef,
|
||||
_req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
let reject = match targets {
|
||||
PermissionTableTargets::Unresolved => true,
|
||||
@@ -2741,6 +2856,7 @@ mod tests {
|
||||
_user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
Ok(match req {
|
||||
PermissionReq::Action(action) => self.reject(action, Some(targets)),
|
||||
@@ -2769,6 +2885,7 @@ mod tests {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
_targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.check_permission(user_info, req)
|
||||
}
|
||||
@@ -2798,6 +2915,7 @@ mod tests {
|
||||
user_info: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
_targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.check_permission(user_info, req)
|
||||
}
|
||||
@@ -3116,6 +3234,7 @@ mod tests {
|
||||
.context(common_meta::error::ExternalSnafu)?;
|
||||
Ok(SubmitDdlTaskResponse::default())
|
||||
}
|
||||
DdlTask::CreateFlow(_) => Ok(SubmitDdlTaskResponse::default()),
|
||||
other => common_meta::error::UnsupportedSnafu {
|
||||
operation: format!("mock submit_ddl_task: {other:?}"),
|
||||
}
|
||||
@@ -3335,6 +3454,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
let applies = match req {
|
||||
PermissionReq::Action(action) => action == COPY_TO && self.reject_read,
|
||||
@@ -3680,6 +3800,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.0.lock().unwrap().push(targets.clone());
|
||||
let PermissionTableTargets::Resolved(tables) = targets else {
|
||||
@@ -4752,6 +4873,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.0.lock().unwrap().push(targets);
|
||||
Ok(PermissionResp::Allow)
|
||||
@@ -4846,6 +4968,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
let PermissionTableTargets::Resolved(targets) = targets else {
|
||||
panic!("physical target must retain its identity")
|
||||
@@ -5104,6 +5227,7 @@ mod tests {
|
||||
_user_info: UserInfoRef,
|
||||
_req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
let reject = match targets {
|
||||
PermissionTableTargets::Unresolved => true,
|
||||
@@ -6681,6 +6805,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<TableTargetPrecheck> {
|
||||
Ok(TableTargetPrecheck::Allow)
|
||||
}
|
||||
@@ -6690,6 +6815,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
panic!("check_permission_with_table_targets should be skipped on precheck Allow")
|
||||
}
|
||||
@@ -6735,6 +6861,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<TableTargetPrecheck> {
|
||||
Ok(match (req, targets) {
|
||||
(PermissionReq::Action(COPY_TO), PermissionTableTargets::Resolved(_)) => {
|
||||
@@ -6749,6 +6876,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
panic!("check_permission_with_table_targets should be skipped on precheck Reject")
|
||||
}
|
||||
@@ -6816,6 +6944,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<TableTargetPrecheck> {
|
||||
let PermissionTableTargets::Resolved(targets) = targets else {
|
||||
return Ok(TableTargetPrecheck::Reject);
|
||||
@@ -6832,6 +6961,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.0.lock().unwrap().push(targets);
|
||||
Ok(PermissionResp::Allow)
|
||||
@@ -6904,6 +7034,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<TableTargetPrecheck> {
|
||||
self.precheck_calls.lock().unwrap().push(targets.clone());
|
||||
let PermissionTableTargets::Resolved(targets) = targets else {
|
||||
@@ -6919,6 +7050,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.final_calls.lock().unwrap().push(targets);
|
||||
Ok(PermissionResp::Allow)
|
||||
@@ -7012,6 +7144,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
self.target_hook_calls
|
||||
.fetch_add(1, atomic::Ordering::Relaxed);
|
||||
@@ -7064,6 +7197,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<TableTargetPrecheck> {
|
||||
Ok(TableTargetPrecheck::NeedsPhysicalResolution(vec![99]))
|
||||
}
|
||||
@@ -7073,6 +7207,7 @@ mod tests {
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
_: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
unreachable!("must fail before check_permission_with_table_targets")
|
||||
}
|
||||
@@ -7104,4 +7239,523 @@ mod tests {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_check_sql_permission_normalizes_unquoted_and_preserves_quoted() -> TestResult<()>
|
||||
{
|
||||
struct RecordingPhysicalChecker {
|
||||
resolved_targets: std::sync::Mutex<Vec<PermissionTableTargets>>,
|
||||
}
|
||||
|
||||
impl PermissionChecker for RecordingPhysicalChecker {
|
||||
fn check_permission(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
Ok(PermissionResp::Allow)
|
||||
}
|
||||
|
||||
fn precheck_table_targets(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: &PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<TableTargetPrecheck> {
|
||||
let PermissionTableTargets::Resolved(targets) = targets else {
|
||||
return Ok(TableTargetPrecheck::Reject);
|
||||
};
|
||||
Ok(TableTargetPrecheck::NeedsPhysicalResolution(
|
||||
(0..targets.len()).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
let denied = matches!(
|
||||
&targets,
|
||||
PermissionTableTargets::Resolved(list)
|
||||
if list.iter().any(|t| t.schema == "public" && t.table == "readings")
|
||||
);
|
||||
self.resolved_targets.lock().unwrap().push(targets);
|
||||
Ok(if denied {
|
||||
PermissionResp::Reject
|
||||
} else {
|
||||
PermissionResp::Allow
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let checker = Arc::new(RecordingPhysicalChecker {
|
||||
resolved_targets: Default::default(),
|
||||
});
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
||||
|
||||
let catalog = catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(
|
||||
1024, "readings",
|
||||
)?);
|
||||
catalog
|
||||
.register_table_sync(catalog::RegisterTableRequest {
|
||||
catalog: "greptime".to_string(),
|
||||
schema: "public".to_string(),
|
||||
table_name: "Readings".to_string(),
|
||||
table_id: 1025,
|
||||
table: test_table(1025, "Readings")?,
|
||||
})
|
||||
.with_context(|_| RegisterTableSnafu {
|
||||
table_name: "Readings".to_string(),
|
||||
})?;
|
||||
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
||||
let instance = test_instance_with_counting_catalog(counting_catalog, plugins).await?;
|
||||
let ctx = test_query_ctx(1);
|
||||
|
||||
// Both unquoted spellings resolve to `readings`, look up the physical table `readings`,
|
||||
// and receive the same PermissionDenied decision.
|
||||
for sql in [
|
||||
"SELECT * FROM readings",
|
||||
"SELECT * FROM Readings",
|
||||
"SELECT * FROM Public.Readings",
|
||||
] {
|
||||
let err = instance
|
||||
.check_sql_permission(&parse_one_sql(sql), &ctx)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{sql}");
|
||||
}
|
||||
|
||||
// Quoted `"Readings"` preserves case, looks up non-physical `"Readings"`, and is allowed.
|
||||
instance
|
||||
.check_sql_permission(&parse_one_sql(r#"SELECT * FROM "Readings""#), &ctx)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// TQL metric names stay case-sensitive.
|
||||
instance
|
||||
.check_sql_permission(&parse_one_sql("TQL EVAL (0, 10, '5s') Readings"), &ctx)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let recorded = checker.resolved_targets.lock().unwrap();
|
||||
assert_eq!(
|
||||
*recorded,
|
||||
vec![
|
||||
PermissionTableTargets::Resolved(vec![
|
||||
PermissionTableTarget::new("greptime", "public", "readings")
|
||||
.with_physical_metric_table(true),
|
||||
]),
|
||||
PermissionTableTargets::Resolved(vec![
|
||||
PermissionTableTarget::new("greptime", "public", "readings")
|
||||
.with_physical_metric_table(true),
|
||||
]),
|
||||
PermissionTableTargets::Resolved(vec![
|
||||
PermissionTableTarget::new("greptime", "public", "readings")
|
||||
.with_physical_metric_table(true),
|
||||
]),
|
||||
PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
|
||||
"greptime", "public", "Readings"
|
||||
)]),
|
||||
PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
|
||||
"greptime", "public", "Readings"
|
||||
)]),
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_flow_sink_permission_preserves_checker_errors() -> TestResult<()> {
|
||||
#[derive(Clone)]
|
||||
enum SinkCreateMode {
|
||||
Deny,
|
||||
InternalError,
|
||||
BackendError,
|
||||
DenyOnResultView,
|
||||
ErrorOnResultView,
|
||||
}
|
||||
|
||||
struct FlowSinkChecker {
|
||||
mode: std::sync::Mutex<SinkCreateMode>,
|
||||
}
|
||||
|
||||
impl PermissionChecker for FlowSinkChecker {
|
||||
fn check_permission(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
Ok(PermissionResp::Allow)
|
||||
}
|
||||
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
request: &Request,
|
||||
_catalog: &str,
|
||||
_schema: &str,
|
||||
) -> PermissionTableTargets {
|
||||
match request {
|
||||
Request::Ddl(ddl)
|
||||
if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
|
||||
{
|
||||
PermissionTableTargets::resolved(vec![])
|
||||
}
|
||||
_ => PermissionTableTargets::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
let PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req else {
|
||||
return Ok(PermissionResp::Allow);
|
||||
};
|
||||
let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr else {
|
||||
return Ok(PermissionResp::Allow);
|
||||
};
|
||||
let _ = targets;
|
||||
match self.mode.lock().unwrap().clone() {
|
||||
SinkCreateMode::Deny => Ok(PermissionResp::Reject),
|
||||
SinkCreateMode::InternalError => auth::error::InternalStateSnafu {
|
||||
msg: "checker internal failure",
|
||||
}
|
||||
.fail(),
|
||||
SinkCreateMode::BackendError => {
|
||||
Err::<PermissionResp, _>(BoxedError::new(PlainError::new(
|
||||
"auth backend unavailable".to_string(),
|
||||
StatusCode::StorageUnavailable,
|
||||
)))
|
||||
.context(auth::error::AuthBackendSnafu)
|
||||
}
|
||||
SinkCreateMode::DenyOnResultView => {
|
||||
if create_table.table_name.ends_with("_result") {
|
||||
Ok(PermissionResp::Reject)
|
||||
} else {
|
||||
Ok(PermissionResp::Allow)
|
||||
}
|
||||
}
|
||||
SinkCreateMode::ErrorOnResultView => {
|
||||
if create_table.table_name.ends_with("_result") {
|
||||
auth::error::InternalStateSnafu {
|
||||
msg: "result view check failed",
|
||||
}
|
||||
.fail()
|
||||
} else {
|
||||
Ok(PermissionResp::Allow)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let checker = Arc::new(FlowSinkChecker {
|
||||
mode: std::sync::Mutex::new(SinkCreateMode::Deny),
|
||||
});
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
||||
|
||||
let catalog =
|
||||
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
||||
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
||||
let instance = test_instance_with_catalog_manager(
|
||||
catalog,
|
||||
test_table(1025, "target")?,
|
||||
plugins,
|
||||
None,
|
||||
executor.clone(),
|
||||
)
|
||||
.await?;
|
||||
let ctx = test_query_ctx(1);
|
||||
|
||||
let grpc_create_flow = |name: &str, incremental: bool| {
|
||||
let mut flow_options = std::collections::HashMap::new();
|
||||
if incremental {
|
||||
flow_options.insert("incremental".to_string(), "true".to_string());
|
||||
}
|
||||
Request::Ddl(api::v1::DdlRequest {
|
||||
expr: Some(api::v1::ddl_request::Expr::CreateFlow(
|
||||
api::v1::CreateFlowExpr {
|
||||
flow_name: name.to_string(),
|
||||
source_table_names: vec![api::v1::TableName {
|
||||
catalog_name: "greptime".to_string(),
|
||||
schema_name: "public".to_string(),
|
||||
table_name: "source".to_string(),
|
||||
}],
|
||||
sink_table_name: Some(api::v1::TableName {
|
||||
catalog_name: "greptime".to_string(),
|
||||
schema_name: "public".to_string(),
|
||||
table_name: "target".to_string(),
|
||||
}),
|
||||
eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
|
||||
sql: "SELECT id, ts FROM source".to_string(),
|
||||
flow_options,
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
})
|
||||
};
|
||||
|
||||
// Denied `table.create` via SQL still submits the flow with `allow_sink_create = false`.
|
||||
execute_one_sql(
|
||||
&instance,
|
||||
"CREATE FLOW sql_denied_sink SINK TO target EVAL INTERVAL '10s' AS SELECT id, ts FROM source",
|
||||
ctx.clone(),
|
||||
)
|
||||
.await?;
|
||||
// Denied `table.create` via gRPC still submits the flow with `allow_sink_create = false`.
|
||||
servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
||||
&instance,
|
||||
grpc_create_flow("grpc_denied_sink", false),
|
||||
ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Incremental result view denial returns `Ok(false)` instead of `Ok(true)`.
|
||||
*checker.mode.lock().unwrap() = SinkCreateMode::DenyOnResultView;
|
||||
assert!(
|
||||
!instance
|
||||
.can_create_flow_sinks(
|
||||
&ctx,
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"target".to_string(),
|
||||
Some("true"),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
{
|
||||
let mut submitted = executor.submitted.lock().unwrap();
|
||||
assert_eq!(2, submitted.len());
|
||||
for task in submitted.drain(..) {
|
||||
let DdlTask::CreateFlow(flow_task) = task else {
|
||||
panic!("expected CreateFlow task");
|
||||
};
|
||||
assert!(!flow_task.allow_sink_create);
|
||||
}
|
||||
}
|
||||
|
||||
// Non-PermissionDenied checker errors must propagate unchanged and submit no DDL task.
|
||||
for (mode, expected_status) in [
|
||||
(SinkCreateMode::InternalError, StatusCode::Unexpected),
|
||||
(SinkCreateMode::BackendError, StatusCode::StorageUnavailable),
|
||||
] {
|
||||
*checker.mode.lock().unwrap() = mode;
|
||||
let sql_err = instance
|
||||
.do_query_inner(
|
||||
"CREATE FLOW sql_err_sink SINK TO target EVAL INTERVAL '10s' AS SELECT id, ts FROM source",
|
||||
ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap_err();
|
||||
assert_eq!(expected_status, sql_err.status_code());
|
||||
|
||||
let grpc_err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
||||
&instance,
|
||||
grpc_create_flow("grpc_err_sink", false),
|
||||
ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(expected_status, grpc_err.status_code());
|
||||
assert!(executor.submitted.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
// Incremental flow where the second sink probe (`_result` view) fails with a checker error
|
||||
// also propagates the original error and submits no DDL task.
|
||||
*checker.mode.lock().unwrap() = SinkCreateMode::ErrorOnResultView;
|
||||
let probe_err = instance
|
||||
.can_create_flow_sinks(
|
||||
&ctx,
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"target".to_string(),
|
||||
Some("true"),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::Unexpected, probe_err.status_code());
|
||||
|
||||
let grpc_err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
||||
&instance,
|
||||
grpc_create_flow("grpc_err_result", true),
|
||||
ctx,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::Unexpected, grpc_err.status_code());
|
||||
assert!(executor.submitted.lock().unwrap().is_empty());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_grpc_create_flow_qualifies_sink_once() -> TestResult<()> {
|
||||
struct RecordingSinkChecker {
|
||||
checked_sinks: std::sync::Mutex<Vec<(String, String, String)>>,
|
||||
}
|
||||
|
||||
impl PermissionChecker for RecordingSinkChecker {
|
||||
fn check_permission(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
_: PermissionReq,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
Ok(PermissionResp::Allow)
|
||||
}
|
||||
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
request: &Request,
|
||||
_catalog: &str,
|
||||
_schema: &str,
|
||||
) -> PermissionTableTargets {
|
||||
match request {
|
||||
Request::Ddl(ddl)
|
||||
if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
|
||||
{
|
||||
PermissionTableTargets::resolved(vec![])
|
||||
}
|
||||
_ => PermissionTableTargets::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_: UserInfoRef,
|
||||
req: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<PermissionResp> {
|
||||
if let PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req
|
||||
&& let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr
|
||||
{
|
||||
let PermissionTableTargets::Resolved(resolved) = &targets else {
|
||||
panic!("expected resolved sink target");
|
||||
};
|
||||
assert_eq!(1, resolved.len());
|
||||
assert_eq!(resolved[0].catalog, create_table.catalog_name);
|
||||
assert_eq!(resolved[0].schema, create_table.schema_name);
|
||||
assert_eq!(resolved[0].table, create_table.table_name);
|
||||
self.checked_sinks.lock().unwrap().push((
|
||||
create_table.catalog_name.clone(),
|
||||
create_table.schema_name.clone(),
|
||||
create_table.table_name.clone(),
|
||||
));
|
||||
}
|
||||
Ok(PermissionResp::Allow)
|
||||
}
|
||||
}
|
||||
|
||||
let checker = Arc::new(RecordingSinkChecker {
|
||||
checked_sinks: Default::default(),
|
||||
});
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
||||
|
||||
let catalog =
|
||||
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
||||
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
||||
let instance = test_instance_with_catalog_manager(
|
||||
catalog,
|
||||
test_table(1025, "target")?,
|
||||
plugins,
|
||||
None,
|
||||
executor.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let ctx = QueryContextBuilder::default()
|
||||
.current_catalog("greptime".to_string())
|
||||
.current_schema("analytics".to_string())
|
||||
.build()
|
||||
.into();
|
||||
|
||||
for (flow_name, sink_catalog, sink_schema, sink_table) in [
|
||||
("flow_unqual", "", "", "unqual_sink"),
|
||||
("flow_schema_qual", "", "explicit_db", "schema_qual_sink"),
|
||||
("flow_full_qual", "other_cat", "other_db", "full_qual_sink"),
|
||||
] {
|
||||
let request = Request::Ddl(api::v1::DdlRequest {
|
||||
expr: Some(api::v1::ddl_request::Expr::CreateFlow(
|
||||
api::v1::CreateFlowExpr {
|
||||
flow_name: flow_name.to_string(),
|
||||
source_table_names: vec![api::v1::TableName {
|
||||
catalog_name: "greptime".to_string(),
|
||||
schema_name: "public".to_string(),
|
||||
table_name: "source".to_string(),
|
||||
}],
|
||||
sink_table_name: Some(api::v1::TableName {
|
||||
catalog_name: sink_catalog.to_string(),
|
||||
schema_name: sink_schema.to_string(),
|
||||
table_name: sink_table.to_string(),
|
||||
}),
|
||||
eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
|
||||
sql: "SELECT id, ts FROM greptime.public.source".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
});
|
||||
servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
||||
&instance,
|
||||
request,
|
||||
Arc::clone(&ctx),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let checked = checker.checked_sinks.lock().unwrap().clone();
|
||||
assert_eq!(
|
||||
checked,
|
||||
vec![
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"analytics".to_string(),
|
||||
"unqual_sink".to_string(),
|
||||
),
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"explicit_db".to_string(),
|
||||
"schema_qual_sink".to_string(),
|
||||
),
|
||||
(
|
||||
"other_cat".to_string(),
|
||||
"other_db".to_string(),
|
||||
"full_qual_sink".to_string(),
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
let submitted = executor.submitted.lock().unwrap();
|
||||
assert_eq!(3, submitted.len());
|
||||
let expected_sinks = [
|
||||
TableName::new("greptime", "analytics", "unqual_sink"),
|
||||
TableName::new("greptime", "explicit_db", "schema_qual_sink"),
|
||||
TableName::new("other_cat", "other_db", "full_qual_sink"),
|
||||
];
|
||||
for (task, expected_sink) in submitted.iter().zip(expected_sinks) {
|
||||
let DdlTask::CreateFlow(flow_task) = task else {
|
||||
panic!("expected CreateFlow task");
|
||||
};
|
||||
assert_eq!("greptime", flow_task.catalog_name);
|
||||
assert_eq!(expected_sink, flow_task.sink_table_name);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +123,7 @@ impl EntityGraphProviderImpl {
|
||||
ctx.current_user(),
|
||||
PermissionReq::Action(SEMANTIC_GRAPH_QUERY),
|
||||
targets,
|
||||
Some(&ctx.current_schema()),
|
||||
) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(err) if err.status_code() == StatusCode::PermissionDenied => Ok(false),
|
||||
@@ -815,6 +816,7 @@ mod tests {
|
||||
_: auth::UserInfoRef,
|
||||
_: PermissionReq,
|
||||
targets: PermissionTableTargets,
|
||||
_: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
let PermissionTableTargets::Resolved(targets) = targets else {
|
||||
panic!("entity graph must resolve its sources");
|
||||
|
||||
@@ -257,8 +257,28 @@ impl GrpcQueryHandler for Instance {
|
||||
.await?
|
||||
}
|
||||
DdlExpr::CreateFlow(expr) => {
|
||||
let allow_sink_create = if let Some(sink) = expr.sink_table_name.as_ref()
|
||||
{
|
||||
self.can_create_flow_sinks(
|
||||
&ctx,
|
||||
sink.catalog_name.clone(),
|
||||
sink.schema_name.clone(),
|
||||
sink.table_name.clone(),
|
||||
expr.flow_options.get("incremental").map(String::as_str),
|
||||
expr.flow_options
|
||||
.get("incremental_result_view")
|
||||
.map(String::as_str),
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
true
|
||||
};
|
||||
self.statement_executor
|
||||
.create_flow_inner(expr, ctx.clone())
|
||||
.create_flow_inner_with_sink_create_permission(
|
||||
expr,
|
||||
allow_sink_create,
|
||||
ctx.clone(),
|
||||
)
|
||||
.await?
|
||||
}
|
||||
DdlExpr::DropFlow(DropFlowExpr {
|
||||
@@ -335,7 +355,7 @@ fn fill_catalog_and_schema_from_context(ddl_expr: &mut DdlExpr, ctx: &QueryConte
|
||||
$expr.catalog_name = catalog.to_string();
|
||||
}
|
||||
if $expr.schema_name.is_empty() {
|
||||
$expr.schema_name = schema.to_string();
|
||||
$expr.schema_name = schema.clone();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -358,6 +378,9 @@ fn fill_catalog_and_schema_from_context(ddl_expr: &mut DdlExpr, ctx: &QueryConte
|
||||
if expr.catalog_name.is_empty() {
|
||||
expr.catalog_name = catalog.to_string();
|
||||
}
|
||||
if let Some(sink) = expr.sink_table_name.as_mut() {
|
||||
check_and_fill!(sink);
|
||||
}
|
||||
}
|
||||
Expr::DropFlow(expr) => {
|
||||
if expr.catalog_name.is_empty() {
|
||||
@@ -386,7 +409,12 @@ impl Instance {
|
||||
self.plugins
|
||||
.get::<PermissionCheckerRef>()
|
||||
.as_ref()
|
||||
.check_permission_with_table_targets(ctx.current_user(), req, targets)
|
||||
.check_permission_with_table_targets(
|
||||
ctx.current_user(),
|
||||
req,
|
||||
targets,
|
||||
Some(&ctx.current_schema()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Checks every logical table targeted by normalized row inserts.
|
||||
@@ -471,6 +499,7 @@ impl Instance {
|
||||
table: &table_name.table_name,
|
||||
},
|
||||
PermissionTableTargets::resolved(vec![target]),
|
||||
Some(&ctx.current_schema()),
|
||||
).context(PermissionSnafu)?;
|
||||
|
||||
// Check permissions for the table
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use auth::{PermissionReq, PermissionTableTarget, PermissionTableTargets};
|
||||
use auth::{
|
||||
PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
|
||||
PermissionTableTargets,
|
||||
};
|
||||
use common_query::Output;
|
||||
use session::context::QueryContextRef;
|
||||
use snafu::ResultExt;
|
||||
@@ -30,6 +33,15 @@ impl Instance {
|
||||
stmt: &Statement,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
self.plugins
|
||||
.get::<PermissionCheckerRef>()
|
||||
.as_ref()
|
||||
.check_permission_with_context(
|
||||
ctx.current_user(),
|
||||
PermissionReq::SqlStatement(stmt),
|
||||
Some(&ctx.current_schema()),
|
||||
)
|
||||
.context(PermissionSnafu)?;
|
||||
let req = operator::statement::to_copy_database_request(arg, &ctx)?;
|
||||
let plan = self
|
||||
.statement_executor
|
||||
|
||||
@@ -206,17 +206,17 @@ impl<'a> StatementToRegion<'a> {
|
||||
[table] => Ok((
|
||||
self.ctx.current_catalog().to_owned(),
|
||||
self.ctx.current_schema(),
|
||||
table.to_string_unquoted(),
|
||||
table.to_string_normalized(),
|
||||
)),
|
||||
[schema, table] => Ok((
|
||||
self.ctx.current_catalog().to_owned(),
|
||||
schema.to_string_unquoted(),
|
||||
table.to_string_unquoted(),
|
||||
schema.to_string_normalized(),
|
||||
table.to_string_normalized(),
|
||||
)),
|
||||
[catalog, schema, table] => Ok((
|
||||
catalog.to_string_unquoted(),
|
||||
schema.to_string_unquoted(),
|
||||
table.to_string_unquoted(),
|
||||
catalog.to_string_normalized(),
|
||||
schema.to_string_normalized(),
|
||||
table.to_string_normalized(),
|
||||
)),
|
||||
_ => InvalidSqlSnafu {
|
||||
err_msg: format!(
|
||||
|
||||
@@ -42,7 +42,7 @@ use common_meta::cache_invalidator::CacheInvalidatorRef;
|
||||
use common_meta::cache_invalidator::Context;
|
||||
use common_meta::ddl::create_flow::{
|
||||
DEFER_ON_MISSING_SOURCE_KEY, FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType,
|
||||
INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY,
|
||||
INTERNAL_ALLOW_SINK_CREATE_KEY, INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY,
|
||||
};
|
||||
use common_meta::instruction::CacheIdent;
|
||||
#[cfg(feature = "enterprise")]
|
||||
@@ -229,7 +229,10 @@ fn validate_and_normalize_flow_options(
|
||||
.map(|(key, value)| {
|
||||
if matches!(
|
||||
key.as_str(),
|
||||
FlowType::FLOW_TYPE_KEY | INTERNAL_EVAL_OFFSET_KEY | INTERNAL_EVAL_SCHEDULE_KEY
|
||||
FlowType::FLOW_TYPE_KEY
|
||||
| INTERNAL_EVAL_OFFSET_KEY
|
||||
| INTERNAL_EVAL_SCHEDULE_KEY
|
||||
| INTERNAL_ALLOW_SINK_CREATE_KEY
|
||||
) {
|
||||
return InvalidSqlSnafu {
|
||||
err_msg: format!("flow option '{key}' is reserved for internal use"),
|
||||
@@ -938,6 +941,18 @@ impl StatementExecutor {
|
||||
&self,
|
||||
stmt: CreateFlow,
|
||||
query_context: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
self.create_flow_with_sink_create_permission(stmt, true, query_context)
|
||||
.await
|
||||
}
|
||||
|
||||
/// SQL entry point for `CREATE FLOW` with pre-evaluated sink-table create permission.
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn create_flow_with_sink_create_permission(
|
||||
&self,
|
||||
stmt: CreateFlow,
|
||||
allow_sink_create: bool,
|
||||
query_context: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
// TODO(ruihang): do some verification
|
||||
let eval_offset_secs = stmt.eval_offset;
|
||||
@@ -945,7 +960,7 @@ impl StatementExecutor {
|
||||
|
||||
// The typed `EVAL OFFSET` comes straight from the parsed SQL AST; it is
|
||||
// the only trusted source of the offset at this boundary.
|
||||
self.create_flow_procedure(expr, eval_offset_secs, query_context)
|
||||
self.create_flow_procedure(expr, eval_offset_secs, allow_sink_create, query_context)
|
||||
.await?;
|
||||
Ok(Output::new_with_affected_rows(0))
|
||||
}
|
||||
@@ -956,7 +971,18 @@ impl StatementExecutor {
|
||||
expr: CreateFlowExpr,
|
||||
query_context: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
self.create_flow_procedure(expr, None, query_context)
|
||||
self.create_flow_inner_with_sink_create_permission(expr, true, query_context)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Direct gRPC entry point for `CREATE FLOW` with pre-evaluated sink-table create permission.
|
||||
pub async fn create_flow_inner_with_sink_create_permission(
|
||||
&self,
|
||||
expr: CreateFlowExpr,
|
||||
allow_sink_create: bool,
|
||||
query_context: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
self.create_flow_procedure(expr, None, allow_sink_create, query_context)
|
||||
.await?;
|
||||
Ok(Output::new_with_affected_rows(0))
|
||||
}
|
||||
@@ -965,6 +991,7 @@ impl StatementExecutor {
|
||||
&self,
|
||||
mut expr: CreateFlowExpr,
|
||||
eval_offset_secs: Option<i64>,
|
||||
allow_sink_create: bool,
|
||||
query_context: QueryContextRef,
|
||||
) -> Result<SubmitDdlTaskResponse> {
|
||||
let eval_interval_secs = expr.eval_interval.as_ref().map(|e| e.seconds);
|
||||
@@ -1003,6 +1030,7 @@ impl StatementExecutor {
|
||||
})
|
||||
.context(error::InvalidExprSnafu)?;
|
||||
task.eval_offset_secs = eval_offset_secs;
|
||||
task.allow_sink_create = allow_sink_create;
|
||||
let executor_context = to_executor_context(query_context, TriggerReason::Manual);
|
||||
let request = SubmitDdlTaskRequest::new(DdlTask::new_create_flow(task));
|
||||
|
||||
|
||||
@@ -48,17 +48,17 @@ pub fn table_idents_to_full_name(
|
||||
[table] => Ok((
|
||||
query_ctx.current_catalog().to_string(),
|
||||
query_ctx.current_schema().clone(),
|
||||
table.to_string_unquoted(),
|
||||
table.to_string_normalized(),
|
||||
)),
|
||||
[schema, table] => Ok((
|
||||
query_ctx.current_catalog().to_string(),
|
||||
schema.to_string_unquoted(),
|
||||
table.to_string_unquoted(),
|
||||
schema.to_string_normalized(),
|
||||
table.to_string_normalized(),
|
||||
)),
|
||||
[catalog, schema, table] => Ok((
|
||||
catalog.to_string_unquoted(),
|
||||
schema.to_string_unquoted(),
|
||||
table.to_string_unquoted(),
|
||||
catalog.to_string_normalized(),
|
||||
schema.to_string_normalized(),
|
||||
table.to_string_normalized(),
|
||||
)),
|
||||
_ => InvalidSqlSnafu {
|
||||
msg: format!(
|
||||
@@ -67,3 +67,135 @@ pub fn table_idents_to_full_name(
|
||||
}.fail(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use sql::dialect::GreptimeDbDialect;
|
||||
use sql::parser::{ParseOptions, ParserContext};
|
||||
use sql::statements::statement::Statement;
|
||||
use sql::util::extract_tables_from_statement_checked;
|
||||
|
||||
use super::*;
|
||||
use crate::context::QueryContext;
|
||||
|
||||
#[test]
|
||||
fn test_table_idents_to_full_name_quote_aware_normalization() {
|
||||
let query_ctx = Arc::new(QueryContext::with("greptime", "public"));
|
||||
|
||||
let extract_single = |sql: &str| -> ObjectName {
|
||||
let stmt = ParserContext::create_with_dialect(
|
||||
sql,
|
||||
&GreptimeDbDialect {},
|
||||
ParseOptions::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.remove(0);
|
||||
let mut tables = extract_tables_from_statement_checked(&stmt).unwrap();
|
||||
let table = tables.next().unwrap();
|
||||
assert!(tables.next().is_none());
|
||||
table
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&extract_single("SELECT * FROM Readings"), &query_ctx)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&extract_single("SELECT * FROM Public.Readings"), &query_ctx)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(
|
||||
&extract_single("SELECT * FROM Greptime.Public.Readings"),
|
||||
&query_ctx
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"Readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&extract_single(r#"SELECT * FROM "Readings""#), &query_ctx)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"Public".to_string(),
|
||||
"Readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(
|
||||
&extract_single(r#"SELECT * FROM "Public"."Readings""#),
|
||||
&query_ctx
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"Readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&extract_single("SELECT * FROM `Readings`"), &query_ctx)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"\u{212A}pi".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&extract_single("SELECT * FROM \u{212A}PI"), &query_ctx)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"\u{212A}PI".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&extract_single("SELECT * FROM \"\u{212A}PI\""), &query_ctx)
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
let stmt = ParserContext::create_with_dialect(
|
||||
"TQL EVAL (0, 10, '5s') Readings",
|
||||
&GreptimeDbDialect {},
|
||||
ParseOptions::default(),
|
||||
)
|
||||
.unwrap()
|
||||
.remove(0);
|
||||
assert!(matches!(stmt, Statement::Tql(_)));
|
||||
let tql_table = extract_tables_from_statement_checked(&stmt)
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
"greptime".to_string(),
|
||||
"public".to_string(),
|
||||
"Readings".to_string()
|
||||
),
|
||||
table_idents_to_full_name(&tql_table, &query_ctx).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+39
-1
@@ -19,8 +19,24 @@ pub use sqlparser::ast::{
|
||||
visit_expressions_mut, visit_statements_mut,
|
||||
};
|
||||
|
||||
/// Normalizes an identifier using ASCII-only case folding when unquoted,
|
||||
/// preserving exact casing for quoted identifiers (matching DataFusion's
|
||||
/// `IdentNormalizer` with `enable_ident_normalization = true`).
|
||||
pub fn normalize_ident(ident: &Ident) -> String {
|
||||
if ident.quote_style.is_some() {
|
||||
ident.value.clone()
|
||||
} else {
|
||||
ident.value.to_ascii_lowercase()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ObjectNamePartExt {
|
||||
fn to_string_unquoted(&self) -> String;
|
||||
|
||||
/// Returns the identifier string normalized with ASCII-only lowercase when
|
||||
/// unquoted, preserving original casing for quoted identifiers (matching
|
||||
/// DataFusion's SQL planner with `enable_ident_normalization = true`).
|
||||
fn to_string_normalized(&self) -> String;
|
||||
}
|
||||
|
||||
impl ObjectNamePartExt for ObjectNamePart {
|
||||
@@ -31,6 +47,13 @@ impl ObjectNamePartExt for ObjectNamePart {
|
||||
};
|
||||
ident.value.clone()
|
||||
}
|
||||
|
||||
fn to_string_normalized(&self) -> String {
|
||||
let ObjectNamePart::Identifier(ident) = self else {
|
||||
return self.to_string();
|
||||
};
|
||||
normalize_ident(ident)
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats an object name by joining its identifier values without quotes.
|
||||
@@ -46,7 +69,7 @@ pub fn object_name_to_string_unquoted(name: &ObjectName) -> String {
|
||||
mod tests {
|
||||
use sqlparser::ast::{Ident, ObjectName, ObjectNamePart};
|
||||
|
||||
use super::object_name_to_string_unquoted;
|
||||
use super::{ObjectNamePartExt, object_name_to_string_unquoted};
|
||||
|
||||
#[test]
|
||||
fn test_object_name_to_string_unquoted() {
|
||||
@@ -65,4 +88,19 @@ mod tests {
|
||||
object_name_to_string_unquoted("ed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_object_name_part_to_string_normalized() {
|
||||
let unquoted = ObjectNamePart::Identifier(Ident::new("Readings"));
|
||||
let double_quoted = ObjectNamePart::Identifier(Ident::with_quote('"', "Readings"));
|
||||
let backtick_quoted = ObjectNamePart::Identifier(Ident::with_quote('`', "Readings"));
|
||||
let kelvin_unquoted = ObjectNamePart::Identifier(Ident::new("\u{212A}PI"));
|
||||
let kelvin_quoted = ObjectNamePart::Identifier(Ident::with_quote('"', "\u{212A}PI"));
|
||||
|
||||
assert_eq!("readings", unquoted.to_string_normalized());
|
||||
assert_eq!("Readings", double_quoted.to_string_normalized());
|
||||
assert_eq!("Readings", backtick_quoted.to_string_normalized());
|
||||
assert_eq!("\u{212A}pi", kelvin_unquoted.to_string_normalized());
|
||||
assert_eq!("\u{212A}PI", kelvin_quoted.to_string_normalized());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,8 +73,6 @@ pub fn is_tql(dialect: &dyn Dialect, sql: &str) -> Result<bool> {
|
||||
}
|
||||
|
||||
pub(crate) fn is_simple_tql_cte_query(query: &Query) -> bool {
|
||||
use crate::parser::ParserContext;
|
||||
|
||||
let Some(hybrid_cte) = &query.hybrid_cte else {
|
||||
return false;
|
||||
};
|
||||
@@ -94,8 +92,8 @@ pub(crate) fn is_simple_tql_cte_query(query: &Query) -> bool {
|
||||
return false;
|
||||
};
|
||||
|
||||
let reference = ParserContext::canonicalize_identifier(reference).value;
|
||||
let cte_name = ParserContext::canonicalize_identifier(cte.name.clone()).value;
|
||||
let reference = crate::ast::normalize_ident(&reference);
|
||||
let cte_name = crate::ast::normalize_ident(&cte.name);
|
||||
reference == cte_name
|
||||
}
|
||||
|
||||
|
||||
@@ -168,7 +168,11 @@ impl ParserContext<'_> {
|
||||
fn parse_hybrid_cte(&mut self, require_now_expr: bool) -> Result<HybridCte> {
|
||||
// Parse CTE name
|
||||
let name = self.parser.parse_identifier().context(error::SyntaxSnafu)?;
|
||||
let name = Self::canonicalize_identifier(name);
|
||||
let name = if name.quote_style.is_some() {
|
||||
name
|
||||
} else {
|
||||
Ident::new(name.value.to_ascii_lowercase())
|
||||
};
|
||||
|
||||
// Parse optional column list
|
||||
let columns = self
|
||||
|
||||
+42
-19
@@ -29,9 +29,8 @@ use sqlparser::ast::{
|
||||
};
|
||||
use sqlparser_derive::{Visit, VisitMut};
|
||||
|
||||
use crate::ast::ObjectNamePartExt;
|
||||
use crate::ast::{ObjectNamePartExt, normalize_ident};
|
||||
use crate::error::{InvalidExprAsOptionValueSnafu, InvalidSqlSnafu, Result};
|
||||
use crate::parser::ParserContext;
|
||||
use crate::parsers::with_tql_parser::CteContent;
|
||||
use crate::statements::alter::AlterTableOperation;
|
||||
use crate::statements::comment::CommentObject;
|
||||
@@ -261,7 +260,7 @@ fn extract_tables_from_statement(stmt: &Statement, names: &mut HashSet<ObjectNam
|
||||
if let AlterTableOperation::RenameTable { new_table_name } = alter.alter_operation() {
|
||||
let mut renamed = current;
|
||||
if let Some(last) = renamed.0.last_mut() {
|
||||
*last = ObjectNamePart::Identifier(Ident::new(new_table_name));
|
||||
*last = ObjectNamePart::Identifier(Ident::with_quote('"', new_table_name));
|
||||
}
|
||||
names.insert(renamed);
|
||||
}
|
||||
@@ -398,8 +397,8 @@ fn collect_relations(ast: &impl AstVisit, names: &mut HashSet<ObjectName>) {
|
||||
|
||||
fn metadata_table_name(table: &str, database: Option<&str>) -> ObjectName {
|
||||
let mut parts = Vec::with_capacity(usize::from(database.is_some()) + 1);
|
||||
parts.extend(database.map(Ident::new));
|
||||
parts.push(Ident::new(table));
|
||||
parts.extend(database.map(|db| Ident::with_quote('"', db)));
|
||||
parts.push(Ident::with_quote('"', table));
|
||||
ObjectName::from(parts)
|
||||
}
|
||||
|
||||
@@ -429,7 +428,7 @@ fn extract_tables_from_hybrid_cte_query(
|
||||
let cte_names: HashSet<String> = hybrid_cte
|
||||
.cte_tables
|
||||
.iter()
|
||||
.map(|cte| ParserContext::canonicalize_identifier(cte.name.clone()).value)
|
||||
.map(|cte| normalize_ident(&cte.name))
|
||||
.collect();
|
||||
remove_cte_names(sql_names, &cte_names);
|
||||
|
||||
@@ -460,7 +459,7 @@ fn remove_cte_names(names: &mut HashSet<ObjectName>, cte_names: &HashSet<String>
|
||||
return true;
|
||||
};
|
||||
|
||||
let canonical = ParserContext::canonicalize_identifier(ident.clone()).value;
|
||||
let canonical = normalize_ident(ident);
|
||||
!cte_names.contains(&canonical)
|
||||
});
|
||||
}
|
||||
@@ -518,9 +517,9 @@ fn extract_tables_from_prom_expr(expr: &PromExpr, names: &mut HashSet<ObjectName
|
||||
Some(_) => return true,
|
||||
}
|
||||
self.names
|
||||
.insert(ObjectName(vec![ObjectNamePart::Identifier(Ident::new(
|
||||
DEFAULT_INFO_METRIC,
|
||||
))]));
|
||||
.insert(ObjectName(vec![ObjectNamePart::Identifier(
|
||||
Ident::with_quote('"', DEFAULT_INFO_METRIC),
|
||||
)]));
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -597,13 +596,13 @@ fn extract_metric_name_from_vector_selector(
|
||||
|
||||
if let Some(schema) = schema_matcher {
|
||||
names.insert(ObjectName(vec![
|
||||
ObjectNamePart::Identifier(Ident::new(&schema.value)),
|
||||
ObjectNamePart::Identifier(Ident::new(metric_name)),
|
||||
ObjectNamePart::Identifier(Ident::with_quote('"', &schema.value)),
|
||||
ObjectNamePart::Identifier(Ident::with_quote('"', metric_name)),
|
||||
]));
|
||||
} else {
|
||||
names.insert(ObjectName(vec![ObjectNamePart::Identifier(Ident::new(
|
||||
metric_name,
|
||||
))]));
|
||||
names.insert(ObjectName(vec![ObjectNamePart::Identifier(
|
||||
Ident::with_quote('"', metric_name),
|
||||
)]));
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -683,7 +682,7 @@ impl Visitor for RelationCollector<'_> {
|
||||
(
|
||||
with.cte_tables
|
||||
.iter()
|
||||
.map(|cte| ParserContext::canonicalize_identifier(cte.alias.name.clone()).value)
|
||||
.map(|cte| normalize_ident(&cte.alias.name))
|
||||
.collect(),
|
||||
with.recursive,
|
||||
)
|
||||
@@ -717,9 +716,7 @@ impl Visitor for RelationCollector<'_> {
|
||||
relation.0.as_slice(),
|
||||
[part]
|
||||
if part.as_ident().is_some_and(|ident| {
|
||||
self.ctes_in_scope.contains(
|
||||
&ParserContext::canonicalize_identifier(ident.clone()).value,
|
||||
)
|
||||
self.ctes_in_scope.contains(&normalize_ident(ident))
|
||||
})
|
||||
);
|
||||
if !is_cte {
|
||||
@@ -732,6 +729,20 @@ impl Visitor for RelationCollector<'_> {
|
||||
/// Helper function for [extract_tables_from_query].
|
||||
///
|
||||
/// Handle [sqlparser::ast::Query].
|
||||
pub fn extract_tables_from_sql_query_ast(query: &sqlparser::ast::Query) -> HashSet<ObjectName> {
|
||||
let mut names = HashSet::new();
|
||||
extract_tables_from_sql_query(query, &mut names);
|
||||
names
|
||||
}
|
||||
|
||||
/// Walks any sqlparser AST node using [`RelationCollector`] so CTE aliases are
|
||||
/// scoped accurately while collecting all referenced table relations.
|
||||
pub fn collect_relations_from_ast(ast: &impl AstVisit) -> HashSet<ObjectName> {
|
||||
let mut names = HashSet::new();
|
||||
collect_relations(ast, &mut names);
|
||||
names
|
||||
}
|
||||
|
||||
fn extract_tables_from_sql_query(query: &sqlparser::ast::Query, names: &mut HashSet<ObjectName>) {
|
||||
let _ = query.visit(&mut RelationCollector::new(names));
|
||||
}
|
||||
@@ -1089,6 +1100,18 @@ SELECT * FROM (
|
||||
"#,
|
||||
vec!["nested_source".to_string()],
|
||||
),
|
||||
(
|
||||
"WITH \u{212A}pi AS (SELECT 1) SELECT * FROM kpi;",
|
||||
vec!["kpi".to_string()],
|
||||
),
|
||||
(
|
||||
"WITH \u{212A}pi AS (SELECT 1) SELECT * FROM \u{212A}PI;",
|
||||
vec![],
|
||||
),
|
||||
(
|
||||
"SELECT * FROM (WITH \u{212A}pi AS (SELECT 1) SELECT * FROM kpi);",
|
||||
vec!["kpi".to_string()],
|
||||
),
|
||||
];
|
||||
|
||||
for (sql, expected_tables) in testcases {
|
||||
|
||||
@@ -723,6 +723,7 @@ mod tests {
|
||||
_: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
if !matches!(req, auth::PermissionReq::Action(auth::PROMQL_QUERY)) {
|
||||
return Ok(auth::PermissionResp::Allow);
|
||||
@@ -859,6 +860,7 @@ mod tests {
|
||||
_user_info: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
if matches!(req, auth::PermissionReq::Action(auth::SEMANTIC_GRAPH_QUERY))
|
||||
&& let auth::PermissionTableTargets::Resolved(targets) = targets
|
||||
@@ -1024,6 +1026,7 @@ mod tests {
|
||||
_user_info: auth::UserInfoRef,
|
||||
_req: auth::PermissionReq,
|
||||
targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
if let auth::PermissionTableTargets::Resolved(targets) = targets
|
||||
&& targets
|
||||
@@ -1111,4 +1114,347 @@ mod tests {
|
||||
"denied descriptor table was created:\n{pretty_print}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_create_flow_sink_denial_vs_checker_error() {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use api::v1::greptime_request::Request;
|
||||
use servers::query_handler::grpc::GrpcQueryHandler;
|
||||
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SinkCreateMode {
|
||||
Allow,
|
||||
Deny,
|
||||
InternalFailure,
|
||||
}
|
||||
|
||||
struct ToggleSinkCreateChecker {
|
||||
mode: Mutex<SinkCreateMode>,
|
||||
}
|
||||
|
||||
impl auth::PermissionChecker for ToggleSinkCreateChecker {
|
||||
fn check_permission(
|
||||
&self,
|
||||
_user_info: auth::UserInfoRef,
|
||||
_req: auth::PermissionReq,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
Ok(auth::PermissionResp::Allow)
|
||||
}
|
||||
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
request: &Request,
|
||||
_catalog: &str,
|
||||
_schema: &str,
|
||||
) -> auth::PermissionTableTargets {
|
||||
match request {
|
||||
Request::Ddl(ddl)
|
||||
if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
|
||||
{
|
||||
auth::PermissionTableTargets::resolved(vec![])
|
||||
}
|
||||
_ => auth::PermissionTableTargets::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_user_info: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
_targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
let auth::PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req else {
|
||||
return Ok(auth::PermissionResp::Allow);
|
||||
};
|
||||
if !matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateTable(_))) {
|
||||
return Ok(auth::PermissionResp::Allow);
|
||||
}
|
||||
match *self.mode.lock().unwrap() {
|
||||
SinkCreateMode::Allow => Ok(auth::PermissionResp::Allow),
|
||||
SinkCreateMode::Deny => Ok(auth::PermissionResp::Reject),
|
||||
SinkCreateMode::InternalFailure => auth::error::InternalStateSnafu {
|
||||
msg: "auth backend down",
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let checker = Arc::new(ToggleSinkCreateChecker {
|
||||
mode: Mutex::new(SinkCreateMode::Allow),
|
||||
});
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<auth::PermissionCheckerRef>(checker.clone());
|
||||
|
||||
let standalone =
|
||||
GreptimeDbStandaloneBuilder::new("test_create_flow_sink_denial_vs_checker_error")
|
||||
.with_plugin(plugins)
|
||||
.build()
|
||||
.await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
|
||||
create_table(
|
||||
&instance,
|
||||
"CREATE TABLE flow_src (val INT, ts TIMESTAMP TIME INDEX)",
|
||||
)
|
||||
.await;
|
||||
create_table(
|
||||
&instance,
|
||||
"CREATE TABLE existing_sink (val INT, ts TIMESTAMP TIME INDEX)",
|
||||
)
|
||||
.await;
|
||||
|
||||
let grpc_create_flow = |flow_name: &str, sink_name: &str| {
|
||||
Request::Ddl(api::v1::DdlRequest {
|
||||
expr: Some(api::v1::ddl_request::Expr::CreateFlow(
|
||||
api::v1::CreateFlowExpr {
|
||||
flow_name: flow_name.to_string(),
|
||||
source_table_names: vec![api::v1::TableName {
|
||||
catalog_name: DEFAULT_CATALOG_NAME.to_string(),
|
||||
schema_name: DEFAULT_SCHEMA_NAME.to_string(),
|
||||
table_name: "flow_src".to_string(),
|
||||
}],
|
||||
sink_table_name: Some(api::v1::TableName {
|
||||
catalog_name: DEFAULT_CATALOG_NAME.to_string(),
|
||||
schema_name: DEFAULT_SCHEMA_NAME.to_string(),
|
||||
table_name: sink_name.to_string(),
|
||||
}),
|
||||
eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
|
||||
sql: "SELECT val, ts FROM flow_src".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
})
|
||||
};
|
||||
|
||||
// Denying `table.create` still allows creating flows against an existing sink.
|
||||
*checker.mode.lock().unwrap() = SinkCreateMode::Deny;
|
||||
query(
|
||||
&instance,
|
||||
"CREATE FLOW flow_existing_sql SINK TO existing_sink EVAL INTERVAL '10s' AS SELECT val, ts FROM flow_src",
|
||||
)
|
||||
.await;
|
||||
GrpcQueryHandler::do_query(
|
||||
&*instance,
|
||||
grpc_create_flow("flow_existing_grpc", "existing_sink"),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Missing sink with denied `table.create` must fail with PermissionDenied.
|
||||
let denied_err = SqlQueryHandler::do_query(
|
||||
&*instance,
|
||||
"CREATE FLOW flow_missing_denied SINK TO missing_sink EVAL INTERVAL '10s' AS SELECT val, ts FROM flow_src",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::PermissionDenied, denied_err.status_code());
|
||||
|
||||
// Checker failures must propagate with their original status and create no flow.
|
||||
*checker.mode.lock().unwrap() = SinkCreateMode::InternalFailure;
|
||||
let sql_err = SqlQueryHandler::do_query(
|
||||
&*instance,
|
||||
"CREATE FLOW flow_err_sql SINK TO existing_sink EVAL INTERVAL '10s' AS SELECT val, ts FROM flow_src",
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await
|
||||
.remove(0)
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::Unexpected, sql_err.status_code());
|
||||
|
||||
let grpc_err = GrpcQueryHandler::do_query(
|
||||
&*instance,
|
||||
grpc_create_flow("flow_err_grpc", "existing_sink"),
|
||||
QueryContext::arc(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::Unexpected, grpc_err.status_code());
|
||||
|
||||
*checker.mode.lock().unwrap() = SinkCreateMode::Allow;
|
||||
let output = query(
|
||||
&instance,
|
||||
"SELECT flow_name FROM information_schema.flows ORDER BY flow_name",
|
||||
)
|
||||
.await;
|
||||
let OutputData::Stream(s) = output.data else {
|
||||
unreachable!()
|
||||
};
|
||||
let batches = common_recordbatch::util::collect_batches(s).await.unwrap();
|
||||
let pretty = batches.pretty_print().unwrap();
|
||||
assert!(pretty.contains("flow_existing_sql"), "{pretty}");
|
||||
assert!(pretty.contains("flow_existing_grpc"), "{pretty}");
|
||||
assert!(!pretty.contains("flow_missing_denied"), "{pretty}");
|
||||
assert!(!pretty.contains("flow_err_sql"), "{pretty}");
|
||||
assert!(!pretty.contains("flow_err_grpc"), "{pretty}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_grpc_create_flow_sink_namespace_persistence() {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use api::v1::greptime_request::Request;
|
||||
use servers::query_handler::grpc::GrpcQueryHandler;
|
||||
use session::context::QueryContextBuilder;
|
||||
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
struct RecordingSinkChecker {
|
||||
checked: Mutex<Vec<(String, String, String)>>,
|
||||
}
|
||||
|
||||
impl auth::PermissionChecker for RecordingSinkChecker {
|
||||
fn check_permission(
|
||||
&self,
|
||||
_user_info: auth::UserInfoRef,
|
||||
_req: auth::PermissionReq,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
Ok(auth::PermissionResp::Allow)
|
||||
}
|
||||
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
request: &Request,
|
||||
_catalog: &str,
|
||||
_schema: &str,
|
||||
) -> auth::PermissionTableTargets {
|
||||
match request {
|
||||
Request::Ddl(ddl)
|
||||
if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
|
||||
{
|
||||
auth::PermissionTableTargets::resolved(vec![])
|
||||
}
|
||||
_ => auth::PermissionTableTargets::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_user_info: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
_targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
if let auth::PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req
|
||||
&& let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr
|
||||
{
|
||||
self.checked.lock().unwrap().push((
|
||||
create_table.catalog_name.clone(),
|
||||
create_table.schema_name.clone(),
|
||||
create_table.table_name.clone(),
|
||||
));
|
||||
}
|
||||
Ok(auth::PermissionResp::Allow)
|
||||
}
|
||||
}
|
||||
|
||||
let checker = Arc::new(RecordingSinkChecker {
|
||||
checked: Mutex::new(Vec::new()),
|
||||
});
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<auth::PermissionCheckerRef>(checker.clone());
|
||||
|
||||
let standalone =
|
||||
GreptimeDbStandaloneBuilder::new("test_grpc_create_flow_sink_namespace_persistence")
|
||||
.with_plugin(plugins)
|
||||
.build()
|
||||
.await;
|
||||
let instance = standalone.fe_instance().clone();
|
||||
|
||||
query(&instance, "CREATE DATABASE session_db").await;
|
||||
query(&instance, "CREATE DATABASE explicit_db").await;
|
||||
create_table(
|
||||
&instance,
|
||||
"CREATE TABLE session_db.src_tbl (val INT, ts TIMESTAMP TIME INDEX)",
|
||||
)
|
||||
.await;
|
||||
create_table(
|
||||
&instance,
|
||||
"CREATE TABLE session_db.unqual_sink (val INT, ts TIMESTAMP TIME INDEX)",
|
||||
)
|
||||
.await;
|
||||
create_table(
|
||||
&instance,
|
||||
"CREATE TABLE explicit_db.qual_sink (val INT, ts TIMESTAMP TIME INDEX)",
|
||||
)
|
||||
.await;
|
||||
|
||||
let ctx: QueryContextRef = QueryContextBuilder::default()
|
||||
.current_catalog(DEFAULT_CATALOG_NAME.to_string())
|
||||
.current_schema("session_db".to_string())
|
||||
.build()
|
||||
.into();
|
||||
|
||||
for (flow_name, sink_schema, sink_table) in [
|
||||
("flow_unqual_sink", "", "unqual_sink"),
|
||||
("flow_qual_sink", "explicit_db", "qual_sink"),
|
||||
] {
|
||||
let request = Request::Ddl(api::v1::DdlRequest {
|
||||
expr: Some(api::v1::ddl_request::Expr::CreateFlow(
|
||||
api::v1::CreateFlowExpr {
|
||||
flow_name: flow_name.to_string(),
|
||||
source_table_names: vec![api::v1::TableName {
|
||||
catalog_name: DEFAULT_CATALOG_NAME.to_string(),
|
||||
schema_name: "session_db".to_string(),
|
||||
table_name: "src_tbl".to_string(),
|
||||
}],
|
||||
sink_table_name: Some(api::v1::TableName {
|
||||
catalog_name: String::new(),
|
||||
schema_name: sink_schema.to_string(),
|
||||
table_name: sink_table.to_string(),
|
||||
}),
|
||||
eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
|
||||
sql: "SELECT val, ts FROM session_db.src_tbl".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
)),
|
||||
});
|
||||
GrpcQueryHandler::do_query(&*instance, request, Arc::clone(&ctx))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
*checker.checked.lock().unwrap(),
|
||||
vec![
|
||||
(
|
||||
DEFAULT_CATALOG_NAME.to_string(),
|
||||
"session_db".to_string(),
|
||||
"unqual_sink".to_string(),
|
||||
),
|
||||
(
|
||||
DEFAULT_CATALOG_NAME.to_string(),
|
||||
"explicit_db".to_string(),
|
||||
"qual_sink".to_string(),
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
let output = query(
|
||||
&instance,
|
||||
"SELECT flow_name, sink_table_name FROM information_schema.flows ORDER BY flow_name",
|
||||
)
|
||||
.await;
|
||||
let OutputData::Stream(s) = output.data else {
|
||||
unreachable!()
|
||||
};
|
||||
let batches = common_recordbatch::util::collect_batches(s).await.unwrap();
|
||||
let pretty = batches.pretty_print().unwrap();
|
||||
assert!(
|
||||
pretty.contains("flow_unqual_sink")
|
||||
&& pretty.contains("greptime.session_db.unqual_sink"),
|
||||
"{pretty}"
|
||||
);
|
||||
assert!(
|
||||
pretty.contains("flow_qual_sink") && pretty.contains("greptime.explicit_db.qual_sink"),
|
||||
"{pretty}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3436,6 +3436,7 @@ WITH(
|
||||
_user_info: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
if matches!(req, auth::PermissionReq::Action(auth::OTLP_WRITE)) {
|
||||
let auth::PermissionTableTargets::Resolved(targets) = targets else {
|
||||
|
||||
@@ -1777,6 +1777,7 @@ async fn test_postgres_copy_in_prom_write_batching_parity() {
|
||||
_: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
if matches!(req, auth::PermissionReq::Action(auth::PROM_STORE_WRITE)) {
|
||||
assert!(
|
||||
|
||||
@@ -1013,6 +1013,7 @@ async fn packed_copy_standalone_heterogeneous_streams() {
|
||||
_: auth::UserInfoRef,
|
||||
req: auth::PermissionReq,
|
||||
targets: auth::PermissionTableTargets,
|
||||
_current_schema: Option<&str>,
|
||||
) -> auth::error::Result<auth::PermissionResp> {
|
||||
let denied = self.0.load(std::sync::atomic::Ordering::SeqCst)
|
||||
&& !req.is_readonly()
|
||||
|
||||
Reference in New Issue
Block a user