Skip to main content

frontend/
instance.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod builder;
16mod copy_in;
17mod dashboard;
18mod entity_graph;
19mod exemplar;
20mod export_database;
21mod grpc;
22mod import_packed;
23mod influxdb;
24mod jaeger;
25mod log_handler;
26mod logical_batcher;
27mod logs;
28mod opentsdb;
29mod otlp;
30pub mod prom_store;
31mod promql;
32mod promql_rollup_cache;
33mod region_query;
34mod schema_selection;
35
36use std::collections::HashSet;
37use std::pin::Pin;
38use std::sync::atomic::AtomicBool;
39use std::sync::{Arc, OnceLock, atomic};
40use std::time::{Duration, SystemTime};
41
42use async_stream::stream;
43use async_trait::async_trait;
44use auth::{
45    COPY_TO, PROMQL_QUERY, PermissionChecker, PermissionCheckerRef, PermissionReq,
46    PermissionTableTarget, PermissionTableTargets, TableTargetPrecheck,
47};
48use catalog::CatalogManagerRef;
49use catalog::process_manager::{
50    ProcessManagerRef, QueryStatement as CatalogQueryStatement, SlowQueryRecorder, SlowQueryTimer,
51};
52use client::OutputData;
53use common_base::Plugins;
54use common_base::cancellation::CancellableFuture;
55use common_batcher::request_limiter::RequestLimiter;
56use common_error::ext::{BoxedError, ErrorExt};
57use common_event_recorder::EventRecorderRef;
58use common_meta::cache::TableFlownodeSetCacheRef;
59use common_meta::cache_invalidator::CacheInvalidatorRef;
60use common_meta::key::TableMetadataManagerRef;
61use common_meta::node_manager::NodeManagerRef;
62use common_meta::procedure_executor::ProcedureExecutorRef;
63use common_query::{Output, OutputMeta};
64use common_recordbatch::RecordBatchStreamWrapper;
65use common_recordbatch::error::StreamTimeoutSnafu;
66use common_telemetry::logging::SlowQueryOptions;
67use common_telemetry::{debug, error, tracing};
68use common_time::timestamp::TimeUnit;
69use datafusion::dataframe::DataFrame;
70use datafusion::physical_plan::ExecutionPlan;
71use datafusion_expr::LogicalPlan;
72use futures::TryStreamExt;
73use futures::{Stream, StreamExt, future};
74use operator::delete::DeleterRef;
75use operator::insert::InserterRef;
76use operator::statement::{StatementExecutor, StatementExecutorRef};
77use partition::manager::PartitionRuleManagerRef;
78use pipeline::pipeline_operator::PipelineOperator;
79use prometheus::HistogramTimer;
80// The absolute path names the `promql` crate, not this module's `promql` submodule.
81use promql_parser::label::{METRIC_NAME, MatchOp, Matcher};
82use promql_parser::util::{ExprVisitor, walk_expr};
83use query::QueryEngineRef;
84use query::metrics::OnDone;
85use query::parser::{PromQuery, QueryStatement};
86use query::query_engine::DescribeResult;
87use query::query_engine::options::{QueryOptions, validate_catalog_and_schema};
88use servers::batcher::logical_table::LogicalTablePendingRowsBatcher;
89use servers::error::{self as server_error, AuthSnafu, ExecuteQuerySnafu};
90use servers::interceptor::{
91    PromQueryInterceptor, PromQueryInterceptorRef, SqlQueryInterceptor, SqlQueryInterceptorRef,
92};
93use servers::prometheus_handler::{
94    ParsedPromQuery, PrometheusHandler, resolve_schema_from_matchers,
95};
96use servers::query_handler::sql::SqlQueryHandler;
97use servers::request_memory_limiter::ServerMemoryLimiter;
98use session::context::{Channel, MetricDiscoveryScope, QueryContextRef};
99use session::table_name::table_idents_to_full_name;
100use snafu::prelude::*;
101use sql::ast::ObjectNamePartExt;
102use sql::dialect::Dialect;
103use sql::parser::{ParseOptions, ParserContext};
104use sql::statements::comment::CommentObject;
105use sql::statements::copy::{Copy, CopyDatabase, CopyTable};
106use sql::statements::statement::Statement;
107use sql::statements::tql::Tql;
108use sql::util::{
109    extract_tables_from_prom_expr_checked, extract_tables_from_prom_expr_partial,
110    extract_tables_from_statement_checked, extract_tables_from_statement_partial,
111    extract_tql_exprs_from_statement,
112};
113use sqlparser::ast::{AnalyzeFormat, ObjectName};
114use tracing::Span;
115
116use crate::error::{
117    self, CatalogSnafu, CollectRecordbatchSnafu, Error, ExecLogicalPlanSnafu, ExecutePromqlSnafu,
118    ExternalSnafu, InvalidSqlSnafu, ParseSqlSnafu, PermissionSnafu, PlanStatementSnafu, Result,
119    SqlExecInterceptedSnafu, StatementTimeoutSnafu, TableOperationSnafu,
120};
121use crate::promql_query_cache::PromqlRollupCache;
122use crate::service_config::InfluxdbMergeMode;
123use crate::stream_wrapper::CancellableStreamWrapper;
124
125fn deduplicate_permission_targets(targets: PermissionTableTargets) -> PermissionTableTargets {
126    let PermissionTableTargets::Resolved(mut targets) = targets else {
127        return PermissionTableTargets::Unresolved;
128    };
129    if targets.len() > 1 {
130        let mut seen = HashSet::with_capacity(targets.len());
131        targets.retain(|target| seen.insert(target.clone()));
132    }
133    PermissionTableTargets::resolved(targets)
134}
135
136/// The frontend instance contains necessary components, and implements many
137/// traits, like [`servers::query_handler::grpc::GrpcQueryHandler`],
138/// [`servers::query_handler::sql::SqlQueryHandler`], etc.
139#[derive(Clone)]
140pub struct Instance {
141    server_memory_limiter: ServerMemoryLimiter,
142    frontend_peer_addr: String,
143    catalog_manager: CatalogManagerRef,
144    pipeline_operator: Arc<PipelineOperator>,
145    statement_executor: Arc<StatementExecutor>,
146    query_engine: QueryEngineRef,
147    plugins: Plugins,
148    inserter: InserterRef,
149    logical_batcher: Arc<OnceLock<Option<Arc<LogicalTablePendingRowsBatcher>>>>,
150    deleter: DeleterRef,
151    table_metadata_manager: TableMetadataManagerRef,
152    event_recorder: EventRecorderRef,
153    slow_query_recorder: EventRecorderRef,
154    process_manager: ProcessManagerRef,
155    slow_query_options: SlowQueryOptions,
156    influxdb_default_merge_mode: InfluxdbMergeMode,
157    /// Time index unit for physical metric tables created by auto table creation
158    /// through the frontend instance (e.g., batched logical-table flushes).
159    auto_create_physical_table_timestamp_unit: TimeUnit,
160    trace_ingest_chunk_size: usize,
161    trace_aux_cache: otlp::TraceAuxCache,
162    trace_aux_limiter: Option<RequestLimiter>,
163    otlp_resource_info: bool,
164    suspend: Arc<AtomicBool>,
165    /// The frontend-local rollup cache of PromQL range queries, when one is
166    /// installed.
167    ///
168    /// Disabled by default. [`crate::frontend::FrontendOptions::promql_rollup_cache`]
169    /// installs it; a request that misses fills it itself, so nothing else has to run
170    /// for it to serve.
171    promql_rollup_cache: Option<Arc<PromqlRollupCache>>,
172}
173
174impl Instance {
175    /// Returns the memory pool shared by protocol admission and table-batch conversion.
176    pub fn server_memory_limiter(&self) -> &ServerMemoryLimiter {
177        &self.server_memory_limiter
178    }
179
180    pub fn frontend_peer_addr(&self) -> &str {
181        &self.frontend_peer_addr
182    }
183
184    pub fn catalog_manager(&self) -> &CatalogManagerRef {
185        &self.catalog_manager
186    }
187
188    pub fn query_engine(&self) -> &QueryEngineRef {
189        &self.query_engine
190    }
191
192    pub fn plugins(&self) -> &Plugins {
193        &self.plugins
194    }
195
196    fn check_permission(
197        &self,
198        ctx: &QueryContextRef,
199        req: PermissionReq<'_>,
200    ) -> server_error::Result<()> {
201        self.plugins
202            .get::<PermissionCheckerRef>()
203            .as_ref()
204            .check_permission(ctx.current_user(), req)
205            .context(AuthSnafu)?;
206        Ok(())
207    }
208
209    pub fn statement_executor(&self) -> &StatementExecutorRef {
210        &self.statement_executor
211    }
212
213    pub fn table_metadata_manager(&self) -> &TableMetadataManagerRef {
214        &self.table_metadata_manager
215    }
216
217    pub fn inserter(&self) -> &InserterRef {
218        &self.inserter
219    }
220
221    pub fn process_manager(&self) -> &ProcessManagerRef {
222        &self.process_manager
223    }
224
225    /// Returns the event recorder configured for this frontend instance.
226    pub fn event_recorder(&self) -> EventRecorderRef {
227        self.event_recorder.clone()
228    }
229
230    pub fn node_manager(&self) -> &NodeManagerRef {
231        self.inserter.node_manager()
232    }
233
234    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
235        self.inserter.partition_manager()
236    }
237
238    pub fn table_flownode_set_cache(&self) -> &TableFlownodeSetCacheRef {
239        self.inserter.table_flownode_set_cache()
240    }
241
242    pub fn cache_invalidator(&self) -> &CacheInvalidatorRef {
243        self.statement_executor.cache_invalidator()
244    }
245
246    pub fn procedure_executor(&self) -> &ProcedureExecutorRef {
247        self.statement_executor.procedure_executor()
248    }
249
250    /// The rollup cache a range query may be served from, when one is installed.
251    pub fn promql_rollup_cache(&self) -> Option<&Arc<PromqlRollupCache>> {
252        self.promql_rollup_cache.as_ref()
253    }
254
255    /// Empties this frontend's local rollup cache.
256    ///
257    /// The cache is process-local. This does not affect other frontends, source
258    /// data, or in-flight queries; those either finish with their own plan or
259    /// refill the cache on their next read.
260    pub fn clear_promql_rollup_cache(&self) {
261        if let Some(cache) = self.promql_rollup_cache.as_ref() {
262            cache.clear();
263        }
264    }
265
266    pub fn suspend_state(&self) -> Arc<AtomicBool> {
267        self.suspend.clone()
268    }
269
270    pub(crate) fn is_suspended(&self) -> bool {
271        self.suspend.load(atomic::Ordering::Relaxed)
272    }
273}
274
275fn parse_stmt(sql: &str, dialect: &(dyn Dialect + Send + Sync)) -> Result<Vec<Statement>> {
276    ParserContext::create_with_dialect(sql, dialect, ParseOptions::default()).context(ParseSqlSnafu)
277}
278
279fn is_explain_analyze_verbose(stmt: &Statement) -> bool {
280    matches!(stmt, Statement::Explain(explain) if explain.analyze && explain.verbose)
281        || matches!(stmt, Statement::Tql(Tql::Analyze(analyze)) if analyze.is_verbose)
282}
283
284fn validate_analyze_stream_statement(stmt: &mut Statement) -> Result<()> {
285    let (is_verbose, format) = match stmt {
286        Statement::Explain(explain) => (explain.analyze && explain.verbose, &mut explain.format),
287        Statement::Tql(Tql::Analyze(analyze)) => (analyze.is_verbose, &mut analyze.format),
288        _ => {
289            return InvalidSqlSnafu {
290                err_msg: "only EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE statement is supported",
291            }
292            .fail();
293        }
294    };
295
296    ensure!(
297        is_verbose,
298        InvalidSqlSnafu {
299            err_msg: "statement must be EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE"
300        }
301    );
302    match format {
303        None | Some(AnalyzeFormat::JSON) => {
304            // Keep explicit FORMAT JSON accepted, but pass JSON through
305            // QueryContext.explain_format instead of the statement to avoid
306            // the planner's current `EXPLAIN VERBOSE with FORMAT` limitation.
307            *format = None;
308            Ok(())
309        }
310        Some(_) => InvalidSqlSnafu {
311            err_msg: "only FORMAT JSON is supported for EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE",
312        }
313        .fail(),
314    }
315}
316
317impl Instance {
318    fn statement_slow_query_timer(
319        &self,
320        stmt: &Statement,
321        schema_name: String,
322    ) -> Option<SlowQueryTimer> {
323        if !should_track_statement_process(stmt) || !self.slow_query_options.enable {
324            return None;
325        }
326
327        Some(SlowQueryTimer::new(
328            CatalogQueryStatement::Sql(stmt.clone()),
329            schema_name,
330            self.slow_query_options.threshold,
331            self.slow_query_options.sample_ratio,
332            self.slow_query_options.record_type,
333            self.slow_query_recorder.clone(),
334        ))
335    }
336
337    async fn query_statement(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result<Output> {
338        check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
339        let query_ctx = if matches!(&stmt, Statement::SetVariables(_)) {
340            query_ctx
341        } else {
342            Arc::new(
343                query_ctx
344                    .query_option_snapshot()
345                    .map_err(|error| {
346                        query::error::InvalidQueryContextExtensionSnafu {
347                            reason: error.to_string(),
348                        }
349                        .build()
350                    })
351                    .context(PlanStatementSnafu)?,
352            )
353        };
354
355        let query_interceptor = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
356        let query_interceptor = query_interceptor.as_ref();
357
358        if should_track_statement_process(&stmt) {
359            let catalog_name = query_ctx.current_catalog().to_string();
360            let schema_name = query_ctx.current_schema();
361            let slow_query_timer = self.statement_slow_query_timer(&stmt, schema_name.clone());
362            let timeout_recorder = is_explain_analyze_verbose(&stmt)
363                .then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder))
364                .flatten();
365
366            let ticket = self.process_manager.register_query(
367                catalog_name,
368                vec![schema_name],
369                stmt.to_string(),
370                query_ctx.conn_info().to_string(),
371                Some(query_ctx.process_id()),
372                slow_query_timer,
373            );
374
375            let query_fut = self.exec_statement_with_timeout(
376                stmt,
377                query_ctx.clone(),
378                query_interceptor,
379                timeout_recorder,
380            );
381
382            let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
383                .await
384                .map_err(|_| error::CancelledSnafu.build())?;
385            result.map(|output| {
386                let Output { meta, data } = output;
387                let data = match data {
388                    OutputData::Stream(stream) => {
389                        OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
390                    }
391                    other => other,
392                };
393                Output { data, meta }
394            })
395        } else {
396            self.exec_statement_with_timeout(stmt, query_ctx, query_interceptor, None)
397                .await
398        }
399    }
400
401    async fn exec_statement_with_timeout(
402        &self,
403        stmt: Statement,
404        query_ctx: QueryContextRef,
405        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
406        timeout_recorder: Option<SlowQueryRecorder>,
407    ) -> Result<Output> {
408        let timeout = derive_timeout(&stmt, &query_ctx);
409        match timeout {
410            Some(timeout) => {
411                let start = tokio::time::Instant::now();
412                let output = tokio::time::timeout(
413                    timeout,
414                    self.exec_statement(stmt, query_ctx, query_interceptor),
415                )
416                .await
417                .map_err(|_| StatementTimeoutSnafu.build())??;
418                let output = map_query_output(output)?;
419                // compute remaining timeout
420                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
421                attach_timeout(output, remaining_timeout, timeout_recorder)
422            }
423            None => self
424                .exec_statement(stmt, query_ctx, query_interceptor)
425                .await
426                .and_then(map_query_output),
427        }
428    }
429
430    async fn exec_statement(
431        &self,
432        stmt: Statement,
433        query_ctx: QueryContextRef,
434        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
435    ) -> Result<Output> {
436        match stmt {
437            Statement::Query(_) | Statement::Explain(_) | Statement::Delete(_) => {
438                // TODO: remove this when format is supported in datafusion
439                if let Statement::Explain(explain) = &stmt
440                    && let Some(format) = explain.format()
441                {
442                    query_ctx.set_explain_format(format.to_string());
443                }
444
445                self.plan_and_exec_sql(stmt, &query_ctx, query_interceptor)
446                    .await
447            }
448            Statement::Tql(tql) => {
449                self.plan_and_exec_tql(&query_ctx, query_interceptor, tql)
450                    .await
451            }
452            _ => {
453                query_interceptor.pre_execute(Some(&stmt), None, query_ctx.clone())?;
454                if let Statement::SetVariables(set) = &stmt
455                    && query_ctx.channel() == Channel::Postgres
456                    && let Some(schemas) = set.search_path()
457                {
458                    return self.set_search_path(schemas, query_ctx).await;
459                }
460                if let Statement::Use(schema) = &stmt {
461                    self.authorize_database(query_ctx.current_catalog(), schema, &query_ctx)
462                        .await?;
463                }
464                if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(
465                    CopyDatabase::From(arg),
466                )) = &stmt
467                    && arg.with.get("metric_data_layout").is_some()
468                {
469                    return self
470                        .copy_packed_database(arg.clone(), &stmt, query_ctx)
471                        .await;
472                }
473                if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(CopyDatabase::To(
474                    arg,
475                ))) = &stmt
476                    && export_database::parse_metric_export_requested(&arg.with)?
477                {
478                    return self.copy_metric_database(arg.clone(), query_ctx).await;
479                }
480                if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy)) = &stmt {
481                    return self.copy_database(copy.clone(), &stmt, query_ctx).await;
482                }
483                if let Statement::CreateFlow(stmt) = stmt {
484                    let (catalog, schema, table) = session::table_name::table_idents_to_full_name(
485                        &stmt.sink_table_name,
486                        &query_ctx,
487                    )
488                    .map_err(BoxedError::new)
489                    .context(crate::error::ExternalSnafu)?;
490                    let allow_sink_create = self
491                        .can_create_flow_sinks(
492                            &query_ctx,
493                            catalog,
494                            schema,
495                            table,
496                            stmt.flow_options.get("incremental"),
497                            stmt.flow_options.get("incremental_result_view"),
498                        )
499                        .await?;
500                    return self
501                        .statement_executor
502                        .create_flow_with_sink_create_permission(stmt, allow_sink_create, query_ctx)
503                        .await
504                        .context(TableOperationSnafu);
505                }
506                self.statement_executor
507                    .execute_sql(stmt, query_ctx)
508                    .await
509                    .context(TableOperationSnafu)
510            }
511        }
512    }
513
514    async fn plan_and_exec_sql(
515        &self,
516        stmt: Statement,
517        query_ctx: &QueryContextRef,
518        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
519    ) -> Result<Output> {
520        let stmt = QueryStatement::Sql(stmt);
521        let plan = self
522            .statement_executor
523            .plan(&stmt, query_ctx.clone())
524            .await?;
525        let QueryStatement::Sql(stmt) = stmt else {
526            unreachable!()
527        };
528        query_interceptor.pre_execute(Some(&stmt), Some(&plan), query_ctx.clone())?;
529
530        self.statement_executor
531            .exec_plan(plan, query_ctx.clone())
532            .await
533            .context(TableOperationSnafu)
534    }
535
536    async fn plan_and_exec_tql(
537        &self,
538        query_ctx: &QueryContextRef,
539        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
540        tql: Tql,
541    ) -> Result<Output> {
542        let plan = self
543            .statement_executor
544            .plan_tql(tql.clone(), query_ctx)
545            .await?;
546        query_interceptor.pre_execute(
547            Some(&Statement::Tql(tql)),
548            Some(&plan),
549            query_ctx.clone(),
550        )?;
551        self.statement_executor
552            .exec_plan(plan, query_ctx.clone())
553            .await
554            .context(TableOperationSnafu)
555    }
556}
557
558/// If the relevant variables are set, the timeout is enforced for all PostgreSQL statements.
559/// For MySQL, it applies only to read-only statements.
560fn derive_timeout(stmt: &Statement, query_ctx: &QueryContextRef) -> Option<Duration> {
561    let query_timeout = query_ctx.query_timeout()?;
562    if query_timeout.is_zero() {
563        return None;
564    }
565    match query_ctx.channel() {
566        Channel::Mysql if stmt.is_readonly() => Some(query_timeout),
567        Channel::Postgres => Some(query_timeout),
568        _ => None,
569    }
570}
571
572/// Derives timeout for plan execution.
573fn derive_timeout_for_plan(plan: &LogicalPlan, query_ctx: &QueryContextRef) -> Option<Duration> {
574    let query_timeout = query_ctx.query_timeout()?;
575    if query_timeout.is_zero() {
576        return None;
577    }
578    match query_ctx.channel() {
579        Channel::Mysql if is_readonly_plan(plan) => Some(query_timeout),
580        Channel::Postgres => Some(query_timeout),
581        _ => None,
582    }
583}
584
585fn record_explain_analyze_timeout(
586    recorder: Option<&SlowQueryRecorder>,
587    plan: Option<&Arc<dyn ExecutionPlan>>,
588) {
589    let Some(recorder) = recorder else {
590        return;
591    };
592    let metrics = plan
593        .and_then(|plan| query::analyze_plan_metrics_to_json_value(plan, true).ok())
594        .unwrap_or_else(|| serde_json::json!([]));
595    recorder.force_record_with_payload(serde_json::json!({
596        "timed_out": true,
597        "metrics": metrics,
598    }));
599}
600
601fn attach_timeout(
602    output: Output,
603    mut timeout: Duration,
604    timeout_recorder: Option<SlowQueryRecorder>,
605) -> Result<Output> {
606    if timeout.is_zero() {
607        return StatementTimeoutSnafu.fail();
608    }
609
610    let plan = timeout_recorder
611        .as_ref()
612        .and_then(|_| output.meta.plan.clone());
613    let output = match output.data {
614        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
615        OutputData::Stream(mut stream) => {
616            let schema = stream.schema();
617            let s = Box::pin(stream! {
618                let mut start = tokio::time::Instant::now();
619                while let Some(item) = tokio::time::timeout(timeout, stream.next()).await.map_err(|_| {
620                    record_explain_analyze_timeout(timeout_recorder.as_ref(), plan.as_ref());
621                    StreamTimeoutSnafu.build()
622                })? {
623                    yield item;
624
625                    let now = tokio::time::Instant::now();
626                    timeout = timeout.checked_sub(now - start).unwrap_or(Duration::ZERO);
627                    start = now;
628                    // tokio::time::timeout may not return an error immediately when timeout is 0.
629                    if timeout.is_zero() {
630                        record_explain_analyze_timeout(timeout_recorder.as_ref(), plan.as_ref());
631                        StreamTimeoutSnafu.fail()?;
632                    }
633                }
634            }) as Pin<Box<dyn Stream<Item = _> + Send>>;
635            let stream = RecordBatchStreamWrapper {
636                schema,
637                stream: s,
638                output_ordering: None,
639                metrics: Default::default(),
640                span: Span::current(),
641            };
642            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
643        }
644    };
645
646    Ok(output)
647}
648
649impl Instance {
650    async fn copy_database(
651        &self,
652        copy: CopyDatabase,
653        stmt: &Statement,
654        ctx: QueryContextRef,
655    ) -> Result<Output> {
656        self.plugins
657            .get::<PermissionCheckerRef>()
658            .as_ref()
659            .check_permission_with_context(
660                ctx.current_user(),
661                PermissionReq::SqlStatement(stmt),
662                Some(&ctx.current_schema()),
663            )
664            .context(PermissionSnafu)?;
665        match copy {
666            CopyDatabase::To(arg) => {
667                let req = operator::statement::to_copy_database_request(arg, &ctx)?;
668                let tables = self
669                    .statement_executor
670                    .capture_database_export_tables(&req, None, &ctx)
671                    .await?;
672                let targets = PermissionTableTargets::resolved(
673                    tables
674                        .iter()
675                        .map(|table| {
676                            let info = table.table_info();
677                            PermissionTableTarget::new(
678                                &info.catalog_name,
679                                &info.schema_name,
680                                &info.name,
681                            )
682                        })
683                        .collect(),
684                );
685                self.check_table_permission(
686                    &ctx,
687                    PermissionReq::SqlStatement(stmt),
688                    targets.clone(),
689                )
690                .context(PermissionSnafu)?;
691                self.check_table_permission(&ctx, PermissionReq::Action(COPY_TO), targets)
692                    .context(PermissionSnafu)?;
693                self.statement_executor
694                    .copy_database_to_tables(req, tables, ctx)
695                    .await
696                    .context(TableOperationSnafu)
697            }
698            CopyDatabase::From(arg) => {
699                let req = operator::statement::to_copy_database_request(arg, &ctx)?;
700                let requests = self
701                    .statement_executor
702                    .prepare_database_import(&req)
703                    .await?;
704                let targets = PermissionTableTargets::resolved(
705                    requests
706                        .iter()
707                        .map(|request| {
708                            PermissionTableTarget::new(
709                                &request.catalog_name,
710                                &request.schema_name,
711                                &request.table_name,
712                            )
713                        })
714                        .collect(),
715                );
716                self.check_resolved_table_permission(
717                    &ctx,
718                    PermissionReq::SqlStatement(stmt),
719                    targets,
720                )
721                .await?;
722                self.statement_executor
723                    .copy_database_from_requests(req, requests, ctx)
724                    .await
725                    .context(TableOperationSnafu)
726            }
727        }
728    }
729
730    /// Authorizes `stmt` and returns the context to plan it with: the one given, carrying the
731    /// metric discovery scope this authorization resolved when the statement evaluates TQL.
732    async fn check_sql_permission(
733        &self,
734        stmt: &Statement,
735        query_ctx: &QueryContextRef,
736    ) -> Result<QueryContextRef> {
737        self.check_unselected_mysql_database(stmt, query_ctx)
738            .await?;
739        self.plugins
740            .get::<PermissionCheckerRef>()
741            .as_ref()
742            .check_permission_with_context(
743                query_ctx.current_user(),
744                PermissionReq::SqlStatement(stmt),
745                Some(&query_ctx.current_schema()),
746            )
747            .context(PermissionSnafu)?;
748
749        // Database COPY needs the full table set before table-target authorization.
750        if matches!(stmt, Statement::Copy(Copy::CopyDatabase(_))) {
751            return Ok(query_ctx.clone());
752        }
753
754        let full_names = |names: Vec<ObjectName>, query_ctx: &QueryContextRef| {
755            names
756                .into_iter()
757                .map(|name| {
758                    table_idents_to_full_name(&name, query_ctx).map(|(catalog, schema, table)| {
759                        PermissionTableTarget::new(catalog, schema, table)
760                    })
761                })
762                .collect::<std::result::Result<Vec<_>, _>>()
763                .map_err(BoxedError::new)
764                .context(ExternalSnafu)
765        };
766        let mut targets = match extract_tables_from_statement_checked(stmt) {
767            Some(tables) => {
768                PermissionTableTargets::resolved(full_names(tables.collect(), query_ctx)?)
769            }
770            None => PermissionTableTargets::Unresolved,
771        };
772        let req = PermissionReq::SqlStatement(stmt);
773        let mut query_ctx = query_ctx.clone();
774        // TQL discovers metrics the way the Prometheus handler does, bounded by the tables this
775        // statement's own permission request may read.
776        if let Some(exprs) = extract_tql_exprs_from_statement(stmt)
777            && !exprs.is_empty()
778        {
779            self.prepare_metric_discovery_scope_with(&exprs, req.clone(), &mut query_ctx)
780                .await?;
781            if matches!(targets, PermissionTableTargets::Unresolved)
782                && let Some(discovered) =
783                    MetricDiscoveryVisitor::walk(&exprs, query_ctx.current_schema())
784                        .discovery_targets(query_ctx.metric_discovery_scope())
785            {
786                let mut resolved =
787                    full_names(extract_tables_from_statement_partial(stmt), &query_ctx)?;
788                resolved.extend(discovered);
789                targets = PermissionTableTargets::resolved(resolved);
790            }
791        }
792        if matches!(
793            stmt,
794            Statement::Copy(Copy::CopyTable(CopyTable::To(_)) | Copy::CopyQueryTo(_))
795        ) {
796            // COPY retains its write permission requirement and also reads source data.
797            self.check_resolved_table_permissions(
798                &query_ctx,
799                [PermissionReq::Action(COPY_TO), req],
800                targets,
801            )
802            .await?;
803        } else {
804            self.check_resolved_table_permission(&query_ctx, req, targets)
805                .await?;
806        }
807        Ok(query_ctx)
808    }
809
810    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_analyze_stream_query")]
811    async fn do_analyze_stream_query_inner(
812        &self,
813        query: &str,
814        query_ctx: QueryContextRef,
815    ) -> Result<Output> {
816        ensure!(!self.is_suspended(), error::SuspendedSnafu);
817
818        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
819        let query_interceptor = query_interceptor_opt.as_ref();
820        let query = query_interceptor.pre_parsing(query, query_ctx.clone())?;
821        let mut stmts = parse_stmt(query.as_ref(), query_ctx.sql_dialect())
822            .and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))?;
823
824        ensure!(
825            stmts.len() == 1,
826            InvalidSqlSnafu {
827                err_msg: "only a single EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE statement is supported"
828            }
829        );
830        let mut stmt = stmts.remove(0);
831        validate_analyze_stream_statement(&mut stmt)?;
832        query_ctx.set_explain_format(AnalyzeFormat::JSON.to_string());
833
834        let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?;
835        check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
836        let catalog_name = query_ctx.current_catalog().to_string();
837        let schema_name = query_ctx.current_schema();
838        let slow_query_timer = self.statement_slow_query_timer(&stmt, schema_name.clone());
839        let ticket = self.process_manager.register_query(
840            catalog_name,
841            vec![schema_name],
842            stmt.to_string(),
843            query_ctx.conn_info().to_string(),
844            Some(query_ctx.process_id()),
845            slow_query_timer,
846        );
847        let query_fut =
848            self.exec_statement_with_timeout(stmt, query_ctx.clone(), query_interceptor, None);
849        let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
850            .await
851            .map_err(|_| error::CancelledSnafu.build())??;
852        let Output { meta, data } = output;
853        let data = match data {
854            OutputData::Stream(stream) => OutputData::Stream(Box::pin(
855                CancellableStreamWrapper::new_cancel_on_drop(stream, ticket),
856            )),
857            other => other,
858        };
859        query_interceptor.post_execute(Output { data, meta }, query_ctx)
860    }
861
862    async fn batch_create_logical_tables(
863        &self,
864        query: &str,
865        query_ctx: QueryContextRef,
866    ) -> Result<Vec<Output>> {
867        use servers::query_handler::sql::{
868            MAX_LOGICAL_TABLE_DDL_BYTES, MAX_LOGICAL_TABLE_DDL_STATEMENTS,
869        };
870        ensure!(!self.is_suspended(), error::SuspendedSnafu);
871        ensure!(
872            query.len() <= MAX_LOGICAL_TABLE_DDL_BYTES,
873            InvalidSqlSnafu {
874                err_msg: "logical-table DDL exceeds 1 MiB"
875            }
876        );
877        let interceptor = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
878        let interceptor = interceptor.as_ref();
879        let query = interceptor.pre_parsing(query, query_ctx.clone())?;
880        ensure!(
881            query.len() <= MAX_LOGICAL_TABLE_DDL_BYTES,
882            InvalidSqlSnafu {
883                err_msg: "logical-table DDL exceeds 1 MiB"
884            }
885        );
886        let statements = parse_stmt(query.as_ref(), query_ctx.sql_dialect()).map_err(|_| {
887            InvalidSqlSnafu {
888                err_msg: "invalid logical-table DDL",
889            }
890            .build()
891        })?;
892        ensure!(
893            !statements.is_empty() && statements.len() <= MAX_LOGICAL_TABLE_DDL_STATEMENTS,
894            InvalidSqlSnafu {
895                err_msg: "logical-table batch requires 1 to 128 statements"
896            }
897        );
898        let original_statements = interceptor.map(|_| statements.clone());
899        let statements = interceptor.post_parsing(statements, query_ctx.clone())?;
900        ensure!(
901            !statements.is_empty() && statements.len() <= MAX_LOGICAL_TABLE_DDL_STATEMENTS,
902            InvalidSqlSnafu {
903                err_msg: "logical-table batch requires 1 to 128 statements"
904            }
905        );
906        let measure_rewritten_sql = || {
907            let mut remaining = MAX_LOGICAL_TABLE_DDL_BYTES - (statements.len() - 1);
908            statements.iter().all(|statement| {
909                matches!(statement, Statement::CreateTable(create) if create.consume_sql_size_budget(&mut remaining))
910            })
911        };
912        ensure!(
913            original_statements
914                .as_ref()
915                .is_none_or(|original| original == &statements)
916                || measure_rewritten_sql(),
917            InvalidSqlSnafu {
918                err_msg: "invalid or oversized rewritten logical-table DDL"
919            }
920        );
921        for statement in &statements {
922            ensure!(
923                matches!(statement, Statement::CreateTable(_)),
924                InvalidSqlSnafu {
925                    err_msg: "batch requires explicit Metric logical CREATE TABLE statements"
926                }
927            );
928            interceptor.pre_execute(Some(statement), None, query_ctx.clone())?;
929        }
930        for statement in &statements {
931            self.check_sql_permission(statement, &query_ctx).await?;
932            check_permission(self.plugins.clone(), statement, &query_ctx)?;
933        }
934        let count = statements.len();
935        let creates = statements
936            .into_iter()
937            .filter_map(|statement| {
938                if let Statement::CreateTable(create) = statement {
939                    Some(create)
940                } else {
941                    None
942                }
943            })
944            .collect();
945        self.statement_executor
946            .batch_create_logical_tables(creates, query_ctx.clone())
947            .await
948            .context(TableOperationSnafu)?;
949        (0..count)
950            .map(|_| interceptor.post_execute(Output::new_with_affected_rows(0), query_ctx.clone()))
951            .collect()
952    }
953
954    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_query")]
955    async fn do_query_inner(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
956        if self.is_suspended() {
957            return vec![error::SuspendedSnafu {}.fail()];
958        }
959
960        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
961        let query_interceptor = query_interceptor_opt.as_ref();
962        let query = match query_interceptor.pre_parsing(query, query_ctx.clone()) {
963            Ok(q) => q,
964            Err(e) => return vec![Err(e)],
965        };
966
967        match parse_stmt(query.as_ref(), query_ctx.sql_dialect())
968            .and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))
969        {
970            Ok(stmts) => {
971                if stmts.is_empty() {
972                    return vec![
973                        InvalidSqlSnafu {
974                            err_msg: "empty statements",
975                        }
976                        .fail(),
977                    ];
978                }
979
980                let mut results = Vec::with_capacity(stmts.len());
981                for stmt in stmts {
982                    let stmt_ctx = match self.check_sql_permission(&stmt, &query_ctx).await {
983                        Ok(stmt_ctx) => stmt_ctx,
984                        Err(e) => {
985                            results.push(Err(e));
986                            break;
987                        }
988                    };
989
990                    match self.query_statement(stmt.clone(), stmt_ctx).await {
991                        Ok(output) => {
992                            let output_result =
993                                query_interceptor.post_execute(output, query_ctx.clone());
994                            results.push(output_result);
995                        }
996                        Err(e) => {
997                            if e.status_code().should_log_error() {
998                                error!(e; user = query_ctx.current_user().username(), protocol = %query_ctx.channel(),
999                                    catalog = query_ctx.current_catalog(), schema = %query_ctx.current_schema(),
1000                                    process_id = query_ctx.process_id(), "Failed to execute query: {stmt}");
1001                            } else {
1002                                debug!("Failed to execute query: {stmt}, {e}");
1003                            }
1004                            results.push(Err(e));
1005                            break;
1006                        }
1007                    }
1008                }
1009                results
1010            }
1011            Err(e) => {
1012                vec![Err(e)]
1013            }
1014        }
1015    }
1016
1017    async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
1018        self.query_engine
1019            .execute(plan, query_ctx)
1020            .await
1021            .context(ExecLogicalPlanSnafu)
1022    }
1023
1024    async fn exec_plan_with_timeout(
1025        &self,
1026        plan: LogicalPlan,
1027        query_ctx: QueryContextRef,
1028        timeout_recorder: Option<SlowQueryRecorder>,
1029    ) -> Result<Output> {
1030        let timeout = derive_timeout_for_plan(&plan, &query_ctx);
1031        match timeout {
1032            Some(timeout) => {
1033                let start = tokio::time::Instant::now();
1034                let output = tokio::time::timeout(timeout, self.exec_plan(plan, query_ctx))
1035                    .await
1036                    .map_err(|_| StatementTimeoutSnafu.build())??;
1037                let output = map_query_output(output)?;
1038                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
1039                attach_timeout(output, remaining_timeout, timeout_recorder)
1040            }
1041            None => self
1042                .exec_plan(plan, query_ctx)
1043                .await
1044                .and_then(map_query_output),
1045        }
1046    }
1047
1048    async fn do_exec_plan_inner(
1049        &self,
1050        plan: LogicalPlan,
1051        stmt: Option<Statement>,
1052        query_ctx: QueryContextRef,
1053    ) -> Result<Output> {
1054        ensure!(!self.is_suspended(), error::SuspendedSnafu);
1055        if let Some(stmt) = &stmt {
1056            self.check_unselected_mysql_database(stmt, &query_ctx)
1057                .await?;
1058        } else if query_ctx.channel() == Channel::Mysql && query_ctx.current_schema().is_empty() {
1059            return Err(BoxedError::new(
1060                session::SessionError::NoDatabaseSelected {},
1061            ))
1062            .context(ExternalSnafu);
1063        }
1064
1065        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
1066        let query_interceptor = query_interceptor_opt.as_ref();
1067
1068        query_interceptor.pre_execute(stmt.as_ref(), Some(&plan), query_ctx.clone())?;
1069
1070        // TQL EXPLAIN/ANALYZE formats are consumed from the query context at
1071        // execution time (see `optimize_physical_plan`); re-apply the side
1072        // effect of `plan_tql` that was lost when the plan was built during
1073        // Describe. `explain_format` is per-query state, so this never
1074        // overwrites anything.
1075        if let Some(Statement::Tql(tql)) = &stmt {
1076            let format = match tql {
1077                Tql::Explain(explain) => explain.format.as_ref(),
1078                Tql::Analyze(analyze) => analyze.format.as_ref(),
1079                Tql::Eval(_) => None,
1080            };
1081            if let Some(format) = format {
1082                query_ctx.set_explain_format(format.to_string());
1083            }
1084        }
1085
1086        let query = stmt
1087            .as_ref()
1088            .map(|s| s.to_string())
1089            .unwrap_or_else(|| plan.display_indent().to_string());
1090
1091        let result = if should_track_plan_process(stmt.as_ref(), &plan) {
1092            let catalog_name = query_ctx.current_catalog().to_string();
1093            let schema_name = query_ctx.current_schema();
1094            let slow_query_timer = self.slow_query_options.enable.then(|| {
1095                SlowQueryTimer::new(
1096                    CatalogQueryStatement::Plan(query.clone()),
1097                    schema_name.clone(),
1098                    self.slow_query_options.threshold,
1099                    self.slow_query_options.sample_ratio,
1100                    self.slow_query_options.record_type,
1101                    self.slow_query_recorder.clone(),
1102                )
1103            });
1104
1105            let timeout_recorder = stmt
1106                .as_ref()
1107                .is_some_and(is_explain_analyze_verbose)
1108                .then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder))
1109                .flatten();
1110            let ticket = self.process_manager.register_query(
1111                catalog_name,
1112                vec![schema_name],
1113                query,
1114                query_ctx.conn_info().to_string(),
1115                Some(query_ctx.process_id()),
1116                slow_query_timer,
1117            );
1118
1119            let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder);
1120
1121            let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
1122                .await
1123                .map_err(|_| error::CancelledSnafu.build())?;
1124            result.map(|output| {
1125                let Output { meta, data } = output;
1126                let data = match data {
1127                    OutputData::Stream(stream) => {
1128                        OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
1129                    }
1130                    other => other,
1131                };
1132                Output { data, meta }
1133            })
1134        } else {
1135            self.exec_plan_with_timeout(plan, query_ctx.clone(), None)
1136                .await
1137        };
1138
1139        result.and_then(|output| query_interceptor.post_execute(output, query_ctx))
1140    }
1141
1142    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_promql_query")]
1143    async fn do_promql_query_inner(
1144        &self,
1145        query: &PromQuery,
1146        query_ctx: QueryContextRef,
1147    ) -> Vec<Result<Output>> {
1148        if self.is_suspended() {
1149            return vec![error::SuspendedSnafu {}.fail()];
1150        }
1151
1152        // check will be done in prometheus handler's do_query
1153        let result = PrometheusHandler::do_query(self, query, query_ctx)
1154            .await
1155            .with_context(|_| ExecutePromqlSnafu {
1156                query: format!("{query:?}"),
1157            });
1158        vec![result]
1159    }
1160
1161    /// Builds the [`DataFrame`] for an information-schema-backed `SHOW`
1162    /// statement; `None` for other statements. The future is boxed to keep
1163    /// `do_describe_inner`'s state machine small.
1164    fn show_statement_dataframe<'a>(
1165        &'a self,
1166        stmt: &'a Statement,
1167        query_ctx: &'a QueryContextRef,
1168    ) -> Pin<Box<dyn Future<Output = Option<query::error::Result<DataFrame>>> + Send + 'a>> {
1169        Box::pin(async move {
1170            let engine = &self.query_engine;
1171            let catalog_manager = self.catalog_manager();
1172            let ctx = query_ctx.clone();
1173            let dataframe = match stmt {
1174                Statement::ShowDatabases(show) => {
1175                    query::sql::show_databases_dataframe(show, engine, catalog_manager, ctx).await
1176                }
1177                Statement::ShowTables(show) => {
1178                    query::sql::show_tables_dataframe(show, engine, catalog_manager, ctx).await
1179                }
1180                Statement::ShowViews(show) => {
1181                    query::sql::show_views_dataframe(show, engine, catalog_manager, ctx).await
1182                }
1183                Statement::ShowFlows(show) => {
1184                    query::sql::show_flows_dataframe(show, engine, catalog_manager, ctx).await
1185                }
1186                Statement::ShowColumns(show) => {
1187                    query::sql::show_columns_dataframe(show, engine, catalog_manager, ctx).await
1188                }
1189                Statement::ShowTableStatus(show) => {
1190                    query::sql::show_table_status_dataframe(show, engine, catalog_manager, ctx)
1191                        .await
1192                }
1193                Statement::ShowCharset(kind) => {
1194                    query::sql::show_charsets_dataframe(kind, engine, catalog_manager, ctx).await
1195                }
1196                Statement::ShowCollation(kind) => {
1197                    query::sql::show_collations_dataframe(kind, engine, catalog_manager, ctx).await
1198                }
1199                Statement::ShowIndex(show) => {
1200                    query::sql::show_index_dataframe(show, engine, catalog_manager, ctx).await
1201                }
1202                Statement::ShowRegion(show) => {
1203                    query::sql::show_region_dataframe(show, engine, catalog_manager, ctx).await
1204                }
1205                Statement::ShowProcesslist(show) => {
1206                    query::sql::show_processlist_dataframe(show, engine, catalog_manager, ctx).await
1207                }
1208                _ => return None,
1209            };
1210            Some(dataframe)
1211        })
1212    }
1213
1214    async fn do_describe_inner(
1215        &self,
1216        stmt: Statement,
1217        query_ctx: QueryContextRef,
1218    ) -> Result<Option<DescribeResult>> {
1219        ensure!(!self.is_suspended(), error::SuspendedSnafu);
1220        self.check_unselected_mysql_database(&stmt, &query_ctx)
1221            .await?;
1222
1223        // EXPLAIN / EXPLAIN ANALYZE wrap an inner statement; describe them when the
1224        // wrapped statement is something we already plan (so that bind parameters
1225        // in the inner query get their types inferred). See #8029.
1226        let is_inner_plannable = |s: &Statement| {
1227            matches!(
1228                s,
1229                Statement::Insert(_) | Statement::Query(_) | Statement::Delete(_)
1230            )
1231        };
1232        let plannable = is_inner_plannable(&stmt)
1233            || matches!(&stmt, Statement::Explain(explain) if is_inner_plannable(explain.statement.as_ref()));
1234
1235        if let Statement::Tql(tql) = stmt {
1236            // TQL produces a logical plan; describe it from the plan so the
1237            // extended-protocol RowDescription matches the executed DataRows.
1238            let query_ctx = self
1239                .check_sql_permission(&Statement::Tql(tql.clone()), &query_ctx)
1240                .await?;
1241            let plan = self.statement_executor.plan_tql(tql, &query_ctx).await?;
1242            return self
1243                .query_engine
1244                .describe(plan, query_ctx)
1245                .await
1246                .map(Some)
1247                .context(error::DescribeStatementSnafu);
1248        }
1249
1250        // Describe SHOW statements from the same projection the executor builds.
1251        if let Some(dataframe) = self
1252            .show_statement_dataframe(&stmt, &query_ctx)
1253            .await
1254            .transpose()
1255            .context(PlanStatementSnafu)?
1256        {
1257            self.check_sql_permission(&stmt, &query_ctx).await?;
1258            let plan = dataframe.into_unoptimized_plan();
1259            return self
1260                .query_engine
1261                .describe(plan, query_ctx)
1262                .await
1263                .map(Some)
1264                .context(error::DescribeStatementSnafu);
1265        }
1266
1267        if plannable {
1268            let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?;
1269
1270            let plan = self
1271                .query_engine
1272                .planner()
1273                .plan(&QueryStatement::Sql(stmt), query_ctx.clone())
1274                .await
1275                .context(PlanStatementSnafu)?;
1276            self.query_engine
1277                .describe(plan, query_ctx)
1278                .await
1279                .map(Some)
1280                .context(error::DescribeStatementSnafu)
1281        } else {
1282            Ok(None)
1283        }
1284    }
1285
1286    async fn is_valid_schema_inner(&self, catalog: &str, schema: &str) -> Result<bool> {
1287        self.catalog_manager
1288            .schema_exists(catalog, schema, None)
1289            .await
1290            .context(error::CatalogSnafu)
1291    }
1292}
1293
1294#[async_trait]
1295impl SqlQueryHandler for Instance {
1296    fn supports_metric_batch_ddl(&self) -> bool {
1297        true
1298    }
1299
1300    async fn create_logical_tables(
1301        &self,
1302        query: &str,
1303        query_ctx: QueryContextRef,
1304    ) -> server_error::Result<Vec<Output>> {
1305        self.batch_create_logical_tables(query, query_ctx)
1306            .await
1307            .map_err(BoxedError::new)
1308            .context(ExecuteQuerySnafu)
1309    }
1310
1311    async fn do_query(
1312        &self,
1313        query: &str,
1314        query_ctx: QueryContextRef,
1315    ) -> Vec<server_error::Result<Output>> {
1316        self.do_query_inner(query, query_ctx)
1317            .await
1318            .into_iter()
1319            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
1320            .collect()
1321    }
1322
1323    async fn do_analyze_stream_query(
1324        &self,
1325        query: &str,
1326        query_ctx: QueryContextRef,
1327    ) -> server_error::Result<Output> {
1328        self.do_analyze_stream_query_inner(query, query_ctx)
1329            .await
1330            .map_err(BoxedError::new)
1331            .context(ExecuteQuerySnafu)
1332    }
1333
1334    async fn do_exec_plan(
1335        &self,
1336        plan: LogicalPlan,
1337        stmt: Option<Statement>,
1338        query_ctx: QueryContextRef,
1339    ) -> server_error::Result<Output> {
1340        // Prepared statements reach here with a plan built before their current execution.
1341        let plan = query::plan::refresh_partition_columns(plan, &self.catalog_manager, &query_ctx)
1342            .await
1343            .map_err(BoxedError::new)
1344            .context(server_error::ExecutePlanSnafu)?;
1345        self.do_exec_plan_inner(plan, stmt, query_ctx)
1346            .await
1347            .map_err(BoxedError::new)
1348            .context(server_error::ExecutePlanSnafu)
1349    }
1350
1351    async fn do_promql_query(
1352        &self,
1353        query: &PromQuery,
1354        query_ctx: QueryContextRef,
1355    ) -> Vec<server_error::Result<Output>> {
1356        self.do_promql_query_inner(query, query_ctx)
1357            .await
1358            .into_iter()
1359            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
1360            .collect()
1361    }
1362
1363    async fn do_describe(
1364        &self,
1365        stmt: Statement,
1366        query_ctx: QueryContextRef,
1367    ) -> server_error::Result<Option<DescribeResult>> {
1368        self.do_describe_inner(stmt, query_ctx)
1369            .await
1370            .map_err(BoxedError::new)
1371            .context(server_error::DescribeStatementSnafu)
1372    }
1373
1374    async fn is_valid_schema(&self, catalog: &str, schema: &str) -> server_error::Result<bool> {
1375        self.is_valid_schema_inner(catalog, schema)
1376            .await
1377            .map_err(BoxedError::new)
1378            .context(server_error::CheckDatabaseValiditySnafu)
1379    }
1380}
1381
1382/// Expands scan-time dictionaries only when a query result leaves the frontend.
1383pub(crate) fn map_query_output(output: Output) -> Result<Output> {
1384    output
1385        .map_dictionary_to_values()
1386        .context(CollectRecordbatchSnafu)
1387}
1388
1389/// Attaches a timer to the output and observes it once the output is exhausted.
1390pub fn attach_timer(output: Output, timer: HistogramTimer) -> Output {
1391    match output.data {
1392        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
1393        OutputData::Stream(stream) => {
1394            let stream = OnDone::new(stream, move || {
1395                timer.observe_duration();
1396            });
1397            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
1398        }
1399    }
1400}
1401
1402impl Instance {
1403    fn check_prom_query_privilege(&self, query_ctx: &QueryContextRef) -> server_error::Result<()> {
1404        self.plugins
1405            .get::<PermissionCheckerRef>()
1406            .as_ref()
1407            .check_permission(
1408                query_ctx.current_user(),
1409                PermissionReq::Action(PROMQL_QUERY),
1410            )
1411            .context(AuthSnafu)?;
1412        Ok(())
1413    }
1414
1415    fn prom_expr_permission_targets(
1416        &self,
1417        expr: &promql_parser::parser::Expr,
1418        query_ctx: &QueryContextRef,
1419    ) -> server_error::Result<Option<Vec<PermissionTableTarget>>> {
1420        extract_tables_from_prom_expr_checked(expr)
1421            .map(|tables| {
1422                tables
1423                    .map(|name| {
1424                        table_idents_to_full_name(&name, query_ctx).map(
1425                            |(catalog, schema, table)| {
1426                                PermissionTableTarget::new(catalog, schema, table)
1427                            },
1428                        )
1429                    })
1430                    .collect::<std::result::Result<Vec<_>, _>>()
1431                    .map_err(BoxedError::new)
1432                    .context(ExecuteQuerySnafu)
1433            })
1434            .transpose()
1435    }
1436
1437    async fn is_physical_query_permission_target(
1438        &self,
1439        target: &PermissionTableTarget,
1440        query_ctx: &QueryContextRef,
1441    ) -> Result<bool> {
1442        self.catalog_manager
1443            .table(
1444                &target.catalog,
1445                &target.schema,
1446                &target.table,
1447                Some(query_ctx),
1448            )
1449            .await
1450            .map(|table| table.is_some_and(|table| table.table_info().is_physical_table()))
1451            .context(CatalogSnafu)
1452    }
1453
1454    pub(crate) async fn check_resolved_table_permission(
1455        &self,
1456        ctx: &QueryContextRef,
1457        req: PermissionReq<'_>,
1458        targets: PermissionTableTargets,
1459    ) -> Result<()> {
1460        self.check_resolved_table_permissions(ctx, [req], targets)
1461            .await
1462    }
1463
1464    pub(crate) async fn can_create_flow_sink(
1465        &self,
1466        ctx: &QueryContextRef,
1467        catalog: String,
1468        schema: String,
1469        table: String,
1470    ) -> Result<bool> {
1471        let req = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
1472            expr: Some(api::v1::ddl_request::Expr::CreateTable(
1473                api::v1::CreateTableExpr {
1474                    catalog_name: catalog.clone(),
1475                    schema_name: schema.clone(),
1476                    table_name: table.clone(),
1477                    ..Default::default()
1478                },
1479            )),
1480        });
1481        let targets = PermissionTableTargets::Resolved(vec![PermissionTableTarget {
1482            catalog,
1483            schema,
1484            table,
1485            is_physical_metric_table: false,
1486        }]);
1487        match self
1488            .check_resolved_table_permission(ctx, PermissionReq::GrpcRequest(&req), targets)
1489            .await
1490        {
1491            Ok(()) => Ok(true),
1492            Err(Error::Permission { source, .. })
1493                if source.status_code()
1494                    == common_error::status_code::StatusCode::PermissionDenied =>
1495            {
1496                Ok(false)
1497            }
1498            Err(err) => Err(err),
1499        }
1500    }
1501
1502    pub(crate) async fn can_create_flow_sinks(
1503        &self,
1504        ctx: &QueryContextRef,
1505        catalog: String,
1506        schema: String,
1507        sink_table: String,
1508        incremental_flag: Option<&str>,
1509        incremental_result_view: Option<&str>,
1510    ) -> Result<bool> {
1511        if !self
1512            .can_create_flow_sink(ctx, catalog.clone(), schema.clone(), sink_table.clone())
1513            .await?
1514        {
1515            return Ok(false);
1516        }
1517        let is_incremental =
1518            incremental_flag.is_some_and(|value| value.trim().eq_ignore_ascii_case("true"));
1519        if !is_incremental {
1520            return Ok(true);
1521        }
1522        let result_view = incremental_result_view
1523            .map(str::trim)
1524            .filter(|value| !value.is_empty())
1525            .map(ToString::to_string)
1526            .unwrap_or_else(|| format!("{sink_table}_result"));
1527        self.can_create_flow_sink(ctx, catalog, schema, result_view)
1528            .await
1529    }
1530
1531    async fn check_resolved_table_permissions<const N: usize>(
1532        &self,
1533        ctx: &QueryContextRef,
1534        requests: [PermissionReq<'_>; N],
1535        targets: PermissionTableTargets,
1536    ) -> Result<()> {
1537        let checker = self.plugins.get::<PermissionCheckerRef>();
1538        if checker.is_none() {
1539            return Ok(());
1540        }
1541        let checker = checker.as_ref();
1542        let mut targets = if checker.uses_table_targets() {
1543            deduplicate_permission_targets(targets)
1544        } else {
1545            targets
1546        };
1547
1548        let user = ctx.current_user();
1549        let current_schema = ctx.current_schema();
1550        let check = |req, targets| {
1551            checker
1552                .check_permission_with_table_targets(
1553                    user.clone(),
1554                    req,
1555                    targets,
1556                    Some(current_schema.as_str()),
1557                )
1558                .map(|_| ())
1559                .context(PermissionSnafu)
1560        };
1561        let mut looked_up = HashSet::new();
1562        for (i, req) in requests.into_iter().enumerate() {
1563            match checker
1564                .precheck_table_targets(
1565                    user.clone(),
1566                    req.clone(),
1567                    &targets,
1568                    Some(current_schema.as_str()),
1569                )
1570                .context(PermissionSnafu)?
1571            {
1572                TableTargetPrecheck::Allow => continue,
1573                TableTargetPrecheck::Reject => {
1574                    unreachable!("Option<&PermissionCheckerRef> maps Reject to PermissionDenied")
1575                }
1576                TableTargetPrecheck::NeedsPhysicalResolution(indices) => {
1577                    self.resolve_physical_permission_targets(
1578                        ctx,
1579                        &mut targets,
1580                        indices,
1581                        &mut looked_up,
1582                    )
1583                    .await?;
1584                }
1585            }
1586
1587            if i + 1 == N {
1588                return check(req, targets);
1589            }
1590            check(req, targets.clone())?;
1591        }
1592        Ok(())
1593    }
1594
1595    async fn resolve_physical_permission_targets(
1596        &self,
1597        ctx: &QueryContextRef,
1598        targets: &mut PermissionTableTargets,
1599        mut indices: Vec<usize>,
1600        looked_up: &mut HashSet<usize>,
1601    ) -> Result<()> {
1602        const CONCURRENCY: usize = 8;
1603
1604        if let PermissionTableTargets::Resolved(resolved) = targets {
1605            if let Some(index) = indices.iter().find(|&&index| index >= resolved.len()) {
1606                return auth::error::InternalStateSnafu {
1607                    msg: format!(
1608                        "permission target precheck returned out-of-bounds index {index} for {} targets",
1609                        resolved.len()
1610                    ),
1611                }
1612                .fail()
1613                .context(PermissionSnafu);
1614            }
1615            indices.retain(|index| looked_up.insert(*index));
1616            // Bound catalog load and inspect results in target order to preserve serial semantics.
1617            for chunk in indices.chunks(CONCURRENCY) {
1618                let results =
1619                    future::join_all(chunk.iter().map(|&index| {
1620                        self.is_physical_query_permission_target(&resolved[index], ctx)
1621                    }))
1622                    .await;
1623                for (&index, result) in chunk.iter().zip(results) {
1624                    if result? {
1625                        resolved[index].is_physical_metric_table = true;
1626                    }
1627                }
1628            }
1629        } else if !indices.is_empty() {
1630            return auth::error::InternalStateSnafu {
1631                msg: "permission target precheck returned indices for unresolved targets"
1632                    .to_string(),
1633            }
1634            .fail()
1635            .context(PermissionSnafu);
1636        }
1637
1638        Ok(())
1639    }
1640
1641    pub(crate) async fn check_server_table_permission(
1642        &self,
1643        ctx: &QueryContextRef,
1644        req: PermissionReq<'_>,
1645        targets: PermissionTableTargets,
1646    ) -> server_error::Result<()> {
1647        match self
1648            .check_resolved_table_permission(ctx, req, targets)
1649            .await
1650        {
1651            Ok(()) => Ok(()),
1652            Err(Error::Permission { source, .. }) => Err(source).context(AuthSnafu),
1653            Err(err) => Err(BoxedError::new(err)).context(ExecuteQuerySnafu),
1654        }
1655    }
1656
1657    fn prom_queries_permission_targets(
1658        &self,
1659        queries: &[ParsedPromQuery],
1660        query_ctx: &QueryContextRef,
1661    ) -> server_error::Result<PermissionTableTargets> {
1662        let mut targets = Vec::new();
1663        let mut resolved = true;
1664
1665        for query in queries {
1666            let QueryStatement::Promql(eval_stmt, _) = query.statement() else {
1667                unreachable!("query is parsed from promql");
1668            };
1669
1670            if let Some(query_targets) =
1671                self.prom_expr_permission_targets(&eval_stmt.expr, query_ctx)?
1672            {
1673                targets.extend(query_targets);
1674            } else {
1675                resolved = false;
1676            }
1677        }
1678
1679        Ok(if resolved {
1680            PermissionTableTargets::resolved(targets)
1681        } else {
1682            PermissionTableTargets::Unresolved
1683        })
1684    }
1685}
1686
1687/// What one PromQL expression needs in order to be answered by discovering metrics.
1688#[derive(Default)]
1689struct MetricDiscoveryVisitor {
1690    needs_discovery: bool,
1691    /// True only while every selector that names no exact table is one discovery can answer. If
1692    /// any selector is not discoverable, the check must stay unresolved rather than be replaced by
1693    /// a set that silently stops naming a table the query reads.
1694    all_unresolved_are_discoverable: bool,
1695    schemas: HashSet<String>,
1696    current_schema: String,
1697    /// Addresses of the label selectors of `info` calls, which the walk reaches after their call.
1698    /// Compared only, never read through; plain integers keep the visitor `Send` across awaits.
1699    info_label_selectors: Vec<usize>,
1700}
1701
1702impl MetricDiscoveryVisitor {
1703    fn new(current_schema: String) -> Self {
1704        Self {
1705            all_unresolved_are_discoverable: true,
1706            current_schema,
1707            ..Default::default()
1708        }
1709    }
1710
1711    fn walk(exprs: &[promql_parser::parser::Expr], current_schema: String) -> Self {
1712        let mut visitor = Self::new(current_schema);
1713        for expr in exprs {
1714            let _ = walk_expr(&mut visitor, expr);
1715        }
1716        visitor
1717    }
1718
1719    /// The tables discovery adds to the statically named ones of a query whose table extraction
1720    /// is unresolved, or `None` when something other than discovery left it unresolved.
1721    fn discovery_targets(
1722        &self,
1723        scope: &MetricDiscoveryScope,
1724    ) -> Option<Vec<PermissionTableTarget>> {
1725        if !self.needs_discovery || !self.all_unresolved_are_discoverable {
1726            return None;
1727        }
1728        match scope {
1729            MetricDiscoveryScope::Allowed(allowed) => Some(allowed.iter().cloned().collect()),
1730            // The named tables alone, because a selector that cannot be resolved statically is
1731            // what left the query unresolved: the complete extraction would answer "no tables",
1732            // dropping the named ones that the same query also reads.
1733            MetricDiscoveryScope::Unrestricted => Some(Vec::new()),
1734            MetricDiscoveryScope::Unavailable => None,
1735        }
1736    }
1737
1738    /// The planner reads the info table this selector stands for and never discovers with it, so
1739    /// it must not authorize a schema here. A shape the table extractor leaves unresolved keeps
1740    /// the whole expression unresolved.
1741    fn inspect_info_labels(&mut self, labels: &promql_parser::parser::VectorSelector) {
1742        self.info_label_selectors
1743            .push(std::ptr::from_ref(labels) as usize);
1744        let names = labels.matchers.find_matchers(METRIC_NAME);
1745        let exact_name =
1746            labels.name.is_some() || (names.len() == 1 && names[0].op == MatchOp::Equal);
1747        self.all_unresolved_are_discoverable &=
1748            exact_name || sql::util::reads_default_info_metric(labels);
1749    }
1750
1751    /// Whether this selector is answered by enumerating the schema's metric tables.
1752    ///
1753    /// The planner decides the same thing before it scans anything, and the two answers have to
1754    /// match: this walk authorizes what the planner will scan, so a selector the planner declines
1755    /// must not authorize a whole schema here. It is one function in `query`, called from both.
1756    fn is_discovery_selector(selector: &promql_parser::parser::VectorSelector) -> bool {
1757        query::promql::planner::discovers_metric_name(selector)
1758    }
1759
1760    fn inspect_selector(&mut self, selector: &promql_parser::parser::VectorSelector) {
1761        let names = selector.matchers.find_matchers(METRIC_NAME);
1762        let exact_name =
1763            selector.name.is_some() || (names.len() == 1 && names[0].op == MatchOp::Equal);
1764        let discover = Self::is_discovery_selector(selector);
1765        if !exact_name {
1766            self.all_unresolved_are_discoverable &= discover;
1767        }
1768        if !discover {
1769            return;
1770        }
1771        self.needs_discovery = true;
1772        let effective_schema = selector
1773            .matchers
1774            .matchers
1775            .iter()
1776            .rev()
1777            .find(|m| {
1778                (m.name == "__schema__" || m.name == "__database__") && m.op == MatchOp::Equal
1779            })
1780            .map(|m| m.value.clone())
1781            .unwrap_or_else(|| self.current_schema.clone());
1782        self.schemas.insert(effective_schema);
1783    }
1784}
1785
1786impl ExprVisitor for MetricDiscoveryVisitor {
1787    type Error = std::convert::Infallible;
1788
1789    fn pre_visit(
1790        &mut self,
1791        expr: &promql_parser::parser::Expr,
1792    ) -> std::result::Result<bool, Self::Error> {
1793        match expr {
1794            promql_parser::parser::Expr::Call(call) if call.func.name == "info" => {
1795                if let Some(promql_parser::parser::Expr::VectorSelector(labels)) =
1796                    call.args.args.get(1).map(|labels| labels.as_ref())
1797                {
1798                    self.inspect_info_labels(labels);
1799                }
1800            }
1801            promql_parser::parser::Expr::VectorSelector(selector)
1802                if !self
1803                    .info_label_selectors
1804                    .contains(&(std::ptr::from_ref(selector) as usize)) =>
1805            {
1806                self.inspect_selector(selector);
1807            }
1808            promql_parser::parser::Expr::MatrixSelector(selector) => {
1809                self.inspect_selector(&selector.vs);
1810            }
1811            _ => {}
1812        }
1813        Ok(true)
1814    }
1815}
1816
1817impl Instance {
1818    /// Bounds the metric tables this request may discover by the caller's grants, before anything
1819    /// reads the catalog. `Unavailable` would make the planner decline discovery entirely, so this
1820    /// always resolves to something explicit.
1821    async fn prepare_metric_discovery_scope(
1822        &self,
1823        expr: &promql_parser::parser::Expr,
1824        query_ctx: &mut QueryContextRef,
1825    ) -> server_error::Result<()> {
1826        self.prepare_metric_discovery_scope_with(
1827            std::slice::from_ref(expr),
1828            PermissionReq::Action(PROMQL_QUERY),
1829            query_ctx,
1830        )
1831        .await
1832        .or_else(|error| match error {
1833            Error::Permission { source, .. } => Err(source).context(AuthSnafu),
1834            error => Err(BoxedError::new(error)).context(ExecuteQuerySnafu),
1835        })
1836    }
1837
1838    /// [`Self::prepare_metric_discovery_scope`] for the expressions one request evaluates, keeping
1839    /// each discovered table that `req` may read.
1840    async fn prepare_metric_discovery_scope_with(
1841        &self,
1842        exprs: &[promql_parser::parser::Expr],
1843        req: PermissionReq<'_>,
1844        query_ctx: &mut QueryContextRef,
1845    ) -> Result<()> {
1846        // Discovery scope is read by the native PromQL route only, so a query that does not ask
1847        // for it pays nothing here beyond resolving the switch: the value is read through the
1848        // query engine's own resolver, which takes what the query states (a request hint, or the
1849        // session `SET` it inherits) over the engine default - the same two sources planning
1850        // reads, so the two cannot disagree. A route that is off leaves discovery unrestricted,
1851        // which is what it was before the switch existed; a route that is on is bounded below
1852        // whether or not the fallback option later keeps the plan on the existing route.
1853        let native_requested = query::promql::planner::native_promql_resolved(
1854            query_ctx,
1855            self.query_engine
1856                .engine_state()
1857                .experimental_native_promql(),
1858        )
1859        .map_err(BoxedError::new)
1860        .context(ExternalSnafu)?;
1861        if !native_requested {
1862            Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted);
1863            return Ok(());
1864        }
1865        let checker = self.plugins.get::<PermissionCheckerRef>();
1866        if !checker.as_ref().uses_table_targets() {
1867            Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted);
1868            return Ok(());
1869        }
1870        let visitor = MetricDiscoveryVisitor::walk(exprs, query_ctx.current_schema());
1871        if !visitor.needs_discovery {
1872            return Ok(());
1873        }
1874        let schemas = visitor.schemas;
1875        let mut allowed = HashSet::new();
1876        for schema in schemas {
1877            let mut tables = self
1878                .catalog_manager
1879                .tables(query_ctx.current_catalog(), &schema, Some(query_ctx))
1880                .try_collect::<Vec<_>>()
1881                .await
1882                .context(CatalogSnafu)?;
1883            tables.sort_by_key(|table| table.table_info().name.clone());
1884            for table in tables {
1885                let info = table.table_info();
1886                if info.meta.engine != store_api::metric_engine_consts::METRIC_ENGINE_NAME
1887                    || info.is_physical_table()
1888                {
1889                    continue;
1890                }
1891                if info.catalog_name != query_ctx.current_catalog() || info.schema_name != schema {
1892                    continue;
1893                }
1894                let target = PermissionTableTarget::new(
1895                    query_ctx.current_catalog(),
1896                    &schema,
1897                    info.name.as_str(),
1898                );
1899                match checker.as_ref().check_permission_with_table_targets(
1900                    query_ctx.current_user(),
1901                    req.clone(),
1902                    PermissionTableTargets::resolved(vec![target.clone()]),
1903                    Some(schema.as_str()),
1904                ) {
1905                    Ok(_) => {
1906                        allowed.insert(target);
1907                    }
1908                    // A rejected metric is skipped rather than failing the query, which is what
1909                    // makes discovery mean "every metric you can see": a table the caller cannot
1910                    // read is one the expression never mentions, the same way a query naming it
1911                    // would be rejected only where it names it. The split route instead rejects a
1912                    // query whose name matchers reach a denied table, so the same regex query
1913                    // answers with the readable metrics here and with `PermissionDenied` there.
1914                    Err(error)
1915                        if error.status_code()
1916                            == common_error::status_code::StatusCode::PermissionDenied => {}
1917                    Err(error) => return Err(error).context(PermissionSnafu),
1918                }
1919            }
1920        }
1921        Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Allowed(allowed));
1922        Ok(())
1923    }
1924
1925    /// Fails closed: a path that must have set the scope and did not is an internal error, not a
1926    /// silent return to an unfiltered discovery.
1927    fn validate_metric_discovery_scope(
1928        expr: &promql_parser::parser::Expr,
1929        scope: &MetricDiscoveryScope,
1930    ) -> server_error::Result<()> {
1931        let mut visitor = MetricDiscoveryVisitor::new(String::new());
1932        let _ = walk_expr(&mut visitor, expr);
1933        if visitor.needs_discovery && matches!(scope, MetricDiscoveryScope::Unavailable) {
1934            return Err(server_error::Error::Internal {
1935                err_msg: "Metric discovery reached without an authorization scope".to_string(),
1936            });
1937        }
1938        Ok(())
1939    }
1940
1941    /// The statically named tables of an expression, kept even when another selector cannot be
1942    /// resolved. The complete extractor would answer "no tables at all" for that expression and
1943    /// drop these, which is how a mixed query lost the tables it names explicitly.
1944    fn prom_expr_permission_targets_partial(
1945        &self,
1946        expr: &promql_parser::parser::Expr,
1947        query_ctx: &QueryContextRef,
1948    ) -> server_error::Result<Vec<PermissionTableTarget>> {
1949        extract_tables_from_prom_expr_partial(expr)
1950            .into_iter()
1951            .map(|name| {
1952                table_idents_to_full_name(&name, query_ctx).map(|(catalog, schema, table)| {
1953                    PermissionTableTarget::new(catalog, schema, table)
1954                })
1955            })
1956            .collect::<std::result::Result<Vec<_>, _>>()
1957            .map_err(BoxedError::new)
1958            .context(ExecuteQuerySnafu)
1959    }
1960}
1961
1962#[async_trait]
1963impl PrometheusHandler for Instance {
1964    async fn query_exemplars(
1965        &self,
1966        query: servers::exemplar::query::Query,
1967        ctx: QueryContextRef,
1968    ) -> server_error::Result<Vec<servers::exemplar::query::Series>> {
1969        self.query_exemplars_inner(query, ctx).await
1970    }
1971
1972    #[tracing::instrument(skip_all)]
1973    async fn do_query(
1974        &self,
1975        query: &PromQuery,
1976        query_ctx: QueryContextRef,
1977    ) -> server_error::Result<Output> {
1978        let query = ParsedPromQuery::parse(query.clone(), &query_ctx)?;
1979        self.do_query_parsed(query, query_ctx).await
1980    }
1981
1982    #[tracing::instrument(skip_all)]
1983    async fn do_query_parsed(
1984        &self,
1985        query: ParsedPromQuery,
1986        query_ctx: QueryContextRef,
1987    ) -> server_error::Result<Output> {
1988        let interceptor = self
1989            .plugins
1990            .get::<PromQueryInterceptorRef<server_error::Error>>();
1991
1992        self.check_prom_query_privilege(&query_ctx)?;
1993
1994        let parsed_expr = match query.statement() {
1995            QueryStatement::Promql(eval_stmt, _) => &eval_stmt.expr,
1996            _ => unreachable!("query is parsed from promql"),
1997        };
1998        // Authorization precedes any catalog read for discovery, so a denied name never reaches
1999        // the plan, an error message, or an output column.
2000        let mut scoped_ctx = query_ctx.clone();
2001        self.prepare_metric_discovery_scope(parsed_expr, &mut scoped_ctx)
2002            .await?;
2003        let query_ctx = scoped_ctx;
2004        Self::validate_metric_discovery_scope(parsed_expr, query_ctx.metric_discovery_scope())?;
2005        let mut targets =
2006            self.prom_queries_permission_targets(std::slice::from_ref(&query), &query_ctx)?;
2007        if matches!(targets, PermissionTableTargets::Unresolved)
2008            && let Some(discovered) = MetricDiscoveryVisitor::walk(
2009                std::slice::from_ref(parsed_expr),
2010                query_ctx.current_schema(),
2011            )
2012            .discovery_targets(query_ctx.metric_discovery_scope())
2013        {
2014            let mut resolved =
2015                self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?;
2016            resolved.extend(discovered);
2017            targets = PermissionTableTargets::resolved(resolved);
2018        }
2019        self.check_query_target_permission(targets, &query_ctx)
2020            .await?;
2021
2022        let requires_output_ordering = query.requires_output_ordering();
2023        let (query, stmt) = query.into_parts();
2024
2025        let QueryStatement::Promql(eval_stmt, alias) = &stmt else {
2026            unreachable!("query is parsed from promql");
2027        };
2028        let cached_alias = alias.clone();
2029
2030        let plan = self
2031            .statement_executor
2032            .plan(&stmt, query_ctx.clone())
2033            .await
2034            .map_err(BoxedError::new)
2035            .context(ExecuteQuerySnafu)?;
2036
2037        let plan = if requires_output_ordering {
2038            plan
2039        } else {
2040            promql::remove_output_sort(plan)
2041        };
2042
2043        interceptor.pre_execute(&query, &eval_stmt.expr, Some(&plan), query_ctx.clone())?;
2044
2045        // Take the EvalStmt from the original QueryStatement and use it to create the
2046        // CatalogQueryStatement. It is copied rather than moved, because the statement
2047        // passed the `let else` above and the range path may still read it below.
2048        let query_statement = CatalogQueryStatement::Promql(eval_stmt.clone(), alias.clone());
2049        let raw_query = query_statement.to_string();
2050
2051        let slow_query_timer = self.slow_query_options.enable.then(|| {
2052            SlowQueryTimer::new(
2053                query_statement,
2054                query_ctx.current_schema(),
2055                self.slow_query_options.threshold,
2056                self.slow_query_options.sample_ratio,
2057                self.slow_query_options.record_type,
2058                self.slow_query_recorder.clone(),
2059            )
2060        });
2061
2062        let ticket = self.process_manager.register_query(
2063            query_ctx.current_catalog().to_string(),
2064            vec![query_ctx.current_schema()],
2065            raw_query,
2066            query_ctx.conn_info().to_string(),
2067            Some(query_ctx.process_id()),
2068            slow_query_timer,
2069        );
2070
2071        // A range query over a whole evaluation grid is the one shape the rollup cache
2072        // serves. It is consulted after authorization, after `pre_execute`, and under the
2073        // same process-list ticket, so a cached answer passes exactly the checks an
2074        // executed one does; anything the cache declines keeps the original plan below.
2075        let cached = self
2076            .cached_range_output(
2077                &query,
2078                eval_stmt,
2079                cached_alias,
2080                requires_output_ordering,
2081                &plan,
2082                &query_ctx,
2083                ticket.cancellation_handle.clone(),
2084            )
2085            .await?;
2086
2087        let output = match cached {
2088            Some(rows) => Output {
2089                data: OutputData::RecordBatches(rows),
2090                // Every row was read into memory above, so the merged answer carries no
2091                // stretches of one plan to point at.
2092                meta: OutputMeta::default(),
2093            },
2094            None => {
2095                let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone());
2096
2097                let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
2098                    .await
2099                    .map_err(|_| servers::error::CancelledSnafu.build())?
2100                    .map_err(BoxedError::new)
2101                    .context(ExecuteQuerySnafu)?;
2102                map_query_output(output)
2103                    .map_err(BoxedError::new)
2104                    .context(ExecuteQuerySnafu)?
2105            }
2106        };
2107        let Output { meta, data } = output;
2108        let data = match data {
2109            OutputData::Stream(stream) => {
2110                OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
2111            }
2112            other => other,
2113        };
2114        let output = Output { data, meta };
2115        Ok(interceptor.post_execute(output, query_ctx)?)
2116    }
2117
2118    async fn check_query_permission(
2119        &self,
2120        queries: &[PromQuery],
2121        query_ctx: &QueryContextRef,
2122    ) -> server_error::Result<()> {
2123        let queries = queries
2124            .iter()
2125            .cloned()
2126            .map(|query| ParsedPromQuery::parse(query, query_ctx))
2127            .collect::<server_error::Result<Vec<_>>>()?;
2128        self.check_query_permission_parsed(&queries, query_ctx)
2129            .await
2130    }
2131
2132    async fn check_query_permission_parsed(
2133        &self,
2134        queries: &[ParsedPromQuery],
2135        query_ctx: &QueryContextRef,
2136    ) -> server_error::Result<()> {
2137        self.check_prom_query_privilege(query_ctx)?;
2138        let targets = self.prom_queries_permission_targets(queries, query_ctx)?;
2139        self.check_query_target_permission(targets, query_ctx).await
2140    }
2141
2142    async fn check_query_target_permission(
2143        &self,
2144        targets: PermissionTableTargets,
2145        query_ctx: &QueryContextRef,
2146    ) -> server_error::Result<()> {
2147        self.check_server_table_permission(query_ctx, PermissionReq::Action(PROMQL_QUERY), targets)
2148            .await
2149    }
2150
2151    async fn filter_metadata_metric_names(
2152        &self,
2153        metric_names: Vec<String>,
2154        schema: &str,
2155        query_ctx: &QueryContextRef,
2156    ) -> server_error::Result<Vec<String>> {
2157        let checker = self.plugins.get::<PermissionCheckerRef>();
2158        if !checker.as_ref().uses_table_targets() {
2159            let Some(metric) = metric_names.first() else {
2160                return Ok(metric_names);
2161            };
2162            let target =
2163                PermissionTableTarget::new(query_ctx.current_catalog(), schema, metric.as_str());
2164            let result = checker
2165                .as_ref()
2166                .check_permission_with_table_targets(
2167                    query_ctx.current_user(),
2168                    PermissionReq::Action(PROMQL_QUERY),
2169                    PermissionTableTargets::resolved(vec![target]),
2170                    Some(schema),
2171                )
2172                .context(AuthSnafu);
2173            return match result {
2174                Ok(_) => Ok(metric_names),
2175                Err(error)
2176                    if error.status_code()
2177                        == common_error::status_code::StatusCode::PermissionDenied =>
2178                {
2179                    Ok(Vec::new())
2180                }
2181                Err(error) => Err(error),
2182            };
2183        }
2184
2185        let mut allowed = Vec::with_capacity(metric_names.len());
2186        for metric in metric_names {
2187            let target =
2188                PermissionTableTarget::new(query_ctx.current_catalog(), schema, metric.as_str());
2189            match checker
2190                .as_ref()
2191                .check_permission_with_table_targets(
2192                    query_ctx.current_user(),
2193                    PermissionReq::Action(PROMQL_QUERY),
2194                    PermissionTableTargets::resolved(vec![target]),
2195                    Some(schema),
2196                )
2197                .context(AuthSnafu)
2198            {
2199                Ok(_) => allowed.push(metric),
2200                Err(error)
2201                    if error.status_code()
2202                        == common_error::status_code::StatusCode::PermissionDenied => {}
2203                Err(error) => return Err(error),
2204            }
2205        }
2206        Ok(allowed)
2207    }
2208
2209    async fn filter_metadata_schema_names(
2210        &self,
2211        schema_names: Vec<String>,
2212        query_ctx: &QueryContextRef,
2213    ) -> server_error::Result<Vec<String>> {
2214        let checker = self.plugins.get::<PermissionCheckerRef>();
2215        let mut allowed = Vec::with_capacity(schema_names.len());
2216        for schema in schema_names {
2217            match checker
2218                .as_ref()
2219                .check_permission(
2220                    query_ctx.current_user(),
2221                    PermissionReq::SchemaRead {
2222                        catalog: query_ctx.current_catalog(),
2223                        schema: &schema,
2224                    },
2225                )
2226                .context(AuthSnafu)
2227            {
2228                Ok(_) => allowed.push(schema),
2229                Err(error)
2230                    if error.status_code()
2231                        == common_error::status_code::StatusCode::PermissionDenied => {}
2232                Err(error) => return Err(error),
2233            }
2234        }
2235        Ok(allowed)
2236    }
2237
2238    async fn query_metric_names(
2239        &self,
2240        matchers: Vec<Matcher>,
2241        schema: &str,
2242        ctx: &QueryContextRef,
2243    ) -> server_error::Result<Vec<String>> {
2244        self.handle_query_metric_names(matchers, schema, ctx)
2245            .await
2246            .map_err(BoxedError::new)
2247            .context(ExecuteQuerySnafu)
2248    }
2249
2250    async fn query_metric_names_by_labels(
2251        &self,
2252        matchers: Vec<Matcher>,
2253        schema: &str,
2254        start: SystemTime,
2255        end: SystemTime,
2256        ctx: &QueryContextRef,
2257    ) -> server_error::Result<Vec<String>> {
2258        self.handle_query_metric_names_by_labels(matchers, schema, start, end, ctx)
2259            .await
2260            .map_err(BoxedError::new)
2261            .context(ExecuteQuerySnafu)
2262    }
2263
2264    async fn query_label_values(
2265        &self,
2266        metric: String,
2267        label_name: String,
2268        matchers: Vec<Matcher>,
2269        start: SystemTime,
2270        end: SystemTime,
2271        ctx: &QueryContextRef,
2272    ) -> server_error::Result<Vec<String>> {
2273        let schema =
2274            resolve_schema_from_matchers(&matchers)?.unwrap_or_else(|| ctx.current_schema());
2275        let target = PermissionTableTarget::new(ctx.current_catalog(), schema.as_str(), &metric);
2276        self.check_query_target_permission(
2277            PermissionTableTargets::resolved(vec![target.clone()]),
2278            ctx,
2279        )
2280        .await?;
2281
2282        self.handle_query_label_values(target, label_name, matchers, start, end, ctx)
2283            .await
2284            .map_err(BoxedError::new)
2285            .context(ExecuteQuerySnafu)
2286    }
2287
2288    fn catalog_manager(&self) -> CatalogManagerRef {
2289        self.catalog_manager.clone()
2290    }
2291}
2292
2293/// Validate `stmt.database` permission if it's presented.
2294macro_rules! validate_db_permission {
2295    ($stmt: expr, $query_ctx: expr) => {
2296        if let Some(database) = &$stmt.database {
2297            validate_catalog_and_schema($query_ctx.current_catalog(), database, $query_ctx)
2298                .map_err(BoxedError::new)
2299                .context(SqlExecInterceptedSnafu)?;
2300        }
2301    };
2302}
2303
2304pub fn check_permission(
2305    plugins: Plugins,
2306    stmt: &Statement,
2307    query_ctx: &QueryContextRef,
2308) -> Result<()> {
2309    let need_validate = plugins
2310        .get::<QueryOptions>()
2311        .map(|opts| opts.disallow_cross_catalog_query)
2312        .unwrap_or_default();
2313
2314    if !need_validate {
2315        return Ok(());
2316    }
2317
2318    match stmt {
2319        // Will be checked in execution.
2320        // TODO(dennis): add a hook for admin commands.
2321        Statement::Admin(_) => {}
2322        // These are executed by query engine, and will be checked there.
2323        Statement::Query(_)
2324        | Statement::Explain(_)
2325        | Statement::Tql(_)
2326        | Statement::Delete(_)
2327        | Statement::DeclareCursor(_)
2328        | Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(_)) => {}
2329        // database ops won't be checked
2330        Statement::CreateDatabase(_)
2331        | Statement::ShowDatabases(_)
2332        | Statement::DropDatabase(_)
2333        | Statement::AlterDatabase(_)
2334        | Statement::DropFlow(_)
2335        | Statement::Use(_) => {}
2336        #[cfg(feature = "enterprise")]
2337        Statement::DropTrigger(_) => {}
2338        Statement::ShowCreateDatabase(stmt) => {
2339            validate_database(&stmt.database_name, query_ctx)?;
2340        }
2341        Statement::ShowCreateTable(stmt) => {
2342            validate_param(&stmt.table_name, query_ctx)?;
2343        }
2344        Statement::ShowCreateFlow(stmt) => {
2345            validate_flow(&stmt.flow_name, query_ctx)?;
2346        }
2347        #[cfg(feature = "enterprise")]
2348        Statement::ShowCreateTrigger(stmt) => {
2349            validate_param(&stmt.trigger_name, query_ctx)?;
2350        }
2351        Statement::ShowCreateView(stmt) => {
2352            validate_param(&stmt.view_name, query_ctx)?;
2353        }
2354        Statement::CreateExternalTable(stmt) => {
2355            validate_param(&stmt.name, query_ctx)?;
2356        }
2357        Statement::CreateFlow(stmt) => {
2358            // TODO: should also validate source table name here?
2359            validate_param(&stmt.sink_table_name, query_ctx)?;
2360        }
2361        #[cfg(feature = "enterprise")]
2362        Statement::CreateTrigger(stmt) => {
2363            validate_param(&stmt.trigger_name, query_ctx)?;
2364        }
2365        Statement::CreateView(stmt) => {
2366            validate_param(&stmt.name, query_ctx)?;
2367        }
2368        Statement::AlterTable(stmt) => {
2369            validate_param(stmt.table_name(), query_ctx)?;
2370        }
2371        #[cfg(feature = "enterprise")]
2372        Statement::AlterTrigger(_) => {}
2373        // set/show variable now only alter/show variable in session
2374        Statement::SetVariables(_) | Statement::ShowVariables(_) => {}
2375        // show charset and show collation won't be checked
2376        Statement::ShowCharset(_) | Statement::ShowCollation(_) => {}
2377
2378        Statement::Comment(comment) => match &comment.object {
2379            CommentObject::Table(table) => validate_param(table, query_ctx)?,
2380            CommentObject::Column { table, .. } => validate_param(table, query_ctx)?,
2381            CommentObject::Flow(flow) => validate_flow(flow, query_ctx)?,
2382        },
2383
2384        Statement::Insert(insert) => {
2385            let name = insert.table_name().context(ParseSqlSnafu)?;
2386            validate_param(name, query_ctx)?;
2387        }
2388        Statement::CreateTable(stmt) => {
2389            validate_param(&stmt.name, query_ctx)?;
2390        }
2391        Statement::CreateTableLike(stmt) => {
2392            validate_param(&stmt.table_name, query_ctx)?;
2393            validate_param(&stmt.source_name, query_ctx)?;
2394        }
2395        Statement::DropTable(drop_stmt) => {
2396            for table_name in drop_stmt.table_names() {
2397                validate_param(table_name, query_ctx)?;
2398            }
2399        }
2400        #[cfg(feature = "enterprise")]
2401        Statement::UndropTable(stmt) => {
2402            validate_param(stmt.table_name(), query_ctx)?;
2403        }
2404        Statement::DropView(stmt) => {
2405            validate_param(&stmt.view_name, query_ctx)?;
2406        }
2407        Statement::ShowTables(stmt) => {
2408            validate_db_permission!(stmt, query_ctx);
2409        }
2410        Statement::ShowTableStatus(stmt) => {
2411            validate_db_permission!(stmt, query_ctx);
2412        }
2413        Statement::ShowColumns(stmt) => {
2414            validate_db_permission!(stmt, query_ctx);
2415        }
2416        Statement::ShowIndex(stmt) => {
2417            validate_db_permission!(stmt, query_ctx);
2418        }
2419        Statement::ShowRegion(stmt) => {
2420            validate_db_permission!(stmt, query_ctx);
2421        }
2422        Statement::ShowViews(stmt) => {
2423            validate_db_permission!(stmt, query_ctx);
2424        }
2425        Statement::ShowFlows(stmt) => {
2426            validate_db_permission!(stmt, query_ctx);
2427        }
2428        Statement::ShowFlowStatus(_stmt) => {
2429            // Flow statistics are organized based on the catalog dimension and
2430            // filtered by the current catalog, so there is no need to check the
2431            // permission of the database(schema).
2432        }
2433        #[cfg(feature = "enterprise")]
2434        Statement::ShowTriggers(_stmt) => {
2435            // The trigger is organized based on the catalog dimension, so there
2436            // is no need to check the permission of the database(schema).
2437        }
2438        Statement::ShowStatus(_stmt) => {}
2439        Statement::ShowSearchPath(_stmt) => {}
2440        Statement::DescribeTable(stmt) => {
2441            validate_param(stmt.name(), query_ctx)?;
2442        }
2443        Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => match stmt {
2444            CopyTable::To(copy_table_to) => validate_param(&copy_table_to.table_name, query_ctx)?,
2445            CopyTable::From(copy_table_from) => {
2446                validate_param(&copy_table_from.table_name, query_ctx)?
2447            }
2448        },
2449        Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
2450            match copy_database {
2451                CopyDatabase::To(stmt) => validate_database(&stmt.database_name, query_ctx)?,
2452                CopyDatabase::From(stmt) => validate_database(&stmt.database_name, query_ctx)?,
2453            }
2454        }
2455        Statement::TruncateTable(stmt) => {
2456            validate_param(stmt.table_name(), query_ctx)?;
2457        }
2458        // cursor operations are always allowed once it's created
2459        Statement::FetchCursor(_) | Statement::CloseCursor(_) => {}
2460        // User can only kill process in their own catalog.
2461        Statement::Kill(_) => {}
2462        // SHOW PROCESSLIST
2463        Statement::ShowProcesslist(_) => {}
2464    }
2465    Ok(())
2466}
2467
2468fn validate_param(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
2469    let (catalog, schema, _) = table_idents_to_full_name(name, query_ctx)
2470        .map_err(BoxedError::new)
2471        .context(ExternalSnafu)?;
2472
2473    validate_catalog_and_schema(&catalog, &schema, query_ctx)
2474        .map_err(BoxedError::new)
2475        .context(SqlExecInterceptedSnafu)
2476}
2477
2478fn validate_flow(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
2479    let catalog = match &name.0[..] {
2480        [_flow] => query_ctx.current_catalog().to_string(),
2481        [catalog, _flow] => catalog.to_string_unquoted(),
2482        _ => {
2483            return InvalidSqlSnafu {
2484                err_msg: format!(
2485                    "expect flow name to be <catalog>.<flow_name> or <flow_name>, actual: {name}",
2486                ),
2487            }
2488            .fail();
2489        }
2490    };
2491
2492    let schema = query_ctx.current_schema();
2493
2494    validate_catalog_and_schema(&catalog, &schema, query_ctx)
2495        .map_err(BoxedError::new)
2496        .context(SqlExecInterceptedSnafu)
2497}
2498
2499fn validate_database(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
2500    let (catalog, schema) = match &name.0[..] {
2501        [schema] => (
2502            query_ctx.current_catalog().to_string(),
2503            schema.to_string_unquoted(),
2504        ),
2505        [catalog, schema] => (catalog.to_string_unquoted(), schema.to_string_unquoted()),
2506        _ => InvalidSqlSnafu {
2507            err_msg: format!(
2508                "expect database name to be <catalog>.<schema> or <schema>, actual: {name}",
2509            ),
2510        }
2511        .fail()?,
2512    };
2513
2514    validate_catalog_and_schema(&catalog, &schema, query_ctx)
2515        .map_err(BoxedError::new)
2516        .context(SqlExecInterceptedSnafu)
2517}
2518
2519fn is_readonly_plan(plan: &LogicalPlan) -> bool {
2520    !matches!(plan, LogicalPlan::Dml(_) | LogicalPlan::Ddl(_))
2521}
2522
2523fn should_track_statement_process(stmt: &Statement) -> bool {
2524    stmt.is_readonly()
2525        || matches!(stmt, Statement::Insert(insert) if insert.has_non_values_query_source())
2526}
2527
2528fn should_track_plan_process(stmt: Option<&Statement>, plan: &LogicalPlan) -> bool {
2529    is_readonly_plan(plan)
2530        || matches!(stmt, Some(Statement::Insert(insert)) if insert.has_non_values_query_source())
2531}
2532
2533#[cfg(test)]
2534mod tests {
2535    use std::any::Any;
2536    use std::collections::HashMap;
2537    use std::future::Future;
2538    use std::pin::Pin;
2539    use std::sync::Arc;
2540    use std::task::{Context, Poll};
2541    use std::time::Duration;
2542
2543    use api::prom_store::remote::label_matcher::Type as PromMatcherType;
2544    use api::prom_store::remote::{
2545        Label, LabelMatcher, Query as RemoteQuery, ReadRequest, ReadResponse, Sample,
2546    };
2547    use api::v1::greptime_request::Request;
2548    use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse};
2549    use api::v1::query_request::Query;
2550    use auth::{
2551        DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE, JAEGER_QUERY, PIPELINE_DELETE,
2552        PIPELINE_INSERT, PIPELINE_QUERY, PermissionAction, PermissionResp, UserInfo, UserInfoRef,
2553    };
2554    use catalog::process_manager::{ProcessManager, QueryStatement, SlowQueryTimer};
2555    use common_base::Plugins;
2556    use common_base::cancellation::CancellationHandle;
2557    use common_catalog::consts::DEFAULT_PRIVATE_SCHEMA_NAME;
2558    use common_error::ext::{BoxedError, ErrorExt, PlainError};
2559    use common_error::status_code::StatusCode;
2560    use common_event_recorder::{Event, EventRecorder, EventTypeFilter, EventTypeFilterRef};
2561    use common_frontend::metrics::{CACHE_HIT, CACHE_MISS};
2562    use common_frontend::slow_query_event::SlowQueryEvent;
2563    use common_meta::cache::LayeredCacheRegistryBuilder;
2564    use common_meta::kv_backend::memory::MemoryKvBackend;
2565    use common_meta::procedure_executor::{ExecutorContext, ProcedureExecutor};
2566    use common_meta::rpc::ddl::{DdlTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse};
2567    use common_meta::rpc::procedure::{
2568        MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse,
2569    };
2570    use common_query::prelude::greptime_value;
2571    use common_query::{Output, OutputMeta};
2572    use common_recordbatch::{
2573        OrderOption, RecordBatch, RecordBatchStream, RecordBatches, SendableRecordBatchStream,
2574    };
2575    use common_telemetry::logging::SlowQueriesRecordType;
2576    use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
2577    use datafusion::physical_plan::empty::EmptyExec;
2578    use datafusion_expr::dml::InsertOp;
2579    use datafusion_expr::{LogicalPlanBuilder, LogicalTableSource};
2580    use datatypes::prelude::ConcreteDataType;
2581    use datatypes::schema::{ColumnSchema, Schema as GtSchema, SchemaRef as GtSchemaRef};
2582    use datatypes::vectors::{
2583        Float64Vector, StringVector, TimestampMillisecondVector, TimestampNanosecondVector,
2584        VectorRef,
2585    };
2586    use log_query::LogQuery;
2587    use promql_parser::parser::EvalStmt;
2588    use prost::Message;
2589    use query::query_engine::options::QueryOptions;
2590    use servers::query_handler::{
2591        DashboardHandler, JaegerQueryHandler, LogQueryHandler, PipelineHandler, PipelineHandlerRef,
2592        PromStoreProtocolHandler,
2593    };
2594    use session::context::{Channel, ConnInfo, QueryContext, QueryContextBuilder};
2595    use snafu::{Location, Snafu};
2596    use sql::dialect::GreptimeDbDialect;
2597    use store_api::data_source::DataSource;
2598    use store_api::metric_engine_consts::{
2599        LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
2600    };
2601    use store_api::storage::ScanRequest;
2602    use strfmt::Format;
2603    use table::metadata::{
2604        FilterPushDownType, TableId, TableInfo, TableInfoBuilder, TableMetaBuilder, TableType,
2605    };
2606    use table::table_name::TableName;
2607    use table::test_util::{EmptyTable, MemTable};
2608    use table::{Table, TableRef};
2609    use tokio::sync::{mpsc, oneshot};
2610    use tower::ServiceExt;
2611
2612    use crate::frontend::FrontendOptions;
2613    use crate::instance::builder::FrontendBuilder;
2614    use crate::instance::*;
2615
2616    /// The id the `cpu` metric table of [`metric_instance`] is registered under.
2617    const CPU_TABLE_ID: TableId = 1024;
2618
2619    fn parse_test_sql(sql: &str) -> Vec<Statement> {
2620        parse_stmt(sql, &GreptimeDbDialect {}).unwrap()
2621    }
2622
2623    #[derive(Debug, Default)]
2624    struct RecordingSlowQueryEventRecorder {
2625        queries: std::sync::Mutex<Vec<String>>,
2626        payloads: std::sync::Mutex<Vec<serde_json::Value>>,
2627    }
2628
2629    impl EventRecorder for RecordingSlowQueryEventRecorder {
2630        fn record(&self, event: Box<dyn Event>) {
2631            let event = event
2632                .as_any()
2633                .downcast_ref::<SlowQueryEvent>()
2634                .expect("expected a slow query event");
2635            self.queries.lock().unwrap().push(event.query.clone());
2636            self.payloads.lock().unwrap().push(event.payload.clone());
2637        }
2638
2639        fn event_type_filter(&self) -> EventTypeFilterRef {
2640            Arc::new(EventTypeFilter::All)
2641        }
2642
2643        fn close(&self) {}
2644    }
2645
2646    #[test]
2647    fn test_validate_analyze_stream_statement_strictness() {
2648        for sql in [
2649            "select 1",
2650            "explain analyze select 1",
2651            "explain analyze verbose format text select 1",
2652            "explain analyze verbose format graphviz select 1",
2653            "TQL ANALYZE (0, 10, '5s') physical_metric",
2654            "TQL EXPLAIN VERBOSE (0, 10, '5s') physical_metric",
2655            "TQL ANALYZE VERBOSE FORMAT TEXT (0, 10, '5s') physical_metric",
2656        ] {
2657            let mut stmts = parse_test_sql(sql);
2658            assert!(
2659                validate_analyze_stream_statement(&mut stmts[0]).is_err(),
2660                "{sql}"
2661            );
2662        }
2663
2664        for sql in [
2665            "explain analyze verbose select 1",
2666            "explain analyze verbose format json select 1",
2667            "TQL ANALYZE VERBOSE (0, 10, '5s') physical_metric",
2668            "TQL ANALYZE VERBOSE FORMAT JSON (0, 10, '5s') physical_metric",
2669        ] {
2670            let mut stmts = parse_test_sql(sql);
2671            assert!(
2672                validate_analyze_stream_statement(&mut stmts[0]).is_ok(),
2673                "{sql}"
2674            );
2675            match &stmts[0] {
2676                Statement::Explain(explain) => assert!(explain.format.is_none()),
2677                Statement::Tql(Tql::Analyze(analyze)) => assert!(analyze.format.is_none()),
2678                _ => unreachable!(),
2679            }
2680        }
2681
2682        assert_eq!(
2683            parse_test_sql("explain analyze verbose select 1; select 2").len(),
2684            2
2685        );
2686
2687        assert!(is_explain_analyze_verbose(
2688            &parse_test_sql("explain analyze verbose select 1")[0]
2689        ));
2690        assert!(is_explain_analyze_verbose(
2691            &parse_test_sql("TQL ANALYZE VERBOSE (0, 10, '5s') physical_metric")[0]
2692        ));
2693        for sql in [
2694            "select 1",
2695            "explain select 1",
2696            "explain analyze select 1",
2697            "explain verbose select 1",
2698            "TQL ANALYZE (0, 10, '5s') physical_metric",
2699            "TQL EXPLAIN VERBOSE (0, 10, '5s') physical_metric",
2700        ] {
2701            assert!(
2702                !is_explain_analyze_verbose(&parse_test_sql(sql)[0]),
2703                "{sql}"
2704            );
2705        }
2706    }
2707
2708    #[derive(Debug, Snafu)]
2709    enum TestError {
2710        #[snafu(display("Failed to build test cache registry"))]
2711        BuildCacheRegistry {
2712            source: cache::error::Error,
2713            #[snafu(implicit)]
2714            location: Location,
2715        },
2716
2717        #[snafu(display("Failed to build test table meta for table: {table_name}"))]
2718        BuildTableMeta {
2719            table_name: String,
2720            source: table::metadata::TableMetaBuilderError,
2721            #[snafu(implicit)]
2722            location: Location,
2723        },
2724
2725        #[snafu(display("Failed to build test table info for table: {table_name}"))]
2726        BuildTableInfo {
2727            table_name: String,
2728            source: table::metadata::TableInfoBuilderError,
2729            #[snafu(implicit)]
2730            location: Location,
2731        },
2732
2733        #[snafu(display("Failed to register test table: {table_name}"))]
2734        RegisterTable {
2735            table_name: String,
2736            source: catalog::error::Error,
2737            #[snafu(implicit)]
2738            location: Location,
2739        },
2740
2741        #[snafu(display("Failed to build test frontend instance"))]
2742        BuildFrontend {
2743            source: crate::error::Error,
2744            #[snafu(implicit)]
2745            location: Location,
2746        },
2747
2748        #[snafu(display("Expected exactly one output for SQL `{sql}`, got {actual}"))]
2749        UnexpectedOutputCount {
2750            sql: String,
2751            actual: usize,
2752            #[snafu(implicit)]
2753            location: Location,
2754        },
2755
2756        #[snafu(display("Failed to execute SQL `{sql}`"))]
2757        ExecuteSql {
2758            sql: String,
2759            source: crate::error::Error,
2760            #[snafu(implicit)]
2761            location: Location,
2762        },
2763
2764        #[snafu(display("Timed out waiting for insert-select start notification"))]
2765        InsertStartTimeout {
2766            source: tokio::time::error::Elapsed,
2767            #[snafu(implicit)]
2768            location: Location,
2769        },
2770
2771        #[snafu(display("Insert-select start notification channel closed"))]
2772        InsertStartChannelClosed {
2773            #[snafu(implicit)]
2774            location: Location,
2775        },
2776
2777        #[snafu(display("Failed to release blocking insert-select interceptor"))]
2778        ReleaseBlockedInsert {
2779            #[snafu(implicit)]
2780            location: Location,
2781        },
2782
2783        #[snafu(display("Timed out waiting for insert-select source to be polled"))]
2784        SourcePollTimeout {
2785            source: tokio::time::error::Elapsed,
2786            #[snafu(implicit)]
2787            location: Location,
2788        },
2789
2790        #[snafu(display("Insert-select source poll notification channel closed"))]
2791        SourcePollChannelClosed {
2792            source: oneshot::error::RecvError,
2793            #[snafu(implicit)]
2794            location: Location,
2795        },
2796
2797        #[snafu(display("Timed out waiting for insert task to finish"))]
2798        InsertTaskTimeout {
2799            source: tokio::time::error::Elapsed,
2800            #[snafu(implicit)]
2801            location: Location,
2802        },
2803
2804        #[snafu(display("Insert task panicked"))]
2805        InsertTaskPanic {
2806            source: tokio::task::JoinError,
2807            #[snafu(implicit)]
2808            location: Location,
2809        },
2810
2811        #[snafu(display("Expected insert-select to be cancelled"))]
2812        InsertSelectNotCancelled {
2813            #[snafu(implicit)]
2814            location: Location,
2815        },
2816    }
2817
2818    type TestResult<T> = std::result::Result<T, TestError>;
2819
2820    fn parse_one_sql(sql: &str) -> Statement {
2821        parse_stmt(sql, &GreptimeDbDialect {}).unwrap().remove(0)
2822    }
2823
2824    fn test_query_ctx(process_id: u32) -> QueryContextRef {
2825        Arc::new(
2826            QueryContextBuilder::default()
2827                .channel(Channel::Mysql)
2828                .conn_info(ConnInfo::new(None, Channel::Mysql))
2829                .process_id(process_id)
2830                .build(),
2831        )
2832    }
2833
2834    #[derive(Debug)]
2835    struct AdminUserInfo;
2836
2837    impl UserInfo for AdminUserInfo {
2838        fn as_any(&self) -> &dyn Any {
2839            self
2840        }
2841
2842        fn username(&self) -> &str {
2843            "admin"
2844        }
2845
2846        fn is_admin(&self) -> bool {
2847            true
2848        }
2849    }
2850
2851    /// A checker that authorizes per table and counts the grants it was asked for, so a test can
2852    /// state that a path did (or did not) ask.
2853    #[derive(Default)]
2854    struct CountingPermissionChecker {
2855        table_target_checks: atomic::AtomicUsize,
2856    }
2857
2858    impl CountingPermissionChecker {
2859        fn table_target_checks(&self) -> usize {
2860            self.table_target_checks.load(atomic::Ordering::Relaxed)
2861        }
2862    }
2863
2864    impl PermissionChecker for CountingPermissionChecker {
2865        fn check_permission(
2866            &self,
2867            _user_info: UserInfoRef,
2868            _req: PermissionReq,
2869        ) -> auth::error::Result<PermissionResp> {
2870            Ok(PermissionResp::Allow)
2871        }
2872
2873        fn check_permission_with_table_targets(
2874            &self,
2875            _user_info: UserInfoRef,
2876            _req: PermissionReq,
2877            _targets: PermissionTableTargets,
2878            _current_schema: Option<&str>,
2879        ) -> auth::error::Result<PermissionResp> {
2880            self.table_target_checks
2881                .fetch_add(1, atomic::Ordering::Relaxed);
2882            Ok(PermissionResp::Allow)
2883        }
2884
2885        fn uses_table_targets(&self) -> bool {
2886            true
2887        }
2888    }
2889
2890    struct RejectUnresolvedPermissionChecker;
2891
2892    impl PermissionChecker for RejectUnresolvedPermissionChecker {
2893        fn check_permission(
2894            &self,
2895            _user_info: UserInfoRef,
2896            _req: PermissionReq,
2897        ) -> auth::error::Result<PermissionResp> {
2898            Ok(PermissionResp::Allow)
2899        }
2900
2901        fn check_permission_with_table_targets(
2902            &self,
2903            _user_info: UserInfoRef,
2904            _req: PermissionReq,
2905            targets: PermissionTableTargets,
2906            _current_schema: Option<&str>,
2907        ) -> auth::error::Result<PermissionResp> {
2908            let reject = match targets {
2909                PermissionTableTargets::Unresolved => true,
2910                PermissionTableTargets::Resolved(targets) => targets
2911                    .iter()
2912                    .any(|target| target.table == "denied" || target.is_physical_metric_table),
2913            };
2914            Ok(if reject {
2915                PermissionResp::Reject
2916            } else {
2917                PermissionResp::Allow
2918            })
2919        }
2920    }
2921
2922    #[derive(Debug, PartialEq, Eq)]
2923    struct CheckedAction {
2924        action: PermissionAction,
2925        targets: Option<PermissionTableTargets>,
2926    }
2927
2928    #[derive(Default)]
2929    struct RejectEndpointPermissionChecker {
2930        checks: std::sync::Mutex<Vec<CheckedAction>>,
2931    }
2932
2933    impl RejectEndpointPermissionChecker {
2934        fn reject(
2935            &self,
2936            action: PermissionAction,
2937            targets: Option<PermissionTableTargets>,
2938        ) -> PermissionResp {
2939            self.checks
2940                .lock()
2941                .unwrap()
2942                .push(CheckedAction { action, targets });
2943            PermissionResp::Reject
2944        }
2945
2946        fn take_check(&self) -> CheckedAction {
2947            let mut checks = self.checks.lock().unwrap();
2948            assert_eq!(1, checks.len());
2949            checks.pop().unwrap()
2950        }
2951    }
2952
2953    impl PermissionChecker for RejectEndpointPermissionChecker {
2954        fn check_permission(
2955            &self,
2956            _user_info: UserInfoRef,
2957            req: PermissionReq,
2958        ) -> auth::error::Result<PermissionResp> {
2959            Ok(match req {
2960                PermissionReq::Action(action) => self.reject(action, None),
2961                _ => PermissionResp::Allow,
2962            })
2963        }
2964
2965        fn check_permission_with_table_targets(
2966            &self,
2967            _user_info: UserInfoRef,
2968            req: PermissionReq,
2969            targets: PermissionTableTargets,
2970            _current_schema: Option<&str>,
2971        ) -> auth::error::Result<PermissionResp> {
2972            Ok(match req {
2973                PermissionReq::Action(action) => self.reject(action, Some(targets)),
2974                _ => PermissionResp::Allow,
2975            })
2976        }
2977    }
2978
2979    struct WriteOnlyPermissionChecker;
2980
2981    impl PermissionChecker for WriteOnlyPermissionChecker {
2982        fn check_permission(
2983            &self,
2984            _user_info: UserInfoRef,
2985            req: PermissionReq,
2986        ) -> auth::error::Result<PermissionResp> {
2987            Ok(if req.is_readonly() {
2988                PermissionResp::Reject
2989            } else {
2990                PermissionResp::Allow
2991            })
2992        }
2993
2994        fn check_permission_with_table_targets(
2995            &self,
2996            user_info: UserInfoRef,
2997            req: PermissionReq,
2998            _targets: PermissionTableTargets,
2999            _current_schema: Option<&str>,
3000        ) -> auth::error::Result<PermissionResp> {
3001            self.check_permission(user_info, req)
3002        }
3003    }
3004
3005    #[derive(Default)]
3006    struct TargetIndependentPermissionChecker {
3007        checks: atomic::AtomicUsize,
3008    }
3009
3010    impl PermissionChecker for TargetIndependentPermissionChecker {
3011        fn check_permission(
3012            &self,
3013            _user_info: UserInfoRef,
3014            _req: PermissionReq,
3015        ) -> auth::error::Result<PermissionResp> {
3016            self.checks.fetch_add(1, atomic::Ordering::Relaxed);
3017            Ok(PermissionResp::Allow)
3018        }
3019
3020        fn uses_table_targets(&self) -> bool {
3021            false
3022        }
3023
3024        fn check_permission_with_table_targets(
3025            &self,
3026            user_info: UserInfoRef,
3027            req: PermissionReq,
3028            _targets: PermissionTableTargets,
3029            _current_schema: Option<&str>,
3030        ) -> auth::error::Result<PermissionResp> {
3031            self.check_permission(user_info, req)
3032        }
3033    }
3034
3035    struct BlockingInsertSelectInterceptor {
3036        started_tx: mpsc::UnboundedSender<()>,
3037        finish_rx: std::sync::Mutex<Option<oneshot::Receiver<()>>>,
3038    }
3039
3040    impl BlockingInsertSelectInterceptor {
3041        fn new(started_tx: mpsc::UnboundedSender<()>, finish_rx: oneshot::Receiver<()>) -> Self {
3042            Self {
3043                started_tx,
3044                finish_rx: std::sync::Mutex::new(Some(finish_rx)),
3045            }
3046        }
3047    }
3048
3049    impl SqlQueryInterceptor for BlockingInsertSelectInterceptor {
3050        type Error = Error;
3051
3052        fn pre_execute(
3053            &self,
3054            statement: Option<&Statement>,
3055            _plan: Option<&LogicalPlan>,
3056            _query_ctx: QueryContextRef,
3057        ) -> Result<()> {
3058            let Some(Statement::Insert(insert)) = statement else {
3059                return Ok(());
3060            };
3061            if !insert.has_non_values_query_source() {
3062                return Ok(());
3063            }
3064
3065            let finish_rx = self.finish_rx.lock().unwrap().take().unwrap();
3066            let _ = self.started_tx.send(());
3067            tokio::task::block_in_place(|| {
3068                tokio::runtime::Handle::current()
3069                    .block_on(finish_rx)
3070                    .unwrap();
3071            });
3072            Ok(())
3073        }
3074    }
3075
3076    struct PendingRecordBatchStream {
3077        schema: GtSchemaRef,
3078        polled_tx: Option<oneshot::Sender<()>>,
3079        _finish_tx: oneshot::Sender<()>,
3080        finish_rx: Pin<Box<oneshot::Receiver<()>>>,
3081    }
3082
3083    impl RecordBatchStream for PendingRecordBatchStream {
3084        fn schema(&self) -> GtSchemaRef {
3085            self.schema.clone()
3086        }
3087
3088        fn output_ordering(&self) -> Option<&[OrderOption]> {
3089            None
3090        }
3091
3092        fn metrics(&self) -> Option<common_recordbatch::adapter::RecordBatchMetrics> {
3093            None
3094        }
3095    }
3096
3097    impl Stream for PendingRecordBatchStream {
3098        type Item = common_recordbatch::error::Result<RecordBatch>;
3099
3100        fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3101            if let Some(polled_tx) = self.polled_tx.take() {
3102                let _ = polled_tx.send(());
3103            }
3104
3105            match self.finish_rx.as_mut().poll(cx) {
3106                Poll::Ready(_) => Poll::Ready(None),
3107                Poll::Pending => Poll::Pending,
3108            }
3109        }
3110    }
3111
3112    impl Unpin for PendingRecordBatchStream {}
3113
3114    #[test]
3115    fn test_record_explain_analyze_timeout_uses_empty_metrics_without_plan() {
3116        let event_recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
3117        let timer = SlowQueryTimer::new(
3118            QueryStatement::Plan("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
3119            "public".to_string(),
3120            Duration::from_secs(3600),
3121            0.0,
3122            SlowQueriesRecordType::SystemTable,
3123            event_recorder.clone(),
3124        );
3125        let timeout_recorder = timer.recorder();
3126
3127        record_explain_analyze_timeout(Some(&timeout_recorder), None);
3128        drop(timer);
3129
3130        let payloads = event_recorder.payloads.lock().unwrap();
3131        assert_eq!(payloads.len(), 1);
3132        assert_eq!(payloads[0]["timed_out"], true);
3133        assert_eq!(payloads[0]["metrics"], serde_json::json!([]));
3134    }
3135
3136    #[tokio::test]
3137    async fn test_attach_timeout_records_explain_analyze_metrics() {
3138        let event_recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
3139        let timer = SlowQueryTimer::new(
3140            QueryStatement::Plan("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
3141            "public".to_string(),
3142            Duration::from_secs(3600),
3143            0.0,
3144            SlowQueriesRecordType::SystemTable,
3145            event_recorder.clone(),
3146        );
3147        let timeout_recorder = timer.recorder();
3148        let plan: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(Arc::new(Schema::empty())));
3149        let (finish_tx, finish_rx) = oneshot::channel();
3150        let stream = PendingRecordBatchStream {
3151            schema: Arc::new(GtSchema::new(vec![])),
3152            polled_tx: None,
3153            _finish_tx: finish_tx,
3154            finish_rx: Box::pin(finish_rx),
3155        };
3156        let output = Output::new(
3157            OutputData::Stream(Box::pin(stream)),
3158            OutputMeta::new_with_plan(plan),
3159        );
3160        let output =
3161            attach_timeout(output, Duration::from_millis(10), Some(timeout_recorder)).unwrap();
3162        let OutputData::Stream(mut stream) = output.data else {
3163            unreachable!();
3164        };
3165
3166        let err = stream.next().await.unwrap().unwrap_err();
3167        assert_eq!(err.to_string(), "Stream timeout");
3168        drop(stream);
3169        drop(timer);
3170
3171        let payloads = event_recorder.payloads.lock().unwrap();
3172        assert_eq!(payloads.len(), 1);
3173        assert_eq!(payloads[0]["timed_out"], true);
3174        assert!(
3175            payloads[0]["metrics"]
3176                .as_array()
3177                .is_some_and(|metrics| !metrics.is_empty())
3178        );
3179    }
3180
3181    struct PendingDataSource {
3182        schema: GtSchemaRef,
3183        polled_tx: std::sync::Mutex<Option<oneshot::Sender<()>>>,
3184    }
3185
3186    impl DataSource for PendingDataSource {
3187        fn get_stream(
3188            &self,
3189            _request: ScanRequest,
3190        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
3191            let (finish_tx, finish_rx) = oneshot::channel();
3192            let mut polled_tx = self.polled_tx.lock().map_err(|_| {
3193                BoxedError::new(PlainError::new(
3194                    "pending data source lock poisoned".to_string(),
3195                    StatusCode::Unexpected,
3196                ))
3197            })?;
3198            Ok(Box::pin(PendingRecordBatchStream {
3199                schema: self.schema.clone(),
3200                polled_tx: polled_tx.take(),
3201                _finish_tx: finish_tx,
3202                finish_rx: Box::pin(finish_rx),
3203            }))
3204        }
3205    }
3206
3207    struct NoopProcedureExecutor;
3208
3209    #[async_trait::async_trait]
3210    impl ProcedureExecutor for NoopProcedureExecutor {
3211        async fn submit_ddl_task(
3212            &self,
3213            _ctx: ExecutorContext,
3214            _request: SubmitDdlTaskRequest,
3215        ) -> common_meta::error::Result<SubmitDdlTaskResponse> {
3216            common_meta::error::UnsupportedSnafu {
3217                operation: "submit_ddl_task",
3218            }
3219            .fail()
3220        }
3221
3222        async fn migrate_region(
3223            &self,
3224            _ctx: &ExecutorContext,
3225            _request: MigrateRegionRequest,
3226        ) -> common_meta::error::Result<MigrateRegionResponse> {
3227            common_meta::error::UnsupportedSnafu {
3228                operation: "migrate_region",
3229            }
3230            .fail()
3231        }
3232
3233        async fn reconcile(
3234            &self,
3235            _ctx: &ExecutorContext,
3236            _request: ReconcileRequest,
3237        ) -> common_meta::error::Result<ReconcileResponse> {
3238            common_meta::error::UnsupportedSnafu {
3239                operation: "reconcile",
3240            }
3241            .fail()
3242        }
3243
3244        async fn query_procedure_state(
3245            &self,
3246            _ctx: &ExecutorContext,
3247            _pid: &str,
3248        ) -> common_meta::error::Result<ProcedureStateResponse> {
3249            common_meta::error::UnsupportedSnafu {
3250                operation: "query_procedure_state",
3251            }
3252            .fail()
3253        }
3254
3255        async fn list_procedures(
3256            &self,
3257            _ctx: &ExecutorContext,
3258        ) -> common_meta::error::Result<ProcedureDetailResponse> {
3259            common_meta::error::UnsupportedSnafu {
3260                operation: "list_procedures",
3261            }
3262            .fail()
3263        }
3264    }
3265
3266    /// A test [`ProcedureExecutor`] that completes create/drop DDL tasks against the
3267    /// in-memory catalog, mimicking what the meta DDL procedures do in production.
3268    /// This allows happy-path DDL requests (create/drop table/view) to be exercised
3269    /// end to end through the gRPC ingress.
3270    struct MockProcedureExecutor {
3271        catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
3272        next_table_id: std::sync::atomic::AtomicU32,
3273        submitted: std::sync::Mutex<Vec<DdlTask>>,
3274    }
3275
3276    impl MockProcedureExecutor {
3277        fn new(catalog_manager: Arc<catalog::memory::MemoryCatalogManager>) -> Self {
3278            Self {
3279                catalog_manager,
3280                next_table_id: std::sync::atomic::AtomicU32::new(1026),
3281                submitted: std::sync::Mutex::new(Vec::new()),
3282            }
3283        }
3284    }
3285
3286    #[async_trait::async_trait]
3287    impl ProcedureExecutor for MockProcedureExecutor {
3288        async fn submit_ddl_task(
3289            &self,
3290            _ctx: ExecutorContext,
3291            request: SubmitDdlTaskRequest,
3292        ) -> common_meta::error::Result<SubmitDdlTaskResponse> {
3293            self.submitted.lock().unwrap().push(request.task.clone());
3294            match request.task {
3295                DdlTask::CreateTable(task) => {
3296                    let table_id = self
3297                        .next_table_id
3298                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3299                    let mut table_info = task.table_info;
3300                    table_info.ident.table_id = table_id;
3301                    self.catalog_manager
3302                        .register_table_sync(catalog::RegisterTableRequest {
3303                            catalog: table_info.catalog_name.clone(),
3304                            schema: table_info.schema_name.clone(),
3305                            table_name: table_info.name.clone(),
3306                            table_id,
3307                            table: table::dist_table::DistTable::table(Arc::new(table_info)),
3308                        })
3309                        .map_err(BoxedError::new)
3310                        .context(common_meta::error::ExternalSnafu)?;
3311                    Ok(SubmitDdlTaskResponse {
3312                        key: Vec::new(),
3313                        table_ids: vec![table_id],
3314                    })
3315                }
3316                DdlTask::CreateView(task) => {
3317                    let view_id = self
3318                        .next_table_id
3319                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3320                    let mut view_info = task.view_info;
3321                    view_info.ident.table_id = view_id;
3322                    self.catalog_manager
3323                        .register_table_sync(catalog::RegisterTableRequest {
3324                            catalog: task.create_view.catalog_name.clone(),
3325                            schema: task.create_view.schema_name.clone(),
3326                            table_name: task.create_view.view_name.clone(),
3327                            table_id: view_id,
3328                            table: table::dist_table::DistTable::table(Arc::new(view_info)),
3329                        })
3330                        .map_err(BoxedError::new)
3331                        .context(common_meta::error::ExternalSnafu)?;
3332                    Ok(SubmitDdlTaskResponse {
3333                        key: Vec::new(),
3334                        table_ids: vec![view_id],
3335                    })
3336                }
3337                DdlTask::DropView(task) => {
3338                    self.catalog_manager
3339                        .deregister_table_sync(catalog::DeregisterTableRequest {
3340                            catalog: task.catalog.clone(),
3341                            schema: task.schema.clone(),
3342                            table_name: task.view.clone(),
3343                        })
3344                        .map_err(BoxedError::new)
3345                        .context(common_meta::error::ExternalSnafu)?;
3346                    Ok(SubmitDdlTaskResponse::default())
3347                }
3348                DdlTask::CreateFlow(_) => Ok(SubmitDdlTaskResponse::default()),
3349                other => common_meta::error::UnsupportedSnafu {
3350                    operation: format!("mock submit_ddl_task: {other:?}"),
3351                }
3352                .fail(),
3353            }
3354        }
3355
3356        async fn migrate_region(
3357            &self,
3358            _ctx: &ExecutorContext,
3359            _request: MigrateRegionRequest,
3360        ) -> common_meta::error::Result<MigrateRegionResponse> {
3361            common_meta::error::UnsupportedSnafu {
3362                operation: "migrate_region",
3363            }
3364            .fail()
3365        }
3366
3367        async fn reconcile(
3368            &self,
3369            _ctx: &ExecutorContext,
3370            _request: ReconcileRequest,
3371        ) -> common_meta::error::Result<ReconcileResponse> {
3372            common_meta::error::UnsupportedSnafu {
3373                operation: "reconcile",
3374            }
3375            .fail()
3376        }
3377
3378        async fn query_procedure_state(
3379            &self,
3380            _ctx: &ExecutorContext,
3381            _pid: &str,
3382        ) -> common_meta::error::Result<ProcedureStateResponse> {
3383            common_meta::error::UnsupportedSnafu {
3384                operation: "query_procedure_state",
3385            }
3386            .fail()
3387        }
3388
3389        async fn list_procedures(
3390            &self,
3391            _ctx: &ExecutorContext,
3392        ) -> common_meta::error::Result<ProcedureDetailResponse> {
3393            common_meta::error::UnsupportedSnafu {
3394                operation: "list_procedures",
3395            }
3396            .fail()
3397        }
3398    }
3399
3400    fn test_cache_registry(
3401        kv_backend: common_meta::kv_backend::KvBackendRef,
3402    ) -> TestResult<common_meta::cache::LayeredCacheRegistryRef> {
3403        Ok(Arc::new(
3404            cache::with_default_composite_cache_registry(
3405                LayeredCacheRegistryBuilder::default()
3406                    .add_cache_registry(cache::build_fundamental_cache_registry(kv_backend)),
3407            )
3408            .context(BuildCacheRegistrySnafu)?
3409            .build(),
3410        ))
3411    }
3412
3413    fn test_table_info(table_id: u32, table_name: &str) -> TestResult<TableInfo> {
3414        let schema = Arc::new(GtSchema::new(vec![
3415            ColumnSchema::new("id", ConcreteDataType::int32_datatype(), false),
3416            ColumnSchema::new(
3417                "ts",
3418                ConcreteDataType::timestamp_millisecond_datatype(),
3419                false,
3420            )
3421            .with_time_index(true),
3422        ]));
3423        let table_meta = TableMetaBuilder::empty()
3424            .schema(schema)
3425            .primary_key_indices(vec![0])
3426            .value_indices(vec![1])
3427            .next_column_id(1024)
3428            .build()
3429            .with_context(|_| BuildTableMetaSnafu {
3430                table_name: table_name.to_string(),
3431            })?;
3432
3433        TableInfoBuilder::new(table_name, table_meta)
3434            .table_id(table_id)
3435            .build()
3436            .with_context(|_| BuildTableInfoSnafu {
3437                table_name: table_name.to_string(),
3438            })
3439    }
3440
3441    fn test_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
3442        let table_info = test_table_info(table_id, table_name)?;
3443        Ok(EmptyTable::from_table_info(&table_info))
3444    }
3445
3446    fn test_physical_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
3447        let mut table_info = test_table_info(table_id, table_name)?;
3448        table_info
3449            .meta
3450            .options
3451            .extra_options
3452            .insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), String::new());
3453        Ok(EmptyTable::from_table_info(&table_info))
3454    }
3455
3456    fn test_logical_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
3457        let mut table_info = test_table_info(table_id, table_name)?;
3458        table_info.meta.engine = METRIC_ENGINE_NAME.to_string();
3459        table_info.meta.options.extra_options.insert(
3460            LOGICAL_TABLE_METADATA_KEY.to_string(),
3461            "physical_metric".to_string(),
3462        );
3463        Ok(EmptyTable::from_table_info(&table_info))
3464    }
3465
3466    /// A metric table of one series whose rows are exactly `rows`.
3467    ///
3468    /// A PromQL range query reads a table through its time index and its value
3469    /// columns, which a table's metadata names, so the fixture states both: the
3470    /// `ts` column is the time index and `cpu` is the single value column. Every
3471    /// scan sees the same rows, which is what makes a cached answer and an executed
3472    /// one comparable.
3473    fn test_metric_table_with_rows(rows: Vec<(i64, f64)>) -> TableRef {
3474        let schema = Arc::new(GtSchema::new(vec![
3475            ColumnSchema::new(
3476                "ts",
3477                ConcreteDataType::timestamp_millisecond_datatype(),
3478                false,
3479            )
3480            .with_time_index(true),
3481            ColumnSchema::new("cpu", ConcreteDataType::float64_datatype(), false),
3482        ]));
3483        let (timestamps, values): (Vec<_>, Vec<_>) = rows.into_iter().unzip();
3484        let recordbatch = RecordBatch::new(
3485            schema.clone(),
3486            vec![
3487                Arc::new(TimestampMillisecondVector::from_vec(timestamps)) as VectorRef,
3488                Arc::new(Float64Vector::from_vec(values)) as VectorRef,
3489            ],
3490        )
3491        .unwrap();
3492        let table_meta = TableMetaBuilder::empty()
3493            .schema(schema)
3494            // No tag columns: the fixture is one series.
3495            .primary_key_indices(vec![])
3496            .value_indices(vec![1])
3497            .next_column_id(1024)
3498            .build()
3499            .unwrap();
3500        let table_info = TableInfoBuilder::new("cpu", table_meta)
3501            .table_id(1024)
3502            .catalog_name("greptime")
3503            .schema_name("public")
3504            .build()
3505            .unwrap();
3506        Arc::new(Table::new(
3507            Arc::new(table_info),
3508            FilterPushDownType::Unsupported,
3509            Arc::new(StaticRowsDataSource { recordbatch }),
3510        ))
3511    }
3512
3513    /// A data source that answers every scan with the same rows.
3514    struct StaticRowsDataSource {
3515        recordbatch: RecordBatch,
3516    }
3517
3518    impl StaticRowsDataSource {
3519        /// The fixture has no storage error of its own, so a failure to lay its one
3520        /// batch out is reported as the test bug it is.
3521        fn boxed(error: impl std::fmt::Display) -> BoxedError {
3522            BoxedError::new(PlainError::new(error.to_string(), StatusCode::Unexpected))
3523        }
3524    }
3525
3526    impl DataSource for StaticRowsDataSource {
3527        fn get_stream(
3528            &self,
3529            request: ScanRequest,
3530        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
3531            let projected = match request.projection.as_deref() {
3532                Some(indices) => self
3533                    .recordbatch
3534                    .df_record_batch()
3535                    .project(indices)
3536                    .map_err(Self::boxed)?,
3537                None => self.recordbatch.df_record_batch().clone(),
3538            };
3539            let schema = Arc::new(GtSchema::try_from(projected.schema()).map_err(Self::boxed)?);
3540            let recordbatch = RecordBatch::from_df_record_batch(schema.clone(), projected);
3541            Ok(RecordBatches::try_new(schema, vec![recordbatch])
3542                .map_err(Self::boxed)?
3543                .as_stream())
3544        }
3545    }
3546
3547    /// Runs one PromQL request and returns the rows it answered with, in order.
3548    async fn promql_rows(
3549        instance: &Instance,
3550        query: &PromQuery,
3551        ctx: QueryContextRef,
3552    ) -> TestResult<RecordBatches> {
3553        let output = PrometheusHandler::do_query(instance, query, ctx)
3554            .await
3555            .with_context(|_| ExecutePromqlSnafu {
3556                query: query.query.clone(),
3557            })
3558            .with_context(|_| ExecuteSqlSnafu {
3559                sql: query.query.clone(),
3560            })?;
3561        match output.data {
3562            OutputData::RecordBatches(rows) => Ok(rows),
3563            OutputData::Stream(stream) => RecordBatches::try_collect(stream)
3564                .await
3565                .context(CollectRecordbatchSnafu)
3566                .with_context(|_| ExecuteSqlSnafu {
3567                    sql: query.query.clone(),
3568                }),
3569            OutputData::AffectedRows(_) => unreachable!("a PromQL query returns rows"),
3570        }
3571    }
3572
3573    /// The rows of a result, in order, as one printed table.
3574    ///
3575    /// The spans of a chunked request read into several batches while a request that
3576    /// executed its whole plan reads into one, so comparing batch by batch would
3577    /// compare layouts rather than rows; one table prints the rows either way.
3578    fn printed(rows: &RecordBatches) -> String {
3579        rows.pretty_print().unwrap()
3580    }
3581
3582    /// How many rows a result holds.
3583    ///
3584    /// A test that compares two answers states with it that the answer they agree on is
3585    /// not empty, which two empty answers would satisfy vacuously.
3586    fn row_count(rows: &RecordBatches) -> usize {
3587        rows.iter().map(|batch| batch.num_rows()).sum()
3588    }
3589
3590    /// A range cache configured with a five-minute chunk target, with no tail, so a
3591    /// request over whole chunks is cacheable in a test that runs at wall-clock time.
3592    ///
3593    /// The target is below the twenty-step floor of a one-minute query, so the chunk
3594    /// these tests plan with is twenty minutes wide, not five.
3595    fn test_promql_rollup_cache() -> Arc<crate::promql_query_cache::PromqlRollupCache> {
3596        let config = crate::promql_query_cache::PromqlRollupCacheConfig::new(
3597            1 << 20,
3598            Duration::ZERO,
3599            Duration::from_secs(300),
3600            Duration::from_secs(3_600),
3601        )
3602        .unwrap();
3603        Arc::new(crate::promql_query_cache::PromqlRollupCache::new(config))
3604    }
3605
3606    /// One-minute steps from 10:00, with a gap between minutes 12 and 19: a
3607    /// lookback of one minute leaves the points inside the gap without a sample.
3608    fn metric_rows() -> Vec<(i64, f64)> {
3609        const HEAD_MS: i64 = 36_000_000;
3610        (0..60i64)
3611            .filter(|minute| !(13..19).contains(minute))
3612            .map(|minute| (HEAD_MS + minute * 60_000, minute as f64))
3613            .collect()
3614    }
3615
3616    /// The range query `expr` asks for: 10:00 to 10:59, one-minute steps, a
3617    /// one-minute lookback.
3618    fn metric_range_query(expr: &str) -> PromQuery {
3619        PromQuery {
3620            query: expr.to_string(),
3621            start: "36000".to_string(),
3622            end: "39540".to_string(),
3623            step: "60".to_string(),
3624            lookback: "60".to_string(),
3625            alias: None,
3626        }
3627    }
3628
3629    /// An instance over [`test_metric_table_with_rows`], with `cache` installed
3630    /// when one is given.
3631    async fn metric_instance(
3632        promql_rollup_cache: Option<Arc<crate::promql_query_cache::PromqlRollupCache>>,
3633    ) -> TestResult<Instance> {
3634        let catalog_manager = catalog::memory::MemoryCatalogManager::new_with_table(
3635            test_metric_table_with_rows(metric_rows()),
3636        );
3637        test_instance_with_catalog_manager_and_cache(
3638            catalog_manager,
3639            test_table(1025, "target")?,
3640            Plugins::default(),
3641            None,
3642            Arc::new(NoopProcedureExecutor),
3643            promql_rollup_cache,
3644        )
3645        .await
3646    }
3647
3648    #[test]
3649    fn range_query_identity_uses_source_from_the_statement_across_sliding_windows() {
3650        let mut query = metric_range_query("sum(rate(cpu[5m]))");
3651        let stmt = EvalStmt {
3652            expr: promql_parser::parser::parse(&query.query).unwrap(),
3653            start: std::time::UNIX_EPOCH + Duration::from_secs(36_000),
3654            end: std::time::UNIX_EPOCH + Duration::from_secs(37_740),
3655            interval: Duration::from_secs(60),
3656            lookback_delta: Duration::from_secs(60),
3657        };
3658        let context = test_query_ctx(1);
3659        let plan = LogicalPlanBuilder::empty(false).build().unwrap();
3660        let first =
3661            Instance::range_query_identity(&query, &stmt, None, &plan, &context, CPU_TABLE_ID)
3662                .expect("the expression names one admitted table");
3663        assert_eq!(first.source_table, "cpu");
3664        assert_eq!(first.table_id, CPU_TABLE_ID);
3665
3666        query.start = "36300".to_string();
3667        query.end = "38040".to_string();
3668        let mut sliding = stmt.clone();
3669        sliding.start += Duration::from_secs(300);
3670        sliding.end += Duration::from_secs(300);
3671        let second =
3672            Instance::range_query_identity(&query, &sliding, None, &plan, &context, CPU_TABLE_ID)
3673                .expect("the sliding expression names the same table");
3674        assert_eq!(first, second);
3675        assert_eq!(second.source_table, "cpu");
3676
3677        // The statement expression, not the original query text, is authoritative.
3678        sliding.expr = promql_parser::parser::parse("sum(rate(memory[5m]))").unwrap();
3679        let other =
3680            Instance::range_query_identity(&query, &sliding, None, &plan, &context, CPU_TABLE_ID)
3681                .expect("the statement names a table");
3682        assert_eq!(other.source_table, "memory");
3683        assert_ne!(first, other);
3684    }
3685
3686    #[test]
3687    fn range_query_identity_bypasses_when_the_source_is_unknown() {
3688        let context = test_query_ctx(1);
3689        let plan = LogicalPlanBuilder::empty(false).build().unwrap();
3690        for text in ["cpu + memory", "avg(cpu)", "{host=\"a\"}"] {
3691            let query = metric_range_query(text);
3692            let stmt = EvalStmt {
3693                expr: promql_parser::parser::parse(text).unwrap(),
3694                start: std::time::UNIX_EPOCH,
3695                end: std::time::UNIX_EPOCH + Duration::from_secs(300),
3696                interval: Duration::from_secs(60),
3697                lookback_delta: Duration::from_secs(60),
3698            };
3699            assert!(
3700                Instance::range_query_identity(&query, &stmt, None, &plan, &context, CPU_TABLE_ID)
3701                    .is_none(),
3702                "{text}"
3703            );
3704        }
3705    }
3706
3707    #[tokio::test]
3708    async fn promql_rollup_cache_is_disabled_by_default() -> TestResult<()> {
3709        let instance = metric_instance(None).await?;
3710
3711        assert!(instance.promql_rollup_cache().is_none());
3712
3713        Ok(())
3714    }
3715
3716    /// Runs the cached range path of `instance` the way a Prometheus range request
3717    /// reaches it: the statement is planned exactly as the original path plans it, and
3718    /// that plan is what the cache is consulted with.
3719    ///
3720    /// Answers the rows the cache served, or `None` when it declined and the original
3721    /// plan has to run. The ordering flag is the one the HTTP and gRPC Prometheus
3722    /// handlers mark: a request that demands execution order keeps its own plan.
3723    async fn run_cached_range(
3724        instance: &Instance,
3725        query: &PromQuery,
3726        ctx: QueryContextRef,
3727        requires_output_ordering: bool,
3728    ) -> TestResult<Option<RecordBatches>> {
3729        let parsed = ParsedPromQuery::parse(query.clone(), &ctx)
3730            .expect("the test query is a parsable PromQL statement");
3731        let (query, statement) = parsed.into_parts();
3732        let query::parser::QueryStatement::Promql(eval_stmt, alias) = &statement else {
3733            unreachable!("a PromQL query parses into a PromQL statement");
3734        };
3735        let plan = instance
3736            .statement_executor()
3737            .plan(&statement, ctx.clone())
3738            .await
3739            .expect("the test statement plans");
3740        instance
3741            .cached_range_output(
3742                &query,
3743                eval_stmt,
3744                alias.clone(),
3745                requires_output_ordering,
3746                &plan,
3747                &ctx,
3748                Arc::new(CancellationHandle::default()),
3749            )
3750            .await
3751            .context(ExecutePromqlSnafu {
3752                query: query.query.clone(),
3753            })
3754            .with_context(|_| ExecuteSqlSnafu {
3755                sql: query.query.clone(),
3756            })
3757    }
3758
3759    /// [`run_cached_range`] on a request the cache must serve.
3760    async fn cached_rows(instance: &Instance, query: &PromQuery) -> TestResult<RecordBatches> {
3761        Ok(run_cached_range(instance, query, test_query_ctx(1), false)
3762            .await?
3763            .expect("the cache served the request"))
3764    }
3765
3766    #[tokio::test]
3767    async fn a_range_query_fills_the_cache_and_the_next_one_is_served() -> TestResult<()> {
3768        let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
3769        let cache = cached.promql_rollup_cache().unwrap().clone();
3770        let plain = metric_instance(None).await?;
3771        // A `rate` rather than a bare selector, which bypasses the cache before it is
3772        // ever consulted.
3773        let query = metric_range_query("rate(cpu[5m])");
3774
3775        let cold = cached_rows(&cached, &query).await?;
3776        assert_eq!(
3777            3,
3778            cache.entry_count(),
3779            "sixty one-minute points are three twenty-step chunks"
3780        );
3781        assert_eq!(0, cache.hit_count(), "the first request filled every chunk");
3782        let warm = cached_rows(&cached, &query).await?;
3783        let uncached = promql_rows(&plain, &query, test_query_ctx(3)).await?;
3784
3785        // The gap is in the answer: the points inside it have no pair of samples the
3786        // `rate` can fold, so the range query holds fewer rows than the sixty grid
3787        // points it evaluates, and more than none.
3788        let rows = row_count(&cold);
3789        assert!(
3790            rows > 0 && rows < 60,
3791            "the gap leaves points unanswered: {rows}"
3792        );
3793        assert_eq!(printed(&uncached), printed(&cold));
3794        assert_eq!(printed(&uncached), printed(&warm));
3795        assert_eq!(3, cache.hit_count(), "the warm request served every chunk");
3796        Ok(())
3797    }
3798
3799    #[tokio::test]
3800    async fn every_bypass_reason_keeps_the_original_plan() -> TestResult<()> {
3801        let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
3802        let cache = cached.promql_rollup_cache().unwrap().clone();
3803        let plain = metric_instance(None).await?;
3804        let cacheable = metric_range_query("rate(cpu[5m])");
3805
3806        // One row per reason a range request keeps its own plan. `nocache` is the client's
3807        // request and the rest are what the request carries, so each row states the flag
3808        // and the context it needs and nothing else.
3809        let nocache = QueryContextBuilder::default()
3810            .set_extension(
3811                session::hints::PROMQL_ROLLUP_CACHE_NOCACHE.to_string(),
3812                "true".to_string(),
3813            )
3814            .build();
3815        let mut instant = cacheable.clone();
3816        instant.start = "36300".to_string();
3817        instant.end = instant.start.clone();
3818        let snapshot = QueryContext::with_db_name(None);
3819        snapshot.set_snapshot(1, 42);
3820        let sst_bounded = QueryContextBuilder::default()
3821            .sst_min_sequences(Arc::new(std::sync::RwLock::new(HashMap::from([(1, 90)]))))
3822            .build();
3823        let flow = QueryContextBuilder::default()
3824            .set_extension("flow.incremental_start".to_string(), "1".to_string())
3825            .build();
3826
3827        for (reason, query, ctx, ordering) in [
3828            ("nocache", &cacheable, Arc::new(nocache), false),
3829            ("instant query", &instant, test_query_ctx(1), false),
3830            ("output ordering", &cacheable, test_query_ctx(1), true),
3831            ("snapshot", &cacheable, Arc::new(snapshot), false),
3832            ("SST bound", &cacheable, Arc::new(sst_bounded), false),
3833            ("flow bound", &cacheable, Arc::new(flow), false),
3834        ] {
3835            assert!(
3836                run_cached_range(&cached, query, ctx.clone(), ordering)
3837                    .await?
3838                    .is_none(),
3839                "{reason}: the cache must decline"
3840            );
3841            // The request still answers what the ordinary path answers, and it fills
3842            // nothing on the way.
3843            let answer = promql_rows(&cached, query, ctx.clone()).await?;
3844            let uncached = promql_rows(&plain, query, ctx).await?;
3845            assert!(
3846                row_count(&answer) > 0,
3847                "{reason}: the answers compared are not empty"
3848            );
3849            assert_eq!(printed(&uncached), printed(&answer), "{reason}");
3850            assert_eq!(0, cache.entry_count(), "{reason}: nothing may be filled");
3851            assert_eq!(0, cache.hit_count(), "{reason}: nothing may be served");
3852        }
3853        Ok(())
3854    }
3855
3856    #[tokio::test]
3857    async fn a_schema_override_range_query_bypasses_the_promql_rollup_cache() -> TestResult<()> {
3858        let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
3859        let cache = cached.promql_rollup_cache().unwrap().clone();
3860        let plain = metric_instance(None).await?;
3861
3862        // `__schema__` makes the planner read another schema, and the cache key only
3863        // names the current one. The expression is a `rate` around a named selector, so
3864        // what bypasses is the override leaving the window allowlist rather than the
3865        // bare-selector heuristic.
3866        let overridden = metric_range_query(r#"rate(cpu{__schema__="public"}[5m])"#);
3867        let answer = promql_rows(&cached, &overridden, test_query_ctx(1)).await?;
3868        let uncached = promql_rows(&plain, &overridden, test_query_ctx(2)).await?;
3869        assert!(row_count(&answer) > 0, "the answers compared are not empty");
3870        assert_eq!(printed(&uncached), printed(&answer));
3871        assert!(
3872            run_cached_range(&cached, &overridden, test_query_ctx(3), false)
3873                .await?
3874                .is_none(),
3875            "a schema override is never planned into chunks"
3876        );
3877        assert_eq!(0, cache.entry_count(), "schema override fills nothing");
3878        Ok(())
3879    }
3880
3881    #[tokio::test]
3882    async fn a_bare_selector_range_query_bypasses_the_promql_rollup_cache() -> TestResult<()> {
3883        // A bare selector is scan- and serialize-dominated, so a chunk served from memory
3884        // costs a copy and a merge of the cached payload (and the fill pays for both) on
3885        // top of a read that was already cheap: the cached path measured ~23% slower in a
3886        // local benchmark on a 2048-series selector. Such a request therefore keeps its
3887        // original plan and fills nothing. Parentheses only group, so they do not make a
3888        // selector cacheable again.
3889        let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
3890        let cache = cached.promql_rollup_cache().unwrap().clone();
3891        let plain = metric_instance(None).await?;
3892
3893        for expr in ["cpu", "((cpu))"] {
3894            let query = metric_range_query(expr);
3895            let cold = promql_rows(&cached, &query, test_query_ctx(1)).await?;
3896            let repeated = promql_rows(&cached, &query, test_query_ctx(2)).await?;
3897            let uncached = promql_rows(&plain, &query, test_query_ctx(3)).await?;
3898
3899            assert_eq!(printed(&uncached), printed(&cold), "{expr}");
3900            assert_eq!(printed(&uncached), printed(&repeated), "{expr}");
3901            assert!(
3902                row_count(&cold) > 0,
3903                "{expr}: the answers compared are not empty"
3904            );
3905            assert!(
3906                run_cached_range(&cached, &query, test_query_ctx(4), false)
3907                    .await?
3908                    .is_none(),
3909                "{expr}: a bare selector keeps its own plan"
3910            );
3911        }
3912        assert_eq!(0, cache.entry_count(), "a bare selector fills nothing");
3913        assert_eq!(0, cache.hit_count(), "a bare selector is never served");
3914
3915        Ok(())
3916    }
3917
3918    #[tokio::test]
3919    async fn the_annotations_of_a_merged_answer_are_replayed_once() {
3920        // The response path reads the collector the request opened, so everything the
3921        // chunked execution recorded has to be replayed into it — once, however many
3922        // spans recorded the same message.
3923        let query_ctx = Arc::new(QueryContext::with("greptime", "public"));
3924        let annotations = crate::promql_query_cache::CachedAnnotations::new(
3925            vec![
3926                "b-warning".to_string(),
3927                "a-warning".to_string(),
3928                "a-warning".to_string(),
3929            ],
3930            vec!["an-info".to_string()],
3931        );
3932
3933        // The response path holds the collector across the call, which is what keeps
3934        // the registry entry alive for the replay to write into.
3935        let collector = common_query::promql_annotations::promql_annotation_collector(
3936            query_ctx.remote_query_id().unwrap(),
3937        );
3938        Instance::record_annotations(&query_ctx, &annotations);
3939        Instance::record_annotations(&query_ctx, &annotations);
3940
3941        let (mut warnings, mut infos) = (Vec::new(), Vec::new());
3942        collector.append_to(&mut warnings, &mut infos);
3943        assert_eq!(
3944            vec!["a-warning".to_string(), "b-warning".to_string()],
3945            warnings
3946        );
3947        assert_eq!(vec!["an-info".to_string()], infos);
3948
3949        // The replay is per request: another request's collector is untouched, and a
3950        // request with nothing to report writes nothing.
3951        let other = Arc::new(QueryContext::with("greptime", "public"));
3952        let other_collector = common_query::promql_annotations::promql_annotation_collector(
3953            other.remote_query_id().unwrap(),
3954        );
3955        Instance::record_annotations(
3956            &other,
3957            &crate::promql_query_cache::CachedAnnotations::default(),
3958        );
3959        let (mut other_warnings, mut other_infos) = (Vec::new(), Vec::new());
3960        other_collector.append_to(&mut other_warnings, &mut other_infos);
3961        assert!(other_warnings.is_empty() && other_infos.is_empty());
3962    }
3963
3964    fn test_metric_names_table() -> TableRef {
3965        let schema = Arc::new(GtSchema::new(vec![
3966            ColumnSchema::new("table_catalog", ConcreteDataType::string_datatype(), false),
3967            ColumnSchema::new("table_schema", ConcreteDataType::string_datatype(), false),
3968            ColumnSchema::new("table_name", ConcreteDataType::string_datatype(), false),
3969            ColumnSchema::new("engine", ConcreteDataType::string_datatype(), false),
3970            ColumnSchema::new("create_options", ConcreteDataType::string_datatype(), false),
3971        ]));
3972        let columns: Vec<VectorRef> = vec![
3973            Arc::new(StringVector::from(vec!["greptime", "greptime"])),
3974            Arc::new(StringVector::from(vec!["public", "public"])),
3975            Arc::new(StringVector::from(vec!["denied", "target"])),
3976            Arc::new(StringVector::from(vec!["metric", "metric"])),
3977            Arc::new(StringVector::from(vec![
3978                "on_physical_table=physical_metric",
3979                "on_physical_table=physical_metric",
3980            ])),
3981        ];
3982        let record_batch = RecordBatch::new(schema, columns).unwrap();
3983        MemTable::new_with_catalog(
3984            "tables",
3985            record_batch,
3986            2048,
3987            "greptime".to_string(),
3988            "information_schema".to_string(),
3989        )
3990    }
3991
3992    fn test_pipeline_table() -> TableRef {
3993        let schema = Arc::new(GtSchema::new(vec![
3994            ColumnSchema::new("name", ConcreteDataType::string_datatype(), false),
3995            ColumnSchema::new("schema", ConcreteDataType::string_datatype(), false),
3996            ColumnSchema::new("content_type", ConcreteDataType::string_datatype(), false),
3997            ColumnSchema::new("pipeline", ConcreteDataType::string_datatype(), false),
3998            ColumnSchema::new(
3999                "created_at",
4000                ConcreteDataType::timestamp_nanosecond_datatype(),
4001                false,
4002            )
4003            .with_time_index(true),
4004        ]));
4005        let columns: Vec<VectorRef> = vec![
4006            Arc::new(StringVector::from(vec!["pipeline"])),
4007            Arc::new(StringVector::from(vec!["public"])),
4008            Arc::new(StringVector::from(vec!["application/yaml"])),
4009            Arc::new(StringVector::from(vec![
4010                "transform:\n- field: ts\n  type: timestamp, ns\n  index: time\n",
4011            ])),
4012            Arc::new(TimestampNanosecondVector::from_values([1])),
4013        ];
4014        let record_batch = RecordBatch::new(schema, columns).unwrap();
4015        MemTable::new_with_catalog(
4016            "pipelines",
4017            record_batch,
4018            2049,
4019            "greptime".to_string(),
4020            DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
4021        )
4022    }
4023
4024    struct CancellableExportSource {
4025        schema: GtSchemaRef,
4026        channels: std::sync::Mutex<Option<(oneshot::Sender<()>, oneshot::Receiver<()>)>>,
4027    }
4028
4029    impl DataSource for CancellableExportSource {
4030        fn get_stream(
4031            &self,
4032            _request: ScanRequest,
4033        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
4034            let (started, release) = self.channels.lock().unwrap().take().unwrap();
4035            let schema = self.schema.clone();
4036            let stream = futures::stream::once(async move {
4037                started.send(()).unwrap();
4038                release.await.unwrap();
4039                Ok(RecordBatch::new_empty(schema))
4040            });
4041            Ok(Box::pin(RecordBatchStreamWrapper::new(
4042                self.schema.clone(),
4043                Box::pin(stream),
4044            )))
4045        }
4046    }
4047
4048    #[tokio::test]
4049    async fn test_copy_database_enforces_read_and_write_targets() -> TestResult<()> {
4050        struct DatabaseCopyAcl {
4051            reject_read: bool,
4052        }
4053        impl PermissionChecker for DatabaseCopyAcl {
4054            fn check_permission(
4055                &self,
4056                _: UserInfoRef,
4057                _: PermissionReq,
4058            ) -> auth::error::Result<PermissionResp> {
4059                Ok(PermissionResp::Allow)
4060            }
4061            fn check_permission_with_table_targets(
4062                &self,
4063                _: UserInfoRef,
4064                req: PermissionReq,
4065                targets: PermissionTableTargets,
4066                _: Option<&str>,
4067            ) -> auth::error::Result<PermissionResp> {
4068                let applies = match req {
4069                    PermissionReq::Action(action) => action == COPY_TO && self.reject_read,
4070                    PermissionReq::SqlStatement(Statement::Copy(Copy::CopyDatabase(_))) => {
4071                        !self.reject_read
4072                    }
4073                    _ => false,
4074                };
4075                let PermissionTableTargets::Resolved(targets) = targets else {
4076                    return Ok(PermissionResp::Reject);
4077                };
4078                Ok(
4079                    if applies
4080                        && targets.iter().any(|target| {
4081                            target.table == "denied" || target.is_physical_metric_table
4082                        })
4083                    {
4084                        PermissionResp::Reject
4085                    } else {
4086                        PermissionResp::Allow
4087                    },
4088                )
4089            }
4090        }
4091        for (table, direction, reject_read) in [
4092            (test_table(1024, "denied")?, "TO", true),
4093            (test_table(1024, "denied")?, "TO", false),
4094            (test_table(1024, "denied")?, "FROM", false),
4095            (test_physical_table(1024, "physical")?, "FROM", false),
4096            (test_table(1024, "source")?, "TO", true),
4097            (test_table(1024, "source")?, "TO", false),
4098            (test_table(1024, "source")?, "FROM", false),
4099        ] {
4100            let dir = common_test_util::temp_dir::create_temp_dir("copy_database_permissions");
4101            let name = table.table_info().name.clone();
4102            let catalog = catalog::memory::MemoryCatalogManager::new_with_table(table);
4103            catalog
4104                .register_table_sync(catalog::RegisterTableRequest {
4105                    catalog: "greptime".into(),
4106                    schema: "public".into(),
4107                    table_name: "allowed".into(),
4108                    table_id: 1025,
4109                    table: test_table(1025, "allowed")?,
4110                })
4111                .unwrap();
4112            if direction == "FROM" {
4113                std::fs::write(dir.path().join("allowed.parquet"), b"not parquet").unwrap();
4114                std::fs::write(dir.path().join(format!("{name}.parquet")), b"not parquet").unwrap();
4115            }
4116            let kv = Arc::new(MemoryKvBackend::new());
4117            let plugins = Plugins::new();
4118            plugins.insert::<PermissionCheckerRef>(Arc::new(DatabaseCopyAcl { reject_read }));
4119            let instance = FrontendBuilder::new(
4120                FrontendOptions::default(),
4121                kv.clone(),
4122                test_cache_registry(kv)?,
4123                catalog,
4124                Arc::new(client::client_manager::NodeClients::default()),
4125                Arc::new(NoopProcedureExecutor),
4126                Arc::new(ProcessManager::new("copy-permissions".into(), None)),
4127            )
4128            .with_plugin(plugins)
4129            .with_local_file_access(
4130                common_datasource::object_store::LocalFileAccess::sandboxed(dir.path()).unwrap(),
4131            )
4132            .try_build()
4133            .await
4134            .context(BuildFrontendSnafu)?;
4135            let location = reqwest::Url::from_directory_path(dir.path()).unwrap();
4136            let sql = format!(
4137                "COPY DATABASE public {direction} '{location}' WITH (continue_on_error='true')"
4138            );
4139            let result = instance
4140                .do_query_inner(&sql, QueryContext::arc())
4141                .await
4142                .remove(0);
4143            if name == "source" {
4144                assert!(result.is_ok(), "{result:?}");
4145            } else {
4146                assert_eq!(
4147                    StatusCode::PermissionDenied,
4148                    result.unwrap_err().status_code()
4149                );
4150                if direction == "TO" {
4151                    assert_eq!(0, std::fs::read_dir(dir.path()).unwrap().count());
4152                }
4153            }
4154        }
4155        Ok(())
4156    }
4157
4158    #[tokio::test]
4159    async fn test_metric_export_http_timeout_cancels_ordinary_source() {
4160        let destination = common_test_util::temp_dir::create_temp_dir("metric_export_timeout");
4161        let (started_tx, started_rx) = oneshot::channel();
4162        let (mut release_tx, release_rx) = oneshot::channel();
4163        let info = test_table_info(1024, "source").unwrap();
4164        let source = Arc::new(Table::new(
4165            Arc::new(info.clone()),
4166            FilterPushDownType::Unsupported,
4167            Arc::new(CancellableExportSource {
4168                schema: info.meta.schema.clone(),
4169                channels: std::sync::Mutex::new(Some((started_tx, release_rx))),
4170            }),
4171        ));
4172        let catalog = catalog::memory::MemoryCatalogManager::new_with_table(source);
4173        let kv = Arc::new(MemoryKvBackend::new());
4174        let instance = FrontendBuilder::new(
4175            FrontendOptions::default(),
4176            kv.clone(),
4177            test_cache_registry(kv).unwrap(),
4178            catalog,
4179            Arc::new(client::client_manager::NodeClients::default()),
4180            Arc::new(NoopProcedureExecutor),
4181            Arc::new(ProcessManager::new("export-timeout".into(), None)),
4182        )
4183        .with_local_file_access(
4184            common_datasource::object_store::LocalFileAccess::sandboxed(destination.path())
4185                .unwrap(),
4186        )
4187        .try_build()
4188        .await
4189        .unwrap();
4190        let server = servers::http::HttpServerBuilder::new(servers::http::HttpOptions {
4191            timeout: Duration::from_secs(2),
4192            ..Default::default()
4193        })
4194        .with_sql_handler(Arc::new(instance))
4195        .build();
4196        let app = server.build(server.make_app()).unwrap();
4197        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4198        let addr = listener.local_addr().unwrap();
4199        let server_task = tokio::spawn(async move {
4200            axum::serve(listener, app).await.unwrap();
4201        });
4202        let uri = reqwest::Url::from_directory_path(destination.path()).unwrap();
4203        let sql = format!(
4204            "COPY DATABASE greptime.public TO '{uri}' WITH (experimental_metric_export='true')"
4205        );
4206        let request = tokio::spawn(async move {
4207            reqwest::Client::builder()
4208                .no_proxy()
4209                .build()
4210                .unwrap()
4211                .post(format!("http://{addr}/v1/sql"))
4212                .form(&[("sql", sql)])
4213                .send()
4214                .await
4215                .unwrap()
4216        });
4217        tokio::time::timeout(Duration::from_secs(5), started_rx)
4218            .await
4219            .unwrap()
4220            .unwrap();
4221        let response = request.await.unwrap();
4222        assert_eq!(response.status(), reqwest::StatusCode::REQUEST_TIMEOUT);
4223        tokio::time::timeout(Duration::from_secs(5), release_tx.closed())
4224            .await
4225            .unwrap();
4226        assert!(!destination.path().join("source.parquet").exists());
4227        server_task.abort();
4228    }
4229
4230    fn pending_table(
4231        table_id: u32,
4232        table_name: &str,
4233        polled_tx: oneshot::Sender<()>,
4234    ) -> TestResult<table::TableRef> {
4235        let table_info = test_table_info(table_id, table_name)?;
4236        let data_source = Arc::new(PendingDataSource {
4237            schema: table_info.meta.schema.clone(),
4238            polled_tx: std::sync::Mutex::new(Some(polled_tx)),
4239        });
4240
4241        Ok(Arc::new(Table::new(
4242            Arc::new(table_info),
4243            FilterPushDownType::Unsupported,
4244            data_source,
4245        )))
4246    }
4247
4248    async fn test_instance_with_tables(
4249        source_table: TableRef,
4250        target_table: TableRef,
4251    ) -> TestResult<Instance> {
4252        test_instance_with_plugins(source_table, target_table, Plugins::new()).await
4253    }
4254
4255    async fn test_instance_with_insert_select_interceptor(
4256        interceptor: SqlQueryInterceptorRef<Error>,
4257    ) -> TestResult<Instance> {
4258        let plugins = Plugins::new();
4259        plugins.insert::<SqlQueryInterceptorRef<Error>>(interceptor);
4260
4261        test_instance_with_plugins(
4262            test_table(1024, "source")?,
4263            test_table(1025, "target")?,
4264            plugins,
4265        )
4266        .await
4267    }
4268
4269    async fn test_instance_with_plugins(
4270        source_table: TableRef,
4271        target_table: TableRef,
4272        plugins: Plugins,
4273    ) -> TestResult<Instance> {
4274        test_instance_with_plugins_and_metric_names(source_table, target_table, plugins, None).await
4275    }
4276
4277    async fn test_instance_with_plugins_and_metric_names(
4278        source_table: TableRef,
4279        target_table: TableRef,
4280        plugins: Plugins,
4281        metric_names_table: Option<TableRef>,
4282    ) -> TestResult<Instance> {
4283        let catalog_manager = catalog::memory::MemoryCatalogManager::new_with_table(source_table);
4284        test_instance_with_catalog_manager(
4285            catalog_manager,
4286            target_table,
4287            plugins,
4288            metric_names_table,
4289            Arc::new(NoopProcedureExecutor),
4290        )
4291        .await
4292    }
4293
4294    /// Builds a test frontend `Instance` over the given (already source-registered)
4295    /// catalog manager, completing DDL tasks through `procedure_executor`.
4296    async fn test_instance_with_catalog_manager(
4297        catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
4298        target_table: TableRef,
4299        plugins: Plugins,
4300        metric_names_table: Option<TableRef>,
4301        procedure_executor: ProcedureExecutorRef,
4302    ) -> TestResult<Instance> {
4303        test_instance_with_catalog_manager_and_cache(
4304            catalog_manager,
4305            target_table,
4306            plugins,
4307            metric_names_table,
4308            procedure_executor,
4309            None,
4310        )
4311        .await
4312    }
4313
4314    /// [`test_instance_with_catalog_manager`] with the rollup cache the PromQL range
4315    /// path serves from, when a test installs one.
4316    async fn test_instance_with_catalog_manager_and_cache(
4317        catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
4318        target_table: TableRef,
4319        plugins: Plugins,
4320        metric_names_table: Option<TableRef>,
4321        procedure_executor: ProcedureExecutorRef,
4322        promql_rollup_cache: Option<Arc<crate::promql_query_cache::PromqlRollupCache>>,
4323    ) -> TestResult<Instance> {
4324        let kv_backend = Arc::new(MemoryKvBackend::new());
4325        let process_manager = Arc::new(ProcessManager::new("test-frontend".to_string(), None));
4326        let target_table_name = "target";
4327        catalog_manager
4328            .register_table_sync(catalog::RegisterTableRequest {
4329                catalog: "greptime".to_string(),
4330                schema: "public".to_string(),
4331                table_name: target_table_name.to_string(),
4332                table_id: 1025,
4333                table: target_table,
4334            })
4335            .with_context(|_| RegisterTableSnafu {
4336                table_name: target_table_name.to_string(),
4337            })?;
4338        if let Some(table) = metric_names_table {
4339            catalog_manager
4340                .deregister_table_sync(catalog::DeregisterTableRequest {
4341                    catalog: "greptime".to_string(),
4342                    schema: "information_schema".to_string(),
4343                    table_name: "tables".to_string(),
4344                })
4345                .unwrap();
4346            catalog_manager
4347                .register_table_sync(catalog::RegisterTableRequest {
4348                    catalog: "greptime".to_string(),
4349                    schema: "information_schema".to_string(),
4350                    table_name: "tables".to_string(),
4351                    table_id: 2048,
4352                    table,
4353                })
4354                .unwrap();
4355        }
4356        catalog_manager.register_process_list_table(process_manager.clone());
4357
4358        let cache_registry = test_cache_registry(kv_backend.clone())?;
4359
4360        let builder = FrontendBuilder::new(
4361            FrontendOptions::default(),
4362            kv_backend,
4363            cache_registry,
4364            catalog_manager,
4365            Arc::new(client::client_manager::NodeClients::default()),
4366            procedure_executor,
4367            process_manager,
4368        )
4369        .with_plugin(plugins);
4370        let builder = match promql_rollup_cache {
4371            Some(cache) => builder.with_promql_rollup_cache(cache),
4372            None => builder,
4373        };
4374        builder.try_build().await.context(BuildFrontendSnafu)
4375    }
4376
4377    async fn execute_one_sql(
4378        instance: &Instance,
4379        sql: &str,
4380        query_ctx: QueryContextRef,
4381    ) -> TestResult<Output> {
4382        let mut results = instance.do_query_inner(sql, query_ctx).await;
4383        ensure!(
4384            results.len() == 1,
4385            UnexpectedOutputCountSnafu {
4386                sql: sql.to_string(),
4387                actual: results.len(),
4388            }
4389        );
4390        results.remove(0).with_context(|_| ExecuteSqlSnafu {
4391            sql: sql.to_string(),
4392        })
4393    }
4394
4395    fn assert_permission_denied<T>(result: servers::error::Result<T>) {
4396        let err = match result {
4397            Ok(_) => panic!("request should be rejected"),
4398            Err(err) => err,
4399        };
4400        assert_eq!(StatusCode::PermissionDenied, err.status_code());
4401    }
4402
4403    fn assert_action_checked(
4404        checker: &RejectEndpointPermissionChecker,
4405        action: PermissionAction,
4406        targets: Option<PermissionTableTargets>,
4407    ) {
4408        assert_eq!(CheckedAction { action, targets }, checker.take_check());
4409    }
4410
4411    #[tokio::test]
4412    async fn database_export_authorizes_all_tables_before_preparation() -> TestResult<()> {
4413        struct ExportAcl(std::sync::Mutex<Vec<PermissionTableTargets>>);
4414        impl PermissionChecker for ExportAcl {
4415            fn check_permission(
4416                &self,
4417                _: UserInfoRef,
4418                req: PermissionReq,
4419            ) -> auth::error::Result<PermissionResp> {
4420                assert!(matches!(
4421                    req,
4422                    PermissionReq::SqlStatement(Statement::Copy(
4423                        sql::statements::copy::Copy::CopyDatabase(
4424                            sql::statements::copy::CopyDatabase::To(_)
4425                        )
4426                    ))
4427                ));
4428                Ok(PermissionResp::Allow)
4429            }
4430            fn check_permission_with_table_targets(
4431                &self,
4432                _: UserInfoRef,
4433                req: PermissionReq,
4434                targets: PermissionTableTargets,
4435                _: Option<&str>,
4436            ) -> auth::error::Result<PermissionResp> {
4437                self.0.lock().unwrap().push(targets.clone());
4438                let PermissionTableTargets::Resolved(tables) = targets else {
4439                    panic!("unresolved export")
4440                };
4441                if req.is_readonly() {
4442                    assert!(matches!(req, PermissionReq::Action(action) if action == COPY_TO));
4443                    // The first table is readable; the later table has only write access.
4444                    Ok(if tables.iter().any(|t| t.table == "target") {
4445                        PermissionResp::Reject
4446                    } else {
4447                        PermissionResp::Allow
4448                    })
4449                } else {
4450                    self.check_permission(QueryContext::arc().current_user(), req)
4451                }
4452            }
4453        }
4454        let checker = Arc::new(ExportAcl(Default::default()));
4455        let plugins = Plugins::new();
4456        plugins.insert::<PermissionCheckerRef>(checker.clone());
4457        let instance = test_instance_with_plugins(
4458            test_logical_table(1024, "source")?,
4459            test_table(1025, "target")?,
4460            plugins,
4461        )
4462        .await?;
4463        let req = table::requests::CopyDatabaseRequest {
4464            catalog_name: "greptime".into(),
4465            schema_name: "public".into(),
4466            location: "invalid-destination".into(),
4467            with: Default::default(),
4468            connection: Default::default(),
4469            time_range: None,
4470        };
4471        let result = instance
4472            .export_database_for_test(
4473                req.clone(),
4474                None,
4475                &tokio_util::sync::CancellationToken::new(),
4476                QueryContext::arc(),
4477            )
4478            .await;
4479        assert!(matches!(result, Err(Error::Permission { .. })));
4480        let expected = PermissionTableTargets::resolved(vec![
4481            PermissionTableTarget::new("greptime", "public", "source"),
4482            PermissionTableTarget::new("greptime", "public", "target"),
4483        ]);
4484        assert_eq!(*checker.0.lock().unwrap(), vec![expected.clone(), expected]);
4485        // An empty selection must still check the operation privilege.
4486        instance
4487            .plugins
4488            .map_mut::<PermissionCheckerRef, _, _>(|checker| {
4489                *checker.unwrap() = Arc::new(WriteOnlyPermissionChecker)
4490            });
4491        let result = instance
4492            .export_database_for_test(
4493                req,
4494                Some(&[]),
4495                &tokio_util::sync::CancellationToken::new(),
4496                QueryContext::arc(),
4497            )
4498            .await;
4499        assert!(matches!(result, Err(Error::Permission { .. })));
4500        Ok(())
4501    }
4502
4503    #[tokio::test]
4504    async fn test_prom_remote_read_with_custom_timestamp_and_value_columns() -> TestResult<()> {
4505        let schema = Arc::new(GtSchema::new(vec![
4506            ColumnSchema::new(
4507                "custom_ts",
4508                ConcreteDataType::timestamp_millisecond_datatype(),
4509                false,
4510            )
4511            .with_time_index(true),
4512            ColumnSchema::new("custom_value", ConcreteDataType::float64_datatype(), false),
4513        ]));
4514        let recordbatch = RecordBatch::new(
4515            schema,
4516            vec![
4517                Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as VectorRef,
4518                Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as VectorRef,
4519            ],
4520        )
4521        .unwrap();
4522        let instance = test_instance_with_tables(
4523            MemTable::table("custom_metric", recordbatch),
4524            test_table(1025, "target")?,
4525        )
4526        .await?;
4527
4528        let response = PromStoreProtocolHandler::read(
4529            &instance,
4530            ReadRequest {
4531                queries: vec![RemoteQuery {
4532                    start_timestamp_ms: 1500,
4533                    end_timestamp_ms: 2500,
4534                    matchers: vec![LabelMatcher {
4535                        r#type: PromMatcherType::Eq as i32,
4536                        name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
4537                        value: "custom_metric".to_string(),
4538                    }],
4539                    ..Default::default()
4540                }],
4541                ..Default::default()
4542            },
4543            test_query_ctx(1),
4544        )
4545        .await
4546        .unwrap();
4547        let body = servers::prom_store::snappy_decompress(&response.body).unwrap();
4548        let response = ReadResponse::decode(body.as_slice()).unwrap();
4549
4550        assert_eq!(1, response.results.len());
4551        assert_eq!(1, response.results[0].timeseries.len());
4552        let timeseries = &response.results[0].timeseries[0];
4553        assert_eq!(
4554            vec![Label {
4555                name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
4556                value: "custom_metric".to_string(),
4557            }],
4558            timeseries.labels
4559        );
4560        assert_eq!(
4561            vec![Sample {
4562                value: 2.0,
4563                timestamp: 2000,
4564            }],
4565            timeseries.samples
4566        );
4567
4568        Ok(())
4569    }
4570
4571    #[tokio::test]
4572    async fn test_prom_remote_read_prefers_default_value_column() -> TestResult<()> {
4573        let schema = Arc::new(GtSchema::new(vec![
4574            ColumnSchema::new(
4575                "custom_ts",
4576                ConcreteDataType::timestamp_millisecond_datatype(),
4577                false,
4578            )
4579            .with_time_index(true),
4580            ColumnSchema::new("extra_field", ConcreteDataType::string_datatype(), false),
4581            ColumnSchema::new(
4582                greptime_value(),
4583                ConcreteDataType::float64_datatype(),
4584                false,
4585            ),
4586        ]));
4587        let recordbatch = RecordBatch::new(
4588            schema,
4589            vec![
4590                Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as VectorRef,
4591                Arc::new(StringVector::from(vec!["99", "99", "99"])) as VectorRef,
4592                Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as VectorRef,
4593            ],
4594        )
4595        .unwrap();
4596        let instance = test_instance_with_tables(
4597            MemTable::table("multi_field_metric", recordbatch),
4598            test_table(1025, "target")?,
4599        )
4600        .await?;
4601
4602        let response = PromStoreProtocolHandler::read(
4603            &instance,
4604            ReadRequest {
4605                queries: vec![RemoteQuery {
4606                    start_timestamp_ms: 1500,
4607                    end_timestamp_ms: 2500,
4608                    matchers: vec![LabelMatcher {
4609                        r#type: PromMatcherType::Eq as i32,
4610                        name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
4611                        value: "multi_field_metric".to_string(),
4612                    }],
4613                    ..Default::default()
4614                }],
4615                ..Default::default()
4616            },
4617            test_query_ctx(1),
4618        )
4619        .await
4620        .unwrap();
4621        let body = servers::prom_store::snappy_decompress(&response.body).unwrap();
4622        let response = ReadResponse::decode(body.as_slice()).unwrap();
4623
4624        assert_eq!(1, response.results.len());
4625        assert_eq!(1, response.results[0].timeseries.len());
4626        let timeseries = &response.results[0].timeseries[0];
4627        assert_eq!(
4628            vec![
4629                Label {
4630                    name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
4631                    value: "multi_field_metric".to_string(),
4632                },
4633                Label {
4634                    name: "extra_field".to_string(),
4635                    value: "99".to_string(),
4636                },
4637            ],
4638            timeseries.labels
4639        );
4640        assert_eq!(
4641            vec![Sample {
4642                value: 2.0,
4643                timestamp: 2000,
4644            }],
4645            timeseries.samples
4646        );
4647
4648        Ok(())
4649    }
4650
4651    #[tokio::test]
4652    async fn test_prom_remote_read_rejects_ambiguous_value_columns() -> TestResult<()> {
4653        let schema = Arc::new(GtSchema::new(vec![
4654            ColumnSchema::new(
4655                "custom_ts",
4656                ConcreteDataType::timestamp_millisecond_datatype(),
4657                false,
4658            )
4659            .with_time_index(true),
4660            ColumnSchema::new("field_a", ConcreteDataType::float64_datatype(), false),
4661            ColumnSchema::new("field_b", ConcreteDataType::float64_datatype(), false),
4662        ]));
4663        let recordbatch = RecordBatch::new(
4664            schema,
4665            vec![
4666                Arc::new(TimestampMillisecondVector::from_vec(vec![1000])) as VectorRef,
4667                Arc::new(Float64Vector::from_vec(vec![1.0])) as VectorRef,
4668                Arc::new(Float64Vector::from_vec(vec![2.0])) as VectorRef,
4669            ],
4670        )
4671        .unwrap();
4672        let instance = test_instance_with_tables(
4673            MemTable::table("ambiguous_metric", recordbatch),
4674            test_table(1025, "target")?,
4675        )
4676        .await?;
4677
4678        let err = PromStoreProtocolHandler::read(
4679            &instance,
4680            ReadRequest {
4681                queries: vec![RemoteQuery {
4682                    matchers: vec![LabelMatcher {
4683                        r#type: PromMatcherType::Eq as i32,
4684                        name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
4685                        value: "ambiguous_metric".to_string(),
4686                    }],
4687                    ..Default::default()
4688                }],
4689                ..Default::default()
4690            },
4691            test_query_ctx(1),
4692        )
4693        .await
4694        .err()
4695        .expect("ambiguous value columns should fail remote read");
4696
4697        assert_eq!(StatusCode::InvalidArguments, err.status_code());
4698        assert!(format!("{err:?}").contains("Ambiguous value column"));
4699
4700        Ok(())
4701    }
4702
4703    #[tokio::test]
4704    async fn test_restricted_endpoint_handlers_check_permissions() -> TestResult<()> {
4705        let checker = Arc::new(RejectEndpointPermissionChecker::default());
4706        let plugins = Plugins::new();
4707        plugins.insert::<PermissionCheckerRef>(checker.clone());
4708        let instance = test_instance_with_plugins(
4709            test_table(1024, "denied")?,
4710            test_table(1025, "target")?,
4711            plugins,
4712        )
4713        .await?;
4714        let mut ctx = test_query_ctx(1);
4715        Arc::get_mut(&mut ctx).unwrap().set_extension(
4716            servers::http::jaeger::JAEGER_QUERY_TABLE_NAME_KEY,
4717            "denied".to_string(),
4718        );
4719        let jaeger_targets = Some(PermissionTableTargets::resolved(vec![
4720            PermissionTableTarget::new("greptime", "public", "denied"),
4721        ]));
4722
4723        assert_permission_denied(JaegerQueryHandler::get_services(&instance, ctx.clone()).await);
4724        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
4725        assert_permission_denied(
4726            JaegerQueryHandler::get_operations(&instance, ctx.clone(), "service", None).await,
4727        );
4728        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
4729        assert_permission_denied(
4730            JaegerQueryHandler::get_trace(&instance, ctx.clone(), "trace", None, None, None).await,
4731        );
4732        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
4733        assert_permission_denied(
4734            JaegerQueryHandler::find_traces(
4735                &instance,
4736                ctx.clone(),
4737                servers::http::jaeger::QueryTraceParams {
4738                    service_name: Some("service".to_string()),
4739                    ..Default::default()
4740                },
4741            )
4742            .await,
4743        );
4744        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets);
4745
4746        assert_permission_denied(
4747            PipelineHandler::get_pipeline_str(&instance, "pipeline", None, ctx.clone()).await,
4748        );
4749        assert_action_checked(&checker, PIPELINE_QUERY, None);
4750        assert_permission_denied(
4751            PipelineHandler::insert_pipeline(
4752                &instance,
4753                "pipeline",
4754                "application/yaml",
4755                "",
4756                ctx.clone(),
4757            )
4758            .await,
4759        );
4760        assert_action_checked(&checker, PIPELINE_INSERT, None);
4761        assert_permission_denied(
4762            PipelineHandler::delete_pipeline(&instance, "pipeline", None, ctx.clone()).await,
4763        );
4764        assert_action_checked(&checker, PIPELINE_DELETE, None);
4765        let app = axum::Router::new()
4766            .route(
4767                "/pipelines/_dryrun",
4768                axum::routing::post(servers::http::event::pipeline_dryrun),
4769            )
4770            .with_state(servers::http::event::LogState {
4771                log_handler: Arc::new(instance.clone()),
4772                log_validator: None,
4773                ingest_interceptor: None,
4774            })
4775            .layer(axum::Extension((*ctx).clone()));
4776        let response = app
4777            .oneshot(
4778                axum::http::Request::post("/pipelines/_dryrun")
4779                    .header("content-type", "application/json")
4780                    .body(axum::body::Body::from("{}"))
4781                    .unwrap(),
4782            )
4783            .await
4784            .unwrap();
4785        assert_eq!(axum::http::StatusCode::FORBIDDEN, response.status());
4786        assert_action_checked(&checker, PIPELINE_QUERY, None);
4787
4788        assert_permission_denied(
4789            DashboardHandler::save(&instance, "dashboard", "{}", ctx.clone()).await,
4790        );
4791        assert_action_checked(&checker, DASHBOARD_SAVE, None);
4792        assert_permission_denied(DashboardHandler::list(&instance, ctx.clone()).await);
4793        assert_action_checked(&checker, DASHBOARD_QUERY, None);
4794        assert_permission_denied(
4795            DashboardHandler::delete(&instance, "dashboard", ctx.clone()).await,
4796        );
4797        assert_action_checked(&checker, DASHBOARD_DELETE, None);
4798
4799        Ok(())
4800    }
4801
4802    #[tokio::test]
4803    async fn test_write_only_ingestion_loads_named_pipeline() -> TestResult<()> {
4804        let plugins = Plugins::new();
4805        plugins.insert::<PermissionCheckerRef>(Arc::new(WriteOnlyPermissionChecker));
4806        let instance = test_instance_with_plugins(
4807            test_table(1024, "source")?,
4808            test_table(1025, "target")?,
4809            plugins,
4810        )
4811        .await?;
4812        instance
4813            .catalog_manager()
4814            .as_any()
4815            .downcast_ref::<catalog::memory::MemoryCatalogManager>()
4816            .unwrap()
4817            .register_table_sync(catalog::RegisterTableRequest {
4818                catalog: "greptime".to_string(),
4819                schema: DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
4820                table_name: "pipelines".to_string(),
4821                table_id: 2049,
4822                table: test_pipeline_table(),
4823            })
4824            .with_context(|_| RegisterTableSnafu {
4825                table_name: "pipelines".to_string(),
4826            })?;
4827        let ctx = test_query_ctx(1);
4828        let handler: PipelineHandlerRef = Arc::new(instance.clone());
4829        let hits = CACHE_HIT.with_label_values(&["pipeline_table"]);
4830        let misses = CACHE_MISS.with_label_values(&["pipeline_table"]);
4831        let before = (hits.get(), misses.get());
4832
4833        handler
4834            .get_pipeline("pipeline", None, ctx.clone())
4835            .await
4836            .unwrap();
4837        assert_eq!((hits.get(), misses.get()), (before.0 + 1, before.1 + 1));
4838        handler
4839            .get_pipeline("pipeline", None, ctx.clone())
4840            .await
4841            .unwrap();
4842        assert_eq!((hits.get(), misses.get()), (before.0 + 3, before.1 + 1));
4843        assert_permission_denied(
4844            PipelineHandler::get_pipeline_str(&instance, "pipeline", None, ctx.clone()).await,
4845        );
4846
4847        let app = axum::Router::new()
4848            .route(
4849                "/pipelines/_dryrun",
4850                axum::routing::post(servers::http::event::pipeline_dryrun),
4851            )
4852            .with_state(servers::http::event::LogState {
4853                log_handler: handler,
4854                log_validator: None,
4855                ingest_interceptor: None,
4856            })
4857            .layer(axum::Extension((*ctx).clone()));
4858        let response = app
4859            .oneshot(
4860                axum::http::Request::post("/pipelines/_dryrun")
4861                    .header("content-type", "application/json")
4862                    .body(axum::body::Body::from("{}"))
4863                    .unwrap(),
4864            )
4865            .await
4866            .unwrap();
4867        assert_eq!(axum::http::StatusCode::FORBIDDEN, response.status());
4868
4869        Ok(())
4870    }
4871
4872    #[tokio::test]
4873    async fn test_copy_export_read_action_has_source_targets() -> TestResult<()> {
4874        let checker = Arc::new(RejectEndpointPermissionChecker::default());
4875        let plugins = Plugins::new();
4876        plugins.insert::<PermissionCheckerRef>(checker.clone());
4877        let instance = test_instance_with_plugins(
4878            test_table(1024, "source")?,
4879            test_physical_table(1025, "target")?,
4880            plugins,
4881        )
4882        .await?;
4883        for (sql, name, physical) in [
4884            ("COPY source TO '/unused.parquet'", "source", false),
4885            (
4886                "COPY (SELECT * FROM source) TO '/unused.parquet'",
4887                "source",
4888                false,
4889            ),
4890            ("COPY target TO '/unused.parquet'", "target", true),
4891        ] {
4892            assert_eq!(
4893                StatusCode::PermissionDenied,
4894                instance
4895                    .check_sql_permission(&parse_one_sql(sql), &QueryContext::arc())
4896                    .await
4897                    .unwrap_err()
4898                    .status_code(),
4899            );
4900            assert_action_checked(
4901                &checker,
4902                COPY_TO,
4903                Some(PermissionTableTargets::resolved(vec![
4904                    PermissionTableTarget::new("greptime", "public", name)
4905                        .with_physical_metric_table(physical),
4906                ])),
4907            );
4908        }
4909        Ok(())
4910    }
4911
4912    #[tokio::test]
4913    async fn test_copy_export_requires_read_and_write_permission() -> TestResult<()> {
4914        use auth::UserProvider;
4915
4916        let plugins = Plugins::new();
4917        plugins.insert::<PermissionCheckerRef>(auth::DefaultPermissionChecker::arc());
4918        let instance = test_instance_with_plugins(
4919            test_table(1024, "source")?,
4920            test_table(1025, "target")?,
4921            plugins,
4922        )
4923        .await?;
4924        let provider = auth::static_user_provider_from_option(
4925            "static_user_provider:cmd:reader:ro=pwd,writer:wo=pwd,owner:rw=pwd",
4926        )
4927        .unwrap();
4928        for (username, can_export, can_import) in [
4929            ("reader", false, false),
4930            ("writer", false, true),
4931            ("owner", true, true),
4932        ] {
4933            let ctx = QueryContext::arc();
4934            ctx.set_current_user(
4935                provider
4936                    .authenticate(
4937                        auth::Identity::UserId(username, None),
4938                        auth::Password::PlainText("pwd".to_string().into()),
4939                    )
4940                    .await
4941                    .unwrap(),
4942            );
4943            for sql in [
4944                "COPY source TO '/unused.parquet'",
4945                "COPY (SELECT * FROM source) TO '/unused.parquet'",
4946            ] {
4947                let result = instance
4948                    .check_sql_permission(&parse_one_sql(sql), &ctx)
4949                    .await;
4950                if can_export {
4951                    result.unwrap();
4952                } else {
4953                    assert_eq!(
4954                        StatusCode::PermissionDenied,
4955                        result.unwrap_err().status_code()
4956                    );
4957                }
4958            }
4959            let result = instance
4960                .check_sql_permission(&parse_one_sql("COPY target FROM '/unused.parquet'"), &ctx)
4961                .await;
4962            if can_import {
4963                result.unwrap();
4964            } else {
4965                assert_eq!(
4966                    StatusCode::PermissionDenied,
4967                    result.unwrap_err().status_code()
4968                );
4969            }
4970        }
4971        Ok(())
4972    }
4973
4974    #[tokio::test]
4975    async fn test_sql_schema_selection_authorizes_before_mutation() -> TestResult<()> {
4976        struct SchemaProvider;
4977        #[async_trait::async_trait]
4978        impl auth::UserProvider for SchemaProvider {
4979            fn name(&self) -> &str {
4980                "schema-test"
4981            }
4982            async fn authenticate(
4983                &self,
4984                _: auth::Identity<'_>,
4985                _: auth::Password<'_>,
4986            ) -> auth::error::Result<UserInfoRef> {
4987                unreachable!("the request already has an authenticated user")
4988            }
4989            async fn authorize(
4990                &self,
4991                _: &str,
4992                schema: &str,
4993                _: &UserInfoRef,
4994            ) -> auth::error::Result<()> {
4995                if schema == "backend_error" {
4996                    return auth::error::InternalStateSnafu {
4997                        msg: "backend unavailable",
4998                    }
4999                    .fail();
5000                }
5001                if matches!(schema, "public" | "allowed" | "allowed_missing" | "admin") {
5002                    Ok(())
5003                } else {
5004                    auth::error::PermissionDeniedSnafu.fail()
5005                }
5006            }
5007        }
5008        let plugins = Plugins::new();
5009        plugins.insert::<auth::UserProviderRef>(Arc::new(SchemaProvider));
5010        let catalog =
5011            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
5012        for schema in ["denied", "allowed", "admin"] {
5013            catalog
5014                .register_schema_sync(catalog::RegisterSchemaRequest {
5015                    catalog: "greptime".to_string(),
5016                    schema: schema.to_string(),
5017                })
5018                .unwrap();
5019        }
5020        let instance = test_instance_with_catalog_manager(
5021            catalog,
5022            test_table(1025, "target")?,
5023            plugins,
5024            None,
5025            Arc::new(NoopProcedureExecutor),
5026        )
5027        .await?;
5028        for sql in [
5029            "Use denied",
5030            " USE denied",
5031            "/* switch */ USE denied",
5032            "USE public; Use denied",
5033            "USE missing",
5034        ] {
5035            let ctx = Arc::new(QueryContext::with_channel(
5036                "greptime",
5037                "public",
5038                Channel::Postgres,
5039            ));
5040            let results = instance.do_query_inner(sql, ctx.clone()).await;
5041            assert_eq!(
5042                StatusCode::PermissionDenied,
5043                results.last().unwrap().as_ref().unwrap_err().status_code(),
5044                "{sql}"
5045            );
5046            assert_eq!("public", ctx.current_schema());
5047        }
5048        for sql in ["USE allowed", "SET search_path TO allowed"] {
5049            let ctx = Arc::new(QueryContext::with_channel(
5050                "greptime",
5051                "public",
5052                Channel::Postgres,
5053            ));
5054            assert!(
5055                instance
5056                    .do_query_inner(sql, ctx.clone())
5057                    .await
5058                    .remove(0)
5059                    .is_ok()
5060            );
5061            assert_eq!("allowed", ctx.current_schema());
5062        }
5063        let ctx = Arc::new(QueryContext::with_channel(
5064            "greptime",
5065            "public",
5066            Channel::Postgres,
5067        ));
5068        let error = instance
5069            .do_query_inner("USE allowed_missing", ctx.clone())
5070            .await
5071            .remove(0)
5072            .unwrap_err();
5073        assert_eq!(StatusCode::InvalidArguments, error.status_code());
5074        assert_eq!("public", ctx.current_schema());
5075        for (sql, expected) in [
5076            ("SET search_path TO denied, public", "public"),
5077            ("SET search_path TO DEFAULT", "admin"),
5078            ("SET search_path TO allowed_missing, allowed", "allowed"),
5079            (
5080                "SET search_path TO denied, allowed_missing, public",
5081                "public",
5082            ),
5083            (r#"SET search_path TO "$user", public"#, "admin"),
5084            (r#"SET "search_path" TO denied, allowed"#, "allowed"),
5085            ("SET SEARCH_PATH TO 'denied'", ""),
5086            ("SET search_path TO allowed_missing", ""),
5087            ("SET search_path TO ''", ""),
5088            ("SET search_path TO allowed; SET search_path TO denied", ""),
5089        ] {
5090            let ctx = Arc::new(QueryContext::with_channel(
5091                "greptime",
5092                "public",
5093                Channel::Postgres,
5094            ));
5095            ctx.set_current_user(Arc::new(AdminUserInfo));
5096            let results = instance.do_query_inner(sql, ctx.clone()).await;
5097            assert!(
5098                results.iter().all(|result| matches!(
5099                    result,
5100                    Ok(Output {
5101                        data: OutputData::AffectedRows(0),
5102                        ..
5103                    })
5104                )),
5105                "{sql}: {results:?}"
5106            );
5107            assert_eq!(expected, ctx.current_schema(), "{sql}");
5108        }
5109
5110        let ctx = Arc::new(QueryContext::with_channel(
5111            "greptime",
5112            "public",
5113            Channel::Postgres,
5114        ));
5115        // The default user's schema is absent or unauthorized, so public remains usable.
5116        assert!(
5117            instance
5118                .do_query_inner(r#"SET search_path TO "$user", public"#, ctx.clone())
5119                .await
5120                .remove(0)
5121                .is_ok()
5122        );
5123        assert_eq!("public", ctx.current_schema());
5124        assert!(
5125            instance
5126                .do_query_inner("SET search_path TO DEFAULT", ctx.clone())
5127                .await
5128                .remove(0)
5129                .is_ok()
5130        );
5131        assert_eq!("public", ctx.current_schema());
5132        let error = instance
5133            .do_query_inner("SET search_path TO backend_error, allowed", ctx.clone())
5134            .await
5135            .remove(0)
5136            .unwrap_err();
5137        assert_eq!(StatusCode::Unexpected, error.status_code());
5138        assert_eq!("public", ctx.current_schema());
5139        Ok(())
5140    }
5141
5142    #[tokio::test]
5143    async fn test_mysql_without_selected_database() -> TestResult<()> {
5144        let plugins = Plugins::new();
5145        plugins.insert::<auth::UserProviderRef>(Arc::new(auth::tests::MockUserProvider::default()));
5146        let instance = test_instance_with_plugins(
5147            test_table(1024, "source")?,
5148            test_table(1025, "target")?,
5149            plugins,
5150        )
5151        .await?;
5152        let ctx = Arc::new(QueryContext::with_channel("greptime", "", Channel::Mysql));
5153        for sql in [
5154            "SELECT * FROM source",
5155            "INSERT INTO source VALUES (1, 0)",
5156            "CREATE TABLE t (ts TIMESTAMP TIME INDEX)",
5157            "SHOW TABLES",
5158            "TRUNCATE TABLE source",
5159            "SHOW CREATE TABLE source",
5160            "COPY source TO '/tmp/out'",
5161            "SELECT flush_table('public.source')",
5162        ] {
5163            let result = instance.do_query_inner(sql, ctx.clone()).await.remove(0);
5164            let error = match result {
5165                Err(error) => Err::<(), _>(BoxedError::new(error))
5166                    .context(servers::error::ExecuteQuerySnafu)
5167                    .unwrap_err(),
5168                Ok(output) => {
5169                    let OutputData::Stream(stream) = output.data else {
5170                        panic!("Expected a query stream: {sql}");
5171                    };
5172                    common_recordbatch::util::collect(stream)
5173                        .await
5174                        .context(servers::error::CollectRecordbatchSnafu)
5175                        .unwrap_err()
5176                }
5177            };
5178            let (kind, message) = servers::mysql::writer::handle_err(error, ctx.clone());
5179            assert_eq!(1046, kind as u16, "{sql}: {message}");
5180            assert!(message.contains("No database selected"), "{message}");
5181        }
5182        let output = instance
5183            .do_query_inner(
5184                "SELECT 1, DATABASE() IS NULL AS no_database, SCHEMA() IS NULL AS no_schema",
5185                ctx.clone(),
5186            )
5187            .await
5188            .remove(0)
5189            .unwrap();
5190        assert_eq!(2, output.data.pretty_print().await.matches("true").count());
5191        for sql in [
5192            "SELECT * FROM denied.source",
5193            "SHOW TABLES FROM denied",
5194            "USE denied",
5195        ] {
5196            let error = instance
5197                .do_query_inner(sql, ctx.clone())
5198                .await
5199                .remove(0)
5200                .unwrap_err();
5201            assert_eq!(
5202                StatusCode::AccessDenied,
5203                error.status_code(),
5204                "{sql}: {error}"
5205            );
5206            assert!(ctx.current_schema().is_empty());
5207        }
5208        for sql in [
5209            "SELECT * FROM public.source",
5210            "SHOW TABLES FROM public",
5211            "SET time_zone = '+00:00'",
5212        ] {
5213            assert!(
5214                instance
5215                    .do_query_inner(sql, ctx.clone())
5216                    .await
5217                    .remove(0)
5218                    .is_ok(),
5219                "{sql}"
5220            );
5221        }
5222        let plan = instance
5223            .do_describe_inner(parse_one_sql("SELECT * FROM public.source"), ctx.clone())
5224            .await
5225            .unwrap()
5226            .unwrap()
5227            .logical_plan;
5228        instance
5229            .do_exec_plan_inner(
5230                plan.clone(),
5231                Some(parse_one_sql("SELECT * FROM public.source")),
5232                ctx.clone(),
5233            )
5234            .await
5235            .unwrap();
5236        let error = instance
5237            .do_describe_inner(parse_one_sql("SELECT * FROM denied.source"), ctx.clone())
5238            .await
5239            .unwrap_err();
5240        assert_eq!(StatusCode::AccessDenied, error.status_code());
5241        assert!(ctx.current_schema().is_empty());
5242        let error = instance
5243            .do_exec_plan_inner(plan.clone(), None, ctx.clone())
5244            .await
5245            .unwrap_err();
5246        assert_eq!(StatusCode::DatabaseNotFound, error.status_code());
5247        let current_user = ctx.current_user();
5248        ctx.set_current_user(Arc::new(AdminUserInfo));
5249        let error = instance
5250            .do_exec_plan_inner(
5251                plan,
5252                Some(parse_one_sql("SELECT * FROM public.source")),
5253                ctx.clone(),
5254            )
5255            .await
5256            .unwrap_err();
5257        assert_eq!(StatusCode::AccessDenied, error.status_code());
5258        ctx.set_current_user(current_user);
5259        instance
5260            .do_query_inner("USE public", ctx.clone())
5261            .await
5262            .remove(0)
5263            .unwrap();
5264        assert_eq!("public", ctx.current_schema());
5265        instance
5266            .do_query_inner("SELECT * FROM source", ctx)
5267            .await
5268            .remove(0)
5269            .unwrap();
5270        Ok(())
5271    }
5272
5273    #[tokio::test]
5274    async fn test_empty_search_path_statements() -> TestResult<()> {
5275        let instance = test_instance_with_plugins(
5276            test_table(1024, "source")?,
5277            test_table(1025, "target")?,
5278            Plugins::new(),
5279        )
5280        .await?;
5281        let ctx = Arc::new(QueryContext::with_channel(
5282            "greptime",
5283            "public",
5284            Channel::Postgres,
5285        ));
5286        instance
5287            .do_query_inner("SET search_path TO ''", ctx.clone())
5288            .await
5289            .remove(0)
5290            .unwrap();
5291        let tables = instance
5292            .do_query_inner("SHOW TABLES", ctx.clone())
5293            .await
5294            .remove(0)
5295            .unwrap()
5296            .data
5297            .pretty_print()
5298            .await;
5299        assert!(
5300            !tables.contains("source") && !tables.contains("target"),
5301            "{tables}"
5302        );
5303        let error = instance
5304            .do_query_inner("INSERT INTO source VALUES (1, 0)", ctx.clone())
5305            .await
5306            .remove(0)
5307            .unwrap_err();
5308        assert!(
5309            matches!(error, Error::TableOperation { source: operator::error::Error::TableNotFound { ref table_name, .. }, .. } if table_name == "greptime..source"),
5310            "{error:?}"
5311        );
5312        for sql in [
5313            "CREATE TABLE no_schema (ts TIMESTAMP TIME INDEX)",
5314            "ALTER TABLE source ADD COLUMN no_schema_column INT",
5315            "CREATE VIEW no_schema_view AS SELECT 1 AS n",
5316            "CREATE FLOW no_schema_flow SINK TO sink AS SELECT * FROM public.source",
5317            "CREATE FLOW no_schema_flow SINK TO public.sink AS SELECT * FROM source",
5318        ] {
5319            let error = instance
5320                .do_query_inner(sql, ctx.clone())
5321                .await
5322                .remove(0)
5323                .unwrap_err();
5324            assert!(
5325                matches!(error, Error::TableOperation { source: operator::error::Error::SchemaNotFound { ref schema_info, .. }, .. } if schema_info.is_empty()),
5326                "{sql}: {error:?}"
5327            );
5328        }
5329
5330        for sql in ["SELECT * FROM source", "DELETE FROM source"] {
5331            assert!(
5332                instance
5333                    .do_query_inner(sql, ctx.clone())
5334                    .await
5335                    .remove(0)
5336                    .is_err(),
5337                "{sql}"
5338            );
5339        }
5340        let output = instance
5341            .do_query_inner(
5342                "SELECT current_schema() IS NULL AS empty, current_schemas(false) AS schemas",
5343                ctx.clone(),
5344            )
5345            .await
5346            .remove(0)
5347            .unwrap();
5348        let printed = output.data.pretty_print().await;
5349        assert!(
5350            printed.contains("true") && printed.contains("[]"),
5351            "{printed}"
5352        );
5353        let output = instance
5354            .do_query_inner("DROP TABLE IF EXISTS source", ctx.clone())
5355            .await
5356            .remove(0)
5357            .unwrap();
5358        assert!(matches!(output.data, OutputData::AffectedRows(0)));
5359        instance
5360            .do_query_inner("USE public", ctx.clone())
5361            .await
5362            .remove(0)
5363            .unwrap();
5364        assert!(
5365            instance
5366                .do_query_inner("SELECT * FROM source", ctx)
5367                .await
5368                .remove(0)
5369                .is_ok()
5370        );
5371        Ok(())
5372    }
5373
5374    #[tokio::test]
5375    async fn test_operator_rejects_search_path_without_frontend() -> TestResult<()> {
5376        let instance = test_instance_with_plugins(
5377            test_table(1024, "source")?,
5378            test_table(1025, "target")?,
5379            Plugins::new(),
5380        )
5381        .await?;
5382        let ctx = Arc::new(QueryContext::with_channel(
5383            "greptime",
5384            "public",
5385            Channel::Postgres,
5386        ));
5387        let error = instance
5388            .statement_executor
5389            .execute_sql(parse_one_sql("SET search_path TO denied"), ctx.clone())
5390            .await
5391            .unwrap_err();
5392        assert!(matches!(error, operator::error::Error::NotSupported { .. }));
5393        assert_eq!("public", ctx.current_schema());
5394        Ok(())
5395    }
5396
5397    #[tokio::test]
5398    async fn test_write_only_grpc_sql_is_checked_after_parsing() -> TestResult<()> {
5399        let plugins = Plugins::new();
5400        plugins.insert::<PermissionCheckerRef>(Arc::new(WriteOnlyPermissionChecker));
5401        let instance = test_instance_with_plugins(
5402            test_table(1024, "source")?,
5403            test_table(1025, "target")?,
5404            plugins,
5405        )
5406        .await?;
5407
5408        let insert = Request::Query(api::v1::QueryRequest {
5409            query: Some(Query::Sql(
5410                "INSERT INTO target SELECT * FROM source".to_string(),
5411            )),
5412        });
5413        servers::query_handler::grpc::GrpcQueryHandler::do_query(
5414            &instance,
5415            insert,
5416            QueryContext::arc(),
5417        )
5418        .await
5419        .unwrap();
5420
5421        let select = Request::Query(api::v1::QueryRequest {
5422            query: Some(Query::Sql("SELECT * FROM source".to_string())),
5423        });
5424        assert_permission_denied(
5425            servers::query_handler::grpc::GrpcQueryHandler::do_query(
5426                &instance,
5427                select,
5428                QueryContext::arc(),
5429            )
5430            .await,
5431        );
5432
5433        Ok(())
5434    }
5435
5436    #[tokio::test]
5437    async fn test_target_independent_checker_skips_target_resolution() -> TestResult<()> {
5438        let physical_table = "physical_metric";
5439        let checker = Arc::new(TargetIndependentPermissionChecker::default());
5440        let plugins = Plugins::new();
5441        plugins.insert::<PermissionCheckerRef>(checker.clone());
5442        let catalog = catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(
5443            1024,
5444            physical_table,
5445        )?);
5446        catalog
5447            .register_table_sync(catalog::RegisterTableRequest {
5448                catalog: "greptime".to_string(),
5449                schema: "public".to_string(),
5450                table_name: "target".to_string(),
5451                table_id: 1025,
5452                table: test_table(1025, "target")?,
5453            })
5454            .with_context(|_| RegisterTableSnafu {
5455                table_name: "target".to_string(),
5456            })?;
5457        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
5458        let instance =
5459            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
5460        counting_catalog.reset_counts();
5461
5462        let ctx = test_query_ctx(1);
5463        let physical_target = PermissionTableTarget::new("greptime", "public", physical_table);
5464        instance
5465            .check_resolved_table_permission(
5466                &ctx,
5467                PermissionReq::Action(PROMQL_QUERY),
5468                PermissionTableTargets::resolved(vec![physical_target]),
5469            )
5470            .await
5471            .unwrap();
5472        assert_eq!(0, counting_catalog.total_table_lookups());
5473        assert_eq!(1, checker.checks.load(atomic::Ordering::Relaxed));
5474        assert_eq!(
5475            vec![physical_table.to_string(), "target".to_string()],
5476            PrometheusHandler::filter_metadata_metric_names(
5477                &instance,
5478                vec![physical_table.to_string(), "target".to_string()],
5479                "public",
5480                &ctx,
5481            )
5482            .await
5483            .unwrap()
5484        );
5485        assert_eq!(0, counting_catalog.total_table_lookups());
5486        assert_eq!(2, checker.checks.load(atomic::Ordering::Relaxed));
5487
5488        Ok(())
5489    }
5490
5491    #[tokio::test]
5492    async fn test_query_permission_targets_are_deduplicated() -> TestResult<()> {
5493        struct RecordingTargetChecker(std::sync::Mutex<Vec<PermissionTableTargets>>);
5494        impl PermissionChecker for RecordingTargetChecker {
5495            fn check_permission(
5496                &self,
5497                _: UserInfoRef,
5498                _: PermissionReq,
5499            ) -> auth::error::Result<PermissionResp> {
5500                Ok(PermissionResp::Allow)
5501            }
5502
5503            fn check_permission_with_table_targets(
5504                &self,
5505                _: UserInfoRef,
5506                _: PermissionReq,
5507                targets: PermissionTableTargets,
5508                _: Option<&str>,
5509            ) -> auth::error::Result<PermissionResp> {
5510                self.0.lock().unwrap().push(targets);
5511                Ok(PermissionResp::Allow)
5512            }
5513        }
5514
5515        let checker = Arc::new(RecordingTargetChecker(Default::default()));
5516        let plugins = Plugins::new();
5517        plugins.insert::<PermissionCheckerRef>(checker.clone());
5518        let catalog =
5519            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
5520        catalog
5521            .register_table_sync(catalog::RegisterTableRequest {
5522                catalog: "greptime".to_string(),
5523                schema: "public".to_string(),
5524                table_name: "target".to_string(),
5525                table_id: 1025,
5526                table: test_table(1025, "target")?,
5527            })
5528            .with_context(|_| RegisterTableSnafu {
5529                table_name: "target".to_string(),
5530            })?;
5531        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
5532        let instance =
5533            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
5534        counting_catalog.reset_counts();
5535        let ctx = test_query_ctx(1);
5536        let target = PermissionTableTarget::new("greptime", "public", "target");
5537
5538        instance
5539            .check_resolved_table_permission(
5540                &ctx,
5541                PermissionReq::Action(PROMQL_QUERY),
5542                PermissionTableTargets::resolved(vec![target.clone(), target.clone()]),
5543            )
5544            .await
5545            .unwrap();
5546        assert_eq!(1, counting_catalog.table_calls());
5547        assert_eq!(0, counting_catalog.table_id_calls());
5548        assert_eq!(0, counting_catalog.table_info_by_id_calls());
5549        assert_eq!(
5550            *checker.0.lock().unwrap(),
5551            vec![PermissionTableTargets::Resolved(vec![target])]
5552        );
5553
5554        counting_catalog.reset_counts();
5555        instance
5556            .check_sql_permission(&parse_one_sql("COPY target TO '/unused.parquet'"), &ctx)
5557            .await
5558            .unwrap();
5559        assert_eq!(1, counting_catalog.total_table_lookups());
5560        assert_eq!(3, checker.0.lock().unwrap().len());
5561
5562        Ok(())
5563    }
5564
5565    #[tokio::test]
5566    async fn test_physical_target_permission_reaches_checker() -> TestResult<()> {
5567        struct PhysicalChecker {
5568            allow: bool,
5569        }
5570        impl PermissionChecker for PhysicalChecker {
5571            fn check_permission(
5572                &self,
5573                _: UserInfoRef,
5574                _: PermissionReq,
5575            ) -> auth::error::Result<PermissionResp> {
5576                Ok(PermissionResp::Allow)
5577            }
5578
5579            fn grpc_table_targets(
5580                &self,
5581                request: &api::v1::greptime_request::Request,
5582                catalog: &str,
5583                schema: &str,
5584            ) -> PermissionTableTargets {
5585                let api::v1::greptime_request::Request::Ddl(ddl) = request else {
5586                    panic!("expected DDL")
5587                };
5588                let Some(api::v1::ddl_request::Expr::CommentOn(comment)) = &ddl.expr else {
5589                    panic!("expected comment")
5590                };
5591                PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
5592                    catalog,
5593                    schema,
5594                    &comment.object_name,
5595                )])
5596            }
5597
5598            fn check_permission_with_table_targets(
5599                &self,
5600                _: UserInfoRef,
5601                _: PermissionReq,
5602                targets: PermissionTableTargets,
5603                _: Option<&str>,
5604            ) -> auth::error::Result<PermissionResp> {
5605                let PermissionTableTargets::Resolved(targets) = targets else {
5606                    panic!("physical target must retain its identity")
5607                };
5608                assert_eq!(targets.len(), 1);
5609                assert_eq!(targets[0].catalog, "greptime");
5610                assert_eq!(targets[0].schema, "public");
5611                assert_eq!(targets[0].table, "physical_metric");
5612                assert!(targets[0].is_physical_metric_table);
5613                Ok(if self.allow {
5614                    PermissionResp::Allow
5615                } else {
5616                    PermissionResp::Reject
5617                })
5618            }
5619        }
5620        for allow in [true, false] {
5621            let plugins = Plugins::new();
5622            plugins.insert::<PermissionCheckerRef>(Arc::new(PhysicalChecker { allow }));
5623            let instance = test_instance_with_plugins(
5624                test_physical_table(1024, "physical_metric")?,
5625                test_table(1025, "target")?,
5626                plugins,
5627            )
5628            .await?;
5629            let ctx = test_query_ctx(1);
5630            for sql in [
5631                "SHOW CREATE TABLE physical_metric",
5632                "SELECT * FROM physical_metric",
5633            ] {
5634                let result = instance
5635                    .check_sql_permission(&parse_one_sql(sql), &ctx)
5636                    .await;
5637                assert_eq!(allow, result.is_ok());
5638                if let Err(error) = result {
5639                    assert_eq!(StatusCode::PermissionDenied, error.status_code());
5640                }
5641            }
5642            if !allow {
5643                let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
5644                    expr: Some(api::v1::ddl_request::Expr::CommentOn(
5645                        api::v1::CommentOnExpr {
5646                            object_name: "physical_metric".to_string(),
5647                            object_type: api::v1::CommentObjectType::Table as i32,
5648                            ..Default::default()
5649                        },
5650                    )),
5651                });
5652                let err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
5653                    &instance, request, ctx,
5654                )
5655                .await
5656                .unwrap_err();
5657                assert_eq!(StatusCode::PermissionDenied, err.status_code());
5658            }
5659        }
5660        Ok(())
5661    }
5662
5663    #[tokio::test]
5664    async fn test_physical_query_targets_fail_closed() -> TestResult<()> {
5665        let physical_table = "physical_metric";
5666        let plugins = Plugins::new();
5667        plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
5668        let instance = test_instance_with_plugins(
5669            test_physical_table(1024, physical_table)?,
5670            test_table(1025, "target")?,
5671            plugins,
5672        )
5673        .await?;
5674
5675        let ctx = test_query_ctx(1);
5676        let logical_target = PermissionTableTarget::new("greptime", "public", "target");
5677        instance
5678            .check_resolved_table_permission(
5679                &ctx,
5680                PermissionReq::Action(PROMQL_QUERY),
5681                PermissionTableTargets::resolved(vec![logical_target.clone()]),
5682            )
5683            .await
5684            .unwrap();
5685        let physical_target = PermissionTableTarget::new("greptime", "public", physical_table)
5686            .with_physical_metric_table(true);
5687        let err = instance
5688            .check_resolved_table_permission(
5689                &ctx,
5690                PermissionReq::Action(PROMQL_QUERY),
5691                PermissionTableTargets::resolved(vec![
5692                    logical_target,
5693                    PermissionTableTarget::new("greptime", "public", physical_table),
5694                ]),
5695            )
5696            .await
5697            .unwrap_err();
5698        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5699        assert_eq!(
5700            vec!["target".to_string()],
5701            PrometheusHandler::filter_metadata_metric_names(
5702                &instance,
5703                vec!["target".to_string(), "denied".to_string()],
5704                "public",
5705                &ctx,
5706            )
5707            .await
5708            .unwrap()
5709        );
5710
5711        let query = PromQuery {
5712            query: physical_table.to_string(),
5713            ..Default::default()
5714        };
5715        let err = PrometheusHandler::check_query_target_permission(
5716            &instance,
5717            PermissionTableTargets::resolved(vec![physical_target]),
5718            &ctx,
5719        )
5720        .await
5721        .unwrap_err();
5722        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5723        let err = PrometheusHandler::check_query_permission(
5724            &instance,
5725            std::slice::from_ref(&query),
5726            &ctx,
5727        )
5728        .await
5729        .unwrap_err();
5730        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5731        let err = PrometheusHandler::do_query(&instance, &query, ctx.clone())
5732            .await
5733            .unwrap_err();
5734        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5735
5736        for sql in [
5737            "SELECT * FROM physical_metric",
5738            "TQL EVAL (0, 10, '5s') physical_metric",
5739            "INSERT INTO target SELECT * FROM physical_metric",
5740        ] {
5741            let mut results = instance.do_query_inner(sql, ctx.clone()).await;
5742            assert_eq!(1, results.len(), "{sql}");
5743            let err = results.remove(0).unwrap_err();
5744            assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{sql}");
5745        }
5746        let err = LogQueryHandler::query(
5747            &instance,
5748            LogQuery {
5749                table: TableName::new("greptime", "public", physical_table),
5750                ..Default::default()
5751            },
5752            ctx.clone(),
5753        )
5754        .await
5755        .unwrap_err();
5756        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5757        let err = instance
5758            .do_describe_inner(parse_one_sql("SELECT * FROM physical_metric"), ctx.clone())
5759            .await
5760            .unwrap_err();
5761        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5762
5763        let request = ReadRequest {
5764            queries: vec![RemoteQuery {
5765                matchers: vec![LabelMatcher {
5766                    r#type: PromMatcherType::Eq as i32,
5767                    name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
5768                    value: physical_table.to_string(),
5769                }],
5770                ..Default::default()
5771            }],
5772            ..Default::default()
5773        };
5774        let Err(err) = PromStoreProtocolHandler::read(&instance, request, ctx.clone()).await else {
5775            panic!("physical remote-read target must be rejected");
5776        };
5777        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5778
5779        let err = PrometheusHandler::query_label_values(
5780            &instance,
5781            physical_table.to_string(),
5782            "host".to_string(),
5783            vec![],
5784            SystemTime::UNIX_EPOCH,
5785            SystemTime::UNIX_EPOCH,
5786            &ctx,
5787        )
5788        .await
5789        .unwrap_err();
5790        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5791
5792        Ok(())
5793    }
5794
5795    #[tokio::test]
5796    async fn test_non_exact_query_discovery_keeps_denied_targets_for_batch_check() -> TestResult<()>
5797    {
5798        let plugins = Plugins::new();
5799        plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
5800        let instance = test_instance_with_plugins_and_metric_names(
5801            test_logical_table(1024, "denied")?,
5802            test_logical_table(1025, "target")?,
5803            plugins,
5804            Some(test_metric_names_table()),
5805        )
5806        .await?;
5807        let ctx = test_query_ctx(1);
5808
5809        let mut metric_names = PrometheusHandler::query_metric_names(
5810            &instance,
5811            vec![Matcher::new(
5812                promql_parser::label::MatchOp::NotEqual,
5813                "__name__",
5814                "",
5815            )],
5816            "public",
5817            &ctx,
5818        )
5819        .await
5820        .unwrap();
5821        metric_names.sort_unstable();
5822        assert_eq!(
5823            vec!["denied".to_string(), "target".to_string()],
5824            metric_names
5825        );
5826
5827        let queries = metric_names
5828            .into_iter()
5829            .map(|query| PromQuery {
5830                query,
5831                ..Default::default()
5832            })
5833            .collect::<Vec<_>>();
5834        let err = PrometheusHandler::check_query_permission(&instance, &queries, &ctx)
5835            .await
5836            .unwrap_err();
5837        assert_eq!(StatusCode::PermissionDenied, err.status_code());
5838
5839        Ok(())
5840    }
5841
5842    /// `info` reads `target_info` without naming it. With a label selector the query used to be
5843    /// answered as a discovery over the tables the caller may read, which never named it either.
5844    #[tokio::test]
5845    async fn test_info_query_checks_the_info_table() -> TestResult<()> {
5846        struct DenyInfoTable;
5847
5848        impl PermissionChecker for DenyInfoTable {
5849            fn check_permission(
5850                &self,
5851                _user_info: UserInfoRef,
5852                _req: PermissionReq,
5853            ) -> auth::error::Result<PermissionResp> {
5854                Ok(PermissionResp::Allow)
5855            }
5856
5857            fn check_permission_with_table_targets(
5858                &self,
5859                _user_info: UserInfoRef,
5860                _req: PermissionReq,
5861                targets: PermissionTableTargets,
5862                _current_schema: Option<&str>,
5863            ) -> auth::error::Result<PermissionResp> {
5864                let reject = match targets {
5865                    PermissionTableTargets::Unresolved => true,
5866                    PermissionTableTargets::Resolved(targets) => {
5867                        targets.iter().any(|target| target.table == "target_info")
5868                    }
5869                };
5870                Ok(if reject {
5871                    PermissionResp::Reject
5872                } else {
5873                    PermissionResp::Allow
5874                })
5875            }
5876        }
5877
5878        let plugins = Plugins::new();
5879        plugins.insert::<PermissionCheckerRef>(Arc::new(DenyInfoTable));
5880        let instance = test_instance_with_plugins_and_metric_names(
5881            test_logical_table(1024, "target_info")?,
5882            test_logical_table(1025, "target")?,
5883            plugins,
5884            None,
5885        )
5886        .await?;
5887        let ctx = Arc::new(
5888            QueryContextBuilder::default()
5889                .channel(Channel::Mysql)
5890                .conn_info(ConnInfo::new(None, Channel::Mysql))
5891                .extensions(HashMap::from([(
5892                    query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY.to_string(),
5893                    "true".to_string(),
5894                )]))
5895                .build(),
5896        );
5897
5898        for promql in [
5899            "info(target)",
5900            r#"info(target, {version="v1"})"#,
5901            // Not a shape that reads `target_info`, and not a discovery either: unresolved.
5902            r#"info(target, {__schema__="public", version="v1"})"#,
5903        ] {
5904            let query = PromQuery {
5905                query: promql.to_string(),
5906                ..Default::default()
5907            };
5908            let err = PrometheusHandler::do_query(&instance, &query, ctx.clone())
5909                .await
5910                .unwrap_err();
5911            assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{promql}");
5912        }
5913
5914        Ok(())
5915    }
5916
5917    #[test]
5918    fn test_should_track_statement_process() {
5919        assert!(should_track_statement_process(&parse_one_sql(
5920            "SELECT * FROM demo"
5921        )));
5922        assert!(should_track_statement_process(&parse_one_sql(
5923            "INSERT INTO demo SELECT * FROM source"
5924        )));
5925        assert!(!should_track_statement_process(&parse_one_sql(
5926            "INSERT INTO demo VALUES (1)"
5927        )));
5928        assert!(!should_track_statement_process(&parse_one_sql(
5929            "INSERT INTO demo VALUES (now())"
5930        )));
5931    }
5932
5933    #[test]
5934    fn test_should_track_plan_process() {
5935        let select_stmt = parse_one_sql("SELECT * FROM demo");
5936        let insert_select_stmt = parse_one_sql("INSERT INTO demo SELECT * FROM source");
5937        let insert_values_stmt = parse_one_sql("INSERT INTO demo VALUES (now())");
5938
5939        let empty_plan = LogicalPlanBuilder::empty(false).build().unwrap();
5940        assert!(should_track_plan_process(Some(&select_stmt), &empty_plan));
5941        assert!(should_track_plan_process(
5942            Some(&insert_select_stmt),
5943            &insert_dml_plan()
5944        ));
5945        assert!(!should_track_plan_process(
5946            Some(&insert_values_stmt),
5947            &insert_dml_plan()
5948        ));
5949        assert!(!should_track_plan_process(None, &insert_dml_plan()));
5950    }
5951
5952    #[tokio::test]
5953    async fn test_exemplar_slow_query() -> TestResult<()> {
5954        use common_catalog::consts::METRICS_EXEMPLARS_TABLE;
5955        use servers::exemplar::query::Query as ExemplarQuery;
5956
5957        for invalid_destination in [false, true] {
5958            let table_name = if invalid_destination {
5959                METRICS_EXEMPLARS_TABLE
5960            } else {
5961                "source"
5962            };
5963            let mut instance = test_instance_with_tables(
5964                test_table(1024, table_name)?,
5965                test_table(1025, "target")?,
5966            )
5967            .await?;
5968            let recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
5969            instance.slow_query_recorder = recorder.clone();
5970            instance.slow_query_options.sample_ratio = 1.0;
5971            instance.slow_query_options.record_type = SlowQueriesRecordType::SystemTable;
5972
5973            for (enabled, threshold, should_record) in [
5974                (true, Duration::ZERO, true),
5975                (false, Duration::ZERO, false),
5976                (true, Duration::from_secs(3600), false),
5977            ] {
5978                instance.slow_query_options.enable = enabled;
5979                instance.slow_query_options.threshold = threshold;
5980                let query =
5981                    ExemplarQuery::parse("source".into(), "-0.001", "0.001", "public").unwrap();
5982                let result = instance.query_exemplars(query, QueryContext::arc()).await;
5983                if invalid_destination {
5984                    assert!(result.is_err());
5985                } else {
5986                    assert!(result.unwrap().is_empty());
5987                }
5988
5989                let queries = std::mem::take(&mut *recorder.queries.lock().unwrap());
5990                let expected = if should_record {
5991                    vec!["query_exemplars(source, start_ns=-1000000, end_ns=1999999)"]
5992                } else {
5993                    vec![]
5994                };
5995                assert_eq!(
5996                    queries, expected,
5997                    "invalid_destination={invalid_destination}, enabled={enabled}, threshold={threshold:?}"
5998                );
5999            }
6000        }
6001        Ok(())
6002    }
6003
6004    #[tokio::test]
6005    async fn test_insert_select_slow_query() -> TestResult<()> {
6006        let mut instance =
6007            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
6008                .await?;
6009        let recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
6010        instance.slow_query_recorder = recorder.clone();
6011        let sql = "INSERT INTO target SELECT * FROM source";
6012
6013        for prepared in [false, true] {
6014            for (enabled, threshold, should_record) in [
6015                (true, Duration::ZERO, true),
6016                (false, Duration::ZERO, false),
6017                (true, Duration::from_secs(3600), false),
6018            ] {
6019                instance.slow_query_options.enable = enabled;
6020                instance.slow_query_options.threshold = threshold;
6021                let query_ctx = test_query_ctx(42);
6022                let output = if prepared {
6023                    let stmt = parse_one_sql(sql);
6024                    let described = instance
6025                        .do_describe_inner(stmt.clone(), query_ctx.clone())
6026                        .await
6027                        .unwrap()
6028                        .unwrap();
6029                    instance
6030                        .do_exec_plan_inner(described.logical_plan, Some(stmt), query_ctx)
6031                        .await
6032                        .unwrap()
6033                } else {
6034                    execute_one_sql(&instance, sql, query_ctx).await?
6035                };
6036                assert!(matches!(output.data, OutputData::AffectedRows(0)));
6037
6038                let queries = std::mem::take(&mut *recorder.queries.lock().unwrap());
6039                let expected = if should_record { vec![sql] } else { vec![] };
6040                assert_eq!(
6041                    queries, expected,
6042                    "prepared={prepared}, enabled={enabled}, threshold={threshold:?}"
6043                );
6044            }
6045        }
6046
6047        Ok(())
6048    }
6049
6050    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6051    async fn test_insert_select_is_visible_in_show_processlist() -> TestResult<()> {
6052        let insert_sql = "INSERT INTO target SELECT * FROM source";
6053        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
6054        let (finish_tx, finish_rx) = oneshot::channel();
6055        let interceptor = Arc::new(BlockingInsertSelectInterceptor::new(started_tx, finish_rx));
6056        let instance = Arc::new(test_instance_with_insert_select_interceptor(interceptor).await?);
6057
6058        let insert_task = tokio::spawn({
6059            let instance = instance.clone();
6060            async move { execute_one_sql(&instance, insert_sql, test_query_ctx(4242)).await }
6061        });
6062
6063        tokio::time::timeout(Duration::from_secs(5), started_rx.recv())
6064            .await
6065            .context(InsertStartTimeoutSnafu)?
6066            .context(InsertStartChannelClosedSnafu)?;
6067
6068        let output = execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
6069        let process_list = output.data.pretty_print().await;
6070        assert!(
6071            process_list.contains(insert_sql),
6072            "process list did not contain running insert:\n{process_list}"
6073        );
6074
6075        finish_tx
6076            .send(())
6077            .map_err(|_| ReleaseBlockedInsertSnafu.build())?;
6078        insert_task.await.context(InsertTaskPanicSnafu)??;
6079
6080        Ok(())
6081    }
6082
6083    #[tokio::test]
6084    async fn test_show_processlist_catalog_scope() -> TestResult<()> {
6085        let instance =
6086            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
6087                .await?;
6088        let _current_catalog = instance.process_manager().register_query(
6089            "greptime".to_string(),
6090            vec!["public".to_string()],
6091            "current_catalog_query".to_string(),
6092            String::new(),
6093            None,
6094            None,
6095        );
6096        let _other_catalog = instance.process_manager().register_query(
6097            "other".to_string(),
6098            vec!["public".to_string()],
6099            "other_catalog_query".to_string(),
6100            String::new(),
6101            None,
6102            None,
6103        );
6104
6105        for sql in ["SHOW PROCESSLIST", "SHOW FULL PROCESSLIST"] {
6106            let output = execute_one_sql(&instance, sql, test_query_ctx(43)).await?;
6107            let process_list = output.data.pretty_print().await;
6108            assert!(
6109                process_list.contains("current_catalog_query"),
6110                "{process_list}"
6111            );
6112            assert!(
6113                !process_list.contains("other_catalog_query"),
6114                "{process_list}"
6115            );
6116
6117            let admin_ctx = test_query_ctx(44);
6118            admin_ctx.set_current_user(Arc::new(AdminUserInfo));
6119            let output = execute_one_sql(&instance, sql, admin_ctx).await?;
6120            let process_list = output.data.pretty_print().await;
6121            assert!(
6122                process_list.contains("current_catalog_query"),
6123                "{process_list}"
6124            );
6125            assert!(
6126                process_list.contains("other_catalog_query"),
6127                "{process_list}"
6128            );
6129        }
6130
6131        Ok(())
6132    }
6133
6134    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6135    async fn test_kill_query_cancels_insert_select() -> TestResult<()> {
6136        assert_kill_cancels_insert_select("KILL QUERY 4242").await
6137    }
6138
6139    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6140    async fn test_kill_process_id_cancels_insert_select() -> TestResult<()> {
6141        assert_kill_cancels_insert_select("KILL 'test-frontend/4242'").await
6142    }
6143
6144    async fn assert_kill_cancels_insert_select(kill_sql: &str) -> TestResult<()> {
6145        let insert_sql = "INSERT INTO target SELECT * FROM source";
6146        let (source_polled_tx, source_polled_rx) = oneshot::channel();
6147        let instance = Arc::new(
6148            test_instance_with_tables(
6149                pending_table(1024, "source", source_polled_tx)?,
6150                test_table(1025, "target")?,
6151            )
6152            .await?,
6153        );
6154
6155        let insert_task = tokio::spawn({
6156            let instance = instance.clone();
6157            async move { execute_one_sql(&instance, insert_sql, test_query_ctx(4242)).await }
6158        });
6159
6160        tokio::time::timeout(Duration::from_secs(5), source_polled_rx)
6161            .await
6162            .context(SourcePollTimeoutSnafu)?
6163            .context(SourcePollChannelClosedSnafu)?;
6164
6165        let output = execute_one_sql(&instance, kill_sql, test_query_ctx(43)).await?;
6166        assert!(matches!(output.data, OutputData::AffectedRows(1)));
6167
6168        let insert_result = tokio::time::timeout(Duration::from_secs(5), insert_task)
6169            .await
6170            .context(InsertTaskTimeoutSnafu)?
6171            .context(InsertTaskPanicSnafu)?;
6172        let err = match insert_result {
6173            Ok(_) => return InsertSelectNotCancelledSnafu.fail(),
6174            Err(TestError::ExecuteSql { source, .. }) => source,
6175            Err(err) => return Err(err),
6176        };
6177        assert_eq!(StatusCode::Cancelled, err.status_code());
6178
6179        let output = execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
6180        let process_list = output.data.pretty_print().await;
6181        assert!(
6182            !process_list.contains(insert_sql),
6183            "process list still contains killed insert:\n{process_list}"
6184        );
6185
6186        Ok(())
6187    }
6188
6189    fn insert_dml_plan() -> LogicalPlan {
6190        let schema = SchemaRef::new(Schema::new(vec![Field::new(
6191            "value",
6192            DataType::Int64,
6193            true,
6194        )]));
6195        let target = Arc::new(LogicalTableSource::new(schema));
6196        let input = LogicalPlanBuilder::empty(false).build().unwrap();
6197
6198        LogicalPlanBuilder::insert_into(input, "demo", target, InsertOp::Append)
6199            .unwrap()
6200            .build()
6201            .unwrap()
6202    }
6203
6204    #[test]
6205    fn test_exec_validation() {
6206        let query_ctx = QueryContext::arc();
6207        let plugins: Plugins = Plugins::new();
6208        plugins.insert(QueryOptions {
6209            disallow_cross_catalog_query: true,
6210        });
6211
6212        let sql = r#"
6213        SELECT * FROM demo;
6214        EXPLAIN SELECT * FROM demo;
6215        CREATE DATABASE test_database;
6216        SHOW DATABASES;
6217        "#;
6218        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
6219        assert_eq!(stmts.len(), 4);
6220        for stmt in stmts {
6221            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
6222            re.unwrap();
6223        }
6224
6225        let sql = r#"
6226        SHOW CREATE TABLE demo;
6227        ALTER TABLE demo ADD COLUMN new_col INT;
6228        "#;
6229        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
6230        assert_eq!(stmts.len(), 2);
6231        for stmt in stmts {
6232            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
6233            re.unwrap();
6234        }
6235
6236        fn replace_test(template_sql: &str, plugins: Plugins, query_ctx: &QueryContextRef) {
6237            // test right
6238            let right = vec![("", ""), ("", "public."), ("greptime.", "public.")];
6239            for (catalog, schema) in right {
6240                let sql = do_fmt(template_sql, catalog, schema);
6241                do_test(&sql, plugins.clone(), query_ctx, true);
6242            }
6243
6244            let wrong = vec![
6245                ("wrongcatalog.", "public."),
6246                ("wrongcatalog.", "wrongschema."),
6247            ];
6248            for (catalog, schema) in wrong {
6249                let sql = do_fmt(template_sql, catalog, schema);
6250                do_test(&sql, plugins.clone(), query_ctx, false);
6251            }
6252        }
6253
6254        fn do_fmt(template: &str, catalog: &str, schema: &str) -> String {
6255            let vars = HashMap::from([
6256                ("catalog".to_string(), catalog),
6257                ("schema".to_string(), schema),
6258            ]);
6259            template.format(&vars).unwrap()
6260        }
6261
6262        fn do_test(sql: &str, plugins: Plugins, query_ctx: &QueryContextRef, is_ok: bool) {
6263            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
6264            let re = check_permission(plugins, stmt, query_ctx);
6265            if is_ok {
6266                re.unwrap();
6267            } else {
6268                assert!(re.is_err());
6269            }
6270        }
6271
6272        // test insert
6273        let sql = "INSERT INTO {catalog}{schema}monitor(host) VALUES ('host1');";
6274        replace_test(sql, plugins.clone(), &query_ctx);
6275
6276        // test create table
6277        let sql = r#"CREATE TABLE {catalog}{schema}demo(
6278                            host STRING,
6279                            ts TIMESTAMP,
6280                            TIME INDEX (ts),
6281                            PRIMARY KEY(host)
6282                        ) engine=mito;"#;
6283        replace_test(sql, plugins.clone(), &query_ctx);
6284
6285        // test drop table
6286        let sql = "DROP TABLE {catalog}{schema}demo;";
6287        replace_test(sql, plugins.clone(), &query_ctx);
6288
6289        // test undrop table
6290        #[cfg(feature = "enterprise")]
6291        {
6292            let sql = "UNDROP TABLE {catalog}{schema}demo;";
6293            replace_test(sql, plugins.clone(), &query_ctx);
6294        }
6295
6296        // test show tables
6297        let sql = "SHOW TABLES FROM public";
6298        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
6299        check_permission(plugins.clone(), &stmt[0], &query_ctx).unwrap();
6300
6301        let sql = "SHOW TABLES FROM private";
6302        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
6303        let re = check_permission(plugins.clone(), &stmt[0], &query_ctx);
6304        assert!(re.is_ok());
6305
6306        // test describe table
6307        let sql = "DESC TABLE {catalog}{schema}demo;";
6308        replace_test(sql, plugins.clone(), &query_ctx);
6309
6310        let comment_flow_cases = [
6311            ("COMMENT ON FLOW my_flow IS 'comment';", true),
6312            ("COMMENT ON FLOW greptime.my_flow IS 'comment';", true),
6313            ("COMMENT ON FLOW wrongcatalog.my_flow IS 'comment';", false),
6314        ];
6315        for (sql, is_ok) in comment_flow_cases {
6316            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
6317            let result = check_permission(plugins.clone(), stmt, &query_ctx);
6318            assert_eq!(result.is_ok(), is_ok);
6319        }
6320
6321        let show_flow_cases = [
6322            ("SHOW CREATE FLOW my_flow;", true),
6323            ("SHOW CREATE FLOW greptime.my_flow;", true),
6324            ("SHOW CREATE FLOW wrongcatalog.my_flow;", false),
6325        ];
6326        for (sql, is_ok) in show_flow_cases {
6327            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
6328            let result = check_permission(plugins.clone(), stmt, &query_ctx);
6329            assert_eq!(result.is_ok(), is_ok);
6330        }
6331    }
6332
6333    /// A `DropView` DDL sent through the direct gRPC ingress must return an error
6334    /// (e.g. table not found) instead of panicking on `todo!()`.
6335    #[tokio::test]
6336    async fn qx_152_drop_view_via_grpc_ddl_returns_error_not_panic() -> TestResult<()> {
6337        let instance =
6338            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
6339                .await?;
6340
6341        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
6342            expr: Some(api::v1::ddl_request::Expr::DropView(
6343                api::v1::DropViewExpr {
6344                    catalog_name: String::new(),
6345                    schema_name: String::new(),
6346                    view_name: "non_existent_view".to_string(),
6347                    view_id: None,
6348                    drop_if_exists: false,
6349                },
6350            )),
6351        });
6352
6353        let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
6354            &instance,
6355            request,
6356            QueryContext::arc(),
6357        )
6358        .await;
6359
6360        let err = match result {
6361            Ok(_) => panic!("DropView DDL request must return an error instead of panicking"),
6362            Err(err) => err,
6363        };
6364        assert_eq!(
6365            err.status_code(),
6366            StatusCode::TableNotFound,
6367            "dropping a non-existent view without IF EXISTS must report TableNotFound, got {err}"
6368        );
6369        Ok(())
6370    }
6371
6372    #[tokio::test]
6373    async fn logical_ddl_validates_and_authorizes_rewritten_batch_before_submission()
6374    -> TestResult<()> {
6375        struct Rewrite(&'static str);
6376        impl SqlQueryInterceptor for Rewrite {
6377            type Error = Error;
6378            fn pre_parsing<'a>(
6379                &self,
6380                query: &'a str,
6381                _: QueryContextRef,
6382            ) -> Result<std::borrow::Cow<'a, str>> {
6383                Ok(if self.0 == "sql_bytes" {
6384                    std::borrow::Cow::Owned(format!("{query}{}", " ".repeat(1024 * 1024 + 1)))
6385                } else {
6386                    std::borrow::Cow::Borrowed(query)
6387                })
6388            }
6389            fn pre_execute(
6390                &self,
6391                statement: Option<&Statement>,
6392                _: Option<&LogicalPlan>,
6393                _: QueryContextRef,
6394            ) -> Result<()> {
6395                ensure!(
6396                    !(self.0 == "pre_execute"
6397                        && matches!(statement,
6398                    Some(Statement::CreateTable(create)) if create.name.to_string() == "allowed2")),
6399                    InvalidSqlSnafu {
6400                        err_msg: "second member rejected by interceptor"
6401                    }
6402                );
6403                Ok(())
6404            }
6405            fn post_parsing(
6406                &self,
6407                mut statements: Vec<Statement>,
6408                _: QueryContextRef,
6409            ) -> Result<Vec<Statement>> {
6410                match self.0 {
6411                    "target" => {
6412                        statements[1] = parse_one_sql(
6413                            "CREATE TABLE denied (ts TIMESTAMP TIME INDEX) ENGINE=metric WITH (on_physical_table='phy')",
6414                        )
6415                    }
6416                    "count" => statements = (0..129).map(|i| parse_one_sql(&format!(
6417                        "CREATE TABLE allowed_{i} (ts TIMESTAMP TIME INDEX) ENGINE=metric WITH (on_physical_table='phy')"
6418                    ))).collect(),
6419                    "type" => statements[1] = parse_one_sql("SELECT 1"),
6420                    "secret_bytes" | "array_bytes" | "small_option" => {
6421                        if let Statement::CreateTable(create) = &mut statements[1] {
6422                            let value = "x".repeat(if self.0 == "small_option" { 10 } else { 2 * 1024 * 1024 });
6423                            if self.0 == "array_bytes" {
6424                                create.options.insert_options("non_scalar", vec![value.as_str()].into());
6425                            } else {
6426                                create.options.insert("secret_access_key".to_string(), value);
6427                            }
6428                        }
6429                    }
6430                    "partition_shape" => {
6431                        if let Statement::CreateTable(create) = &mut statements[1] {
6432                            create.partitions = Some(sql::statements::create::Partitions {
6433                                column_list: vec![],
6434                                exprs: vec![sqlparser::ast::Expr::Identifier(sqlparser::ast::Ident::new("hidden"))],
6435                            });
6436                        }
6437                    }
6438                    "vector_hidden" => {
6439                        statements[1] = parse_one_sql("CREATE TABLE allowed2 (ts TIMESTAMP TIME INDEX, v VECTOR(3)) ENGINE=metric WITH (on_physical_table='phy')");
6440                        if let Statement::CreateTable(create) = &mut statements[1] {
6441                            create.columns[1].column_def.options.push(sqlparser::ast::ColumnOptionDef {
6442                                name: None,
6443                                option: sqlparser::ast::ColumnOption::Comment("private-value".repeat(200_000)),
6444                            });
6445                        }
6446                    }
6447                    mode if mode.starts_with("fulltext_") || mode.starts_with("skipping_")
6448                        || mode.starts_with("inverted_") || mode.starts_with("vector_") => {
6449                        if let Statement::CreateTable(create) = &mut statements[1] {
6450                            let (kind, value_type) = mode.split_once('_').unwrap();
6451                            let value = "x".repeat(if value_type == "small" { 10 } else { 2 * 1024 * 1024 });
6452                            let extensions = &mut create.columns[1].extensions;
6453                            let options = match kind {
6454                                "fulltext" => &mut extensions.fulltext_index_options,
6455                                "skipping" => &mut extensions.skipping_index_options,
6456                                "inverted" => &mut extensions.inverted_index_options,
6457                                _ => &mut extensions.vector_options,
6458                            }.get_or_insert_default();
6459                            if kind == "vector" {
6460                                options.insert("dim".to_string(), "3".to_string());
6461                            }
6462                            if value_type == "array" {
6463                                options.insert_options("non_scalar", vec![value.as_str()].into());
6464                            } else {
6465                                options.insert("secret_access_key".to_string(), value);
6466                            }
6467                        }
6468                    }
6469                    "physical_null" | "physical_array" => {
6470                        let value = if self.0 == "physical_null" { "NULL" } else { "['x']" };
6471                        statements[1] = parse_one_sql(&format!(
6472                            "CREATE TABLE allowed2 (ts TIMESTAMP TIME INDEX) ENGINE=metric WITH (on_physical_table='phy', physical_metric_table={value})"
6473                        ));
6474                    }
6475                    "ast_bytes" => {
6476                        if let Statement::CreateTable(create) = &mut statements[1] {
6477                            create.name =
6478                                ObjectName(vec![sqlparser::ast::ObjectNamePart::Identifier(
6479                                    sqlparser::ast::Ident::new("t".repeat(1024 * 1024)),
6480                                )]);
6481                        }
6482                    }
6483                    _ => {}
6484                }
6485                Ok(statements)
6486            }
6487        }
6488        for mode in [
6489            "none",
6490            "target",
6491            "count",
6492            "type",
6493            "sql_bytes",
6494            "ast_bytes",
6495            "secret_bytes",
6496            "array_bytes",
6497            "small_option",
6498            "physical_null",
6499            "physical_array",
6500            "fulltext_secret",
6501            "fulltext_array",
6502            "fulltext_small",
6503            "skipping_secret",
6504            "skipping_array",
6505            "skipping_small",
6506            "inverted_secret",
6507            "inverted_array",
6508            "inverted_small",
6509            "vector_secret",
6510            "vector_array",
6511            "vector_small",
6512            "vector_hidden",
6513            "partition_shape",
6514            "pre_execute",
6515            "cross_catalog",
6516            "valid",
6517        ] {
6518            let catalog =
6519                catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
6520            let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
6521            let plugins = Plugins::new();
6522            plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
6523            plugins.insert::<SqlQueryInterceptorRef<Error>>(Arc::new(Rewrite(mode)));
6524            plugins.insert(QueryOptions {
6525                disallow_cross_catalog_query: mode == "cross_catalog",
6526            });
6527            let instance = test_instance_with_catalog_manager(
6528                catalog,
6529                test_table(1025, "target")?,
6530                plugins,
6531                None,
6532                executor.clone(),
6533            )
6534            .await?;
6535            let create = |name| {
6536                format!(
6537                    "CREATE TABLE {name} (ts TIMESTAMP TIME INDEX, host STRING) ENGINE=metric WITH (on_physical_table='phy')"
6538                )
6539            };
6540            let sql = format!(
6541                "{};{}",
6542                create("allowed"),
6543                create(match mode {
6544                    "none" => "denied",
6545                    "cross_catalog" => "other.public.allowed2",
6546                    _ => "allowed2",
6547                })
6548            );
6549            let result =
6550                SqlQueryHandler::create_logical_tables(&instance, &sql, QueryContext::arc()).await;
6551            let submits = matches!(mode, "valid" | "small_option")
6552                || (mode.ends_with("_small") && !mode.starts_with("vector_"));
6553            if matches!(mode, "none" | "target") {
6554                let err = result.unwrap_err();
6555                assert_eq!(
6556                    err.status_code(),
6557                    StatusCode::PermissionDenied,
6558                    "{mode}: {err}"
6559                );
6560            } else {
6561                assert_eq!(
6562                    result.unwrap_err().status_code(),
6563                    match mode {
6564                        _ if submits => StatusCode::Unsupported,
6565                        "cross_catalog" => StatusCode::AccessDenied,
6566                        _ => StatusCode::InvalidArguments,
6567                    },
6568                    "{mode}"
6569                );
6570            }
6571            assert_eq!(
6572                executor.submitted.lock().unwrap().len(),
6573                usize::from(submits),
6574                "{mode}"
6575            );
6576        }
6577        Ok(())
6578    }
6579
6580    /// `DROP VIEW IF EXISTS` on a missing view through the direct gRPC ingress must
6581    /// succeed with 0 affected rows (no error, no DDL task submitted), instead of
6582    /// returning `TableNotFound`.
6583    #[tokio::test]
6584    async fn qx_152_drop_view_if_exists_missing_view_via_grpc_ddl_succeeds() -> TestResult<()> {
6585        let catalog_manager =
6586            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
6587        let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
6588        let instance = test_instance_with_catalog_manager(
6589            catalog_manager,
6590            test_table(1025, "target")?,
6591            Plugins::new(),
6592            None,
6593            procedure_executor.clone() as ProcedureExecutorRef,
6594        )
6595        .await?;
6596
6597        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
6598            expr: Some(api::v1::ddl_request::Expr::DropView(
6599                api::v1::DropViewExpr {
6600                    catalog_name: String::new(),
6601                    schema_name: String::new(),
6602                    view_name: "non_existent_view".to_string(),
6603                    view_id: None,
6604                    drop_if_exists: true,
6605                },
6606            )),
6607        });
6608
6609        let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
6610            &instance,
6611            request,
6612            QueryContext::arc(),
6613        )
6614        .await;
6615
6616        let output = match result {
6617            Ok(output) => output,
6618            Err(err) => {
6619                panic!("DROP VIEW IF EXISTS on a missing view must succeed, got error: {err}")
6620            }
6621        };
6622        assert!(
6623            matches!(output.data, OutputData::AffectedRows(0)),
6624            "DROP VIEW IF EXISTS on a missing view must report 0 affected rows"
6625        );
6626        assert!(
6627            procedure_executor.submitted.lock().unwrap().is_empty(),
6628            "DROP VIEW IF EXISTS on a missing view must not submit a DDL task"
6629        );
6630        Ok(())
6631    }
6632
6633    /// A `CREATE VIEW` followed by `DROP VIEW` through the direct gRPC ingress must
6634    /// succeed end to end: the view is registered in the catalog and then removed.
6635    #[tokio::test]
6636    async fn qx_152_drop_existing_view_via_grpc_ddl_succeeds() -> TestResult<()> {
6637        let catalog_manager =
6638            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
6639        let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
6640        let instance = test_instance_with_catalog_manager(
6641            catalog_manager,
6642            test_table(1025, "target")?,
6643            Plugins::new(),
6644            None,
6645            procedure_executor.clone() as ProcedureExecutorRef,
6646        )
6647        .await?;
6648
6649        // The default "greptime.public" schema must be visible to the kv-backed table
6650        // metadata manager for `CREATE VIEW`/`CREATE TABLE` to pass validation.
6651        instance
6652            .table_metadata_manager()
6653            .schema_manager()
6654            .create(
6655                common_meta::key::schema_name::SchemaNameKey::new("greptime", "public"),
6656                None,
6657                true,
6658            )
6659            .await
6660            .unwrap();
6661
6662        let create_view_request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
6663            expr: Some(api::v1::ddl_request::Expr::CreateView(
6664                api::v1::CreateViewExpr {
6665                    catalog_name: String::new(),
6666                    schema_name: String::new(),
6667                    view_name: "my_view".to_string(),
6668                    logical_plan: vec![1, 2, 3],
6669                    create_if_not_exists: false,
6670                    or_replace: false,
6671                    table_names: vec![],
6672                    columns: vec![],
6673                    plan_columns: vec![],
6674                    definition: "CREATE VIEW my_view AS SELECT * FROM source".to_string(),
6675                },
6676            )),
6677        });
6678
6679        let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
6680            &instance,
6681            create_view_request,
6682            QueryContext::arc(),
6683        )
6684        .await
6685        {
6686            Ok(output) => output,
6687            Err(err) => panic!("CREATE VIEW via gRPC DDL must succeed, got error: {err}"),
6688        };
6689        assert!(
6690            matches!(output.data, OutputData::AffectedRows(0)),
6691            "CREATE VIEW via gRPC DDL must report 0 affected rows"
6692        );
6693
6694        // The view is registered in the catalog as a view.
6695        let view = instance
6696            .catalog_manager()
6697            .table("greptime", "public", "my_view", None)
6698            .await
6699            .unwrap()
6700            .expect("view should exist after CREATE VIEW");
6701        assert_eq!(view.table_info().table_type, TableType::View);
6702
6703        let drop_view_request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
6704            expr: Some(api::v1::ddl_request::Expr::DropView(
6705                api::v1::DropViewExpr {
6706                    catalog_name: String::new(),
6707                    schema_name: String::new(),
6708                    view_name: "my_view".to_string(),
6709                    view_id: None,
6710                    drop_if_exists: false,
6711                },
6712            )),
6713        });
6714
6715        let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
6716            &instance,
6717            drop_view_request,
6718            QueryContext::arc(),
6719        )
6720        .await
6721        {
6722            Ok(output) => output,
6723            Err(err) => panic!("DROP VIEW via gRPC DDL must succeed, got error: {err}"),
6724        };
6725        assert!(
6726            matches!(output.data, OutputData::AffectedRows(0)),
6727            "DROP VIEW via gRPC DDL must report 0 affected rows"
6728        );
6729
6730        // The view is gone after the drop.
6731        assert!(
6732            instance
6733                .catalog_manager()
6734                .table("greptime", "public", "my_view", None)
6735                .await
6736                .unwrap()
6737                .is_none(),
6738            "view should be removed after DROP VIEW"
6739        );
6740
6741        let submitted = procedure_executor.submitted.lock().unwrap();
6742        assert_eq!(
6743            submitted.len(),
6744            2,
6745            "expected create and drop view tasks, got {submitted:?}"
6746        );
6747        assert!(matches!(&submitted[0], DdlTask::CreateView(_)));
6748        assert!(matches!(&submitted[1], DdlTask::DropView(_)));
6749        Ok(())
6750    }
6751
6752    /// A direct gRPC `CreateTable` whose time index column is not a timestamp must
6753    /// be rejected with `InvalidArguments` instead of panicking while building the schema.
6754    #[tokio::test]
6755    async fn qx_153_create_table_with_non_timestamp_time_index_via_grpc_returns_error()
6756    -> TestResult<()> {
6757        let instance =
6758            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
6759                .await?;
6760
6761        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
6762            expr: Some(api::v1::ddl_request::Expr::CreateTable(
6763                api::v1::CreateTableExpr {
6764                    catalog_name: String::new(),
6765                    schema_name: String::new(),
6766                    table_name: "demo".to_string(),
6767                    desc: String::new(),
6768                    column_defs: vec![api::v1::ColumnDef {
6769                        name: "host".to_string(),
6770                        data_type: api::v1::ColumnDataType::String as i32,
6771                        is_nullable: true,
6772                        default_constraint: vec![],
6773                        semantic_type: 0,
6774                        comment: String::new(),
6775                        datatype_extension: None,
6776                        options: None,
6777                    }],
6778                    time_index: "host".to_string(),
6779                    primary_keys: vec![],
6780                    create_if_not_exists: false,
6781                    table_options: HashMap::new(),
6782                    table_id: None,
6783                    engine: "mito".to_string(),
6784                },
6785            )),
6786        });
6787
6788        let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
6789            &instance,
6790            request,
6791            QueryContext::arc(),
6792        )
6793        .await;
6794
6795        let err = match result {
6796            Ok(_) => panic!("CreateTable with a non-timestamp time index must be rejected"),
6797            Err(err) => err,
6798        };
6799        assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err}");
6800        Ok(())
6801    }
6802
6803    /// A valid `CREATE TABLE` (timestamp time index) through the direct gRPC ingress
6804    /// must succeed, guarding that the `validate_create_expr` ingress check doesn't
6805    /// accidentally reject good requests.
6806    #[tokio::test]
6807    async fn qx_153_create_table_with_timestamp_time_index_via_grpc_succeeds() -> TestResult<()> {
6808        let catalog_manager =
6809            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
6810        let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
6811        let instance = test_instance_with_catalog_manager(
6812            catalog_manager,
6813            test_table(1025, "target")?,
6814            Plugins::new(),
6815            None,
6816            procedure_executor.clone() as ProcedureExecutorRef,
6817        )
6818        .await?;
6819
6820        // The default "greptime.public" schema must be visible to the kv-backed table
6821        // metadata manager for `CREATE TABLE` to pass validation.
6822        instance
6823            .table_metadata_manager()
6824            .schema_manager()
6825            .create(
6826                common_meta::key::schema_name::SchemaNameKey::new("greptime", "public"),
6827                None,
6828                true,
6829            )
6830            .await
6831            .unwrap();
6832
6833        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
6834            expr: Some(api::v1::ddl_request::Expr::CreateTable(
6835                api::v1::CreateTableExpr {
6836                    catalog_name: String::new(),
6837                    schema_name: String::new(),
6838                    table_name: "demo".to_string(),
6839                    desc: String::new(),
6840                    column_defs: vec![
6841                        api::v1::ColumnDef {
6842                            name: "host".to_string(),
6843                            data_type: api::v1::ColumnDataType::String as i32,
6844                            is_nullable: true,
6845                            default_constraint: vec![],
6846                            semantic_type: 0,
6847                            comment: String::new(),
6848                            datatype_extension: None,
6849                            options: None,
6850                        },
6851                        api::v1::ColumnDef {
6852                            name: "ts".to_string(),
6853                            data_type: api::v1::ColumnDataType::TimestampMillisecond as i32,
6854                            is_nullable: true,
6855                            default_constraint: vec![],
6856                            semantic_type: 0,
6857                            comment: String::new(),
6858                            datatype_extension: None,
6859                            options: None,
6860                        },
6861                    ],
6862                    time_index: "ts".to_string(),
6863                    primary_keys: vec![],
6864                    create_if_not_exists: false,
6865                    table_options: HashMap::new(),
6866                    table_id: None,
6867                    engine: "mito".to_string(),
6868                },
6869            )),
6870        });
6871
6872        let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
6873            &instance,
6874            request,
6875            QueryContext::arc(),
6876        )
6877        .await
6878        {
6879            Ok(output) => output,
6880            Err(err) => panic!("CREATE TABLE via gRPC DDL must succeed, got error: {err}"),
6881        };
6882        assert!(
6883            matches!(output.data, OutputData::AffectedRows(0)),
6884            "CREATE TABLE via gRPC DDL must report 0 affected rows"
6885        );
6886
6887        // The table is registered in the catalog.
6888        let table = instance
6889            .catalog_manager()
6890            .table("greptime", "public", "demo", None)
6891            .await
6892            .unwrap()
6893            .expect("table should exist after CREATE TABLE");
6894        assert_eq!(table.table_info().table_type, TableType::Base);
6895
6896        let submitted = procedure_executor.submitted.lock().unwrap();
6897        assert_eq!(
6898            submitted.len(),
6899            1,
6900            "expected one create table task, got {submitted:?}"
6901        );
6902        assert!(matches!(&submitted[0], DdlTask::CreateTable(_)));
6903        Ok(())
6904    }
6905
6906    #[tokio::test]
6907    async fn test_copy_in_checks_table_permissions() -> TestResult<()> {
6908        use servers::query_handler::CopyInHandler;
6909
6910        for source in [
6911            test_table(1024, "denied")?,
6912            test_physical_table(1024, "physical")?,
6913        ] {
6914            let name = source.table_info().name.clone();
6915            let plugins = Plugins::new();
6916            plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
6917            let instance =
6918                test_instance_with_plugins(source, test_table(1025, "target")?, plugins).await?;
6919            let ctx = QueryContext::arc();
6920            assert_permission_denied(
6921                instance
6922                    .copy_in_table("greptime", "public", &name, ctx.clone())
6923                    .await,
6924            );
6925            assert!(
6926                instance
6927                    .copy_in_table("greptime", "public", "target", ctx.clone())
6928                    .await
6929                    .unwrap()
6930                    .is_some()
6931            );
6932            assert!(
6933                instance
6934                    .copy_in_table("greptime", "public", "missing", ctx)
6935                    .await
6936                    .unwrap()
6937                    .is_none()
6938            );
6939        }
6940        Ok(())
6941    }
6942
6943    /// COPY FROM STDIN must enforce the same cross-catalog restriction as
6944    /// SQL INSERT when `disallow_cross_catalog_query` is configured.
6945    #[tokio::test]
6946    async fn test_copy_in_cross_catalog_restriction() -> TestResult<()> {
6947        use catalog::memory::MemoryCatalogManager;
6948        use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
6949        use servers::query_handler::CopyInHandler;
6950
6951        let catalog = MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
6952        // A table in another catalog.
6953        catalog.register_catalog_sync("other").unwrap();
6954        catalog
6955            .register_schema_sync(catalog::RegisterSchemaRequest {
6956                catalog: "other".to_string(),
6957                schema: DEFAULT_SCHEMA_NAME.to_string(),
6958            })
6959            .unwrap();
6960        catalog
6961            .register_table_sync(catalog::RegisterTableRequest {
6962                catalog: "other".to_string(),
6963                schema: DEFAULT_SCHEMA_NAME.to_string(),
6964                table_name: "copy_guard".to_string(),
6965                table_id: 2048,
6966                table: test_table(2048, "copy_guard")?,
6967            })
6968            .unwrap();
6969        let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
6970        let plugins = Plugins::new();
6971        plugins.insert(QueryOptions {
6972            disallow_cross_catalog_query: true,
6973        });
6974        let instance = test_instance_with_catalog_manager(
6975            catalog,
6976            test_table(1025, "target")?,
6977            plugins,
6978            None,
6979            executor,
6980        )
6981        .await?;
6982
6983        let ctx = Arc::new(QueryContext::with(
6984            DEFAULT_CATALOG_NAME,
6985            DEFAULT_SCHEMA_NAME,
6986        ));
6987
6988        // Cross-catalog COPY is rejected before any data is streamed.
6989        let err = instance
6990            .copy_in_table("other", DEFAULT_SCHEMA_NAME, "copy_guard", ctx.clone())
6991            .await
6992            .unwrap_err();
6993        assert!(
6994            format!("{err:?}").contains("Illegal access to catalog"),
6995            "{err}"
6996        );
6997
6998        // Same-catalog COPY resolves normally.
6999        let found = instance
7000            .copy_in_table(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "target", ctx)
7001            .await
7002            .unwrap();
7003        assert!(found.is_some());
7004
7005        Ok(())
7006    }
7007
7008    /// Scope-targeted COPY formats (OTLP logs/traces) run the same
7009    /// cross-catalog restriction through `copy_in_validate_scope` before
7010    /// any data is streamed.
7011    #[tokio::test]
7012    async fn test_copy_in_validate_scope_cross_catalog_restriction() -> TestResult<()> {
7013        use catalog::memory::MemoryCatalogManager;
7014        use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
7015        use servers::query_handler::CopyInHandler;
7016
7017        let catalog = MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
7018        let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
7019        let plugins = Plugins::new();
7020        plugins.insert(QueryOptions {
7021            disallow_cross_catalog_query: true,
7022        });
7023        let instance = test_instance_with_catalog_manager(
7024            catalog,
7025            test_table(1025, "target")?,
7026            plugins,
7027            None,
7028            executor,
7029        )
7030        .await?;
7031
7032        let ctx = Arc::new(QueryContext::with(
7033            DEFAULT_CATALOG_NAME,
7034            DEFAULT_SCHEMA_NAME,
7035        ));
7036
7037        // A target outside the session's catalog is rejected before any
7038        // data is streamed; a same-catalog schema is not.
7039        let err = instance
7040            .copy_in_validate_scope("other", DEFAULT_SCHEMA_NAME, ctx.clone())
7041            .await
7042            .unwrap_err();
7043        assert!(
7044            format!("{err:?}").contains("Illegal access to catalog"),
7045            "{err}"
7046        );
7047        instance
7048            .copy_in_validate_scope(DEFAULT_CATALOG_NAME, "other_schema", ctx.clone())
7049            .await
7050            .unwrap();
7051
7052        // Without the restriction every scope validates.
7053        let plugins = Plugins::new();
7054        plugins.insert(QueryOptions {
7055            disallow_cross_catalog_query: false,
7056        });
7057        let catalog = MemoryCatalogManager::new_with_table(test_table(1026, "source")?);
7058        let instance = test_instance_with_catalog_manager(
7059            catalog.clone(),
7060            test_table(1027, "target")?,
7061            plugins,
7062            None,
7063            Arc::new(MockProcedureExecutor::new(catalog)),
7064        )
7065        .await?;
7066        instance
7067            .copy_in_validate_scope("other", DEFAULT_SCHEMA_NAME, ctx)
7068            .await
7069            .unwrap();
7070
7071        Ok(())
7072    }
7073
7074    const NATIVE_PROMQL_OPTION: &str = "query.experimental_native_promql";
7075
7076    /// A frontend whose `public` schema holds two metric-engine logical tables, `cpu_usage` and
7077    /// `target`, with `checker` as its permission checker.
7078    async fn test_metric_discovery_instance(checker: PermissionCheckerRef) -> TestResult<Instance> {
7079        let plugins = Plugins::new();
7080        plugins.insert::<PermissionCheckerRef>(checker);
7081        test_instance_with_plugins_and_metric_names(
7082            test_logical_table(1024, "cpu_usage")?,
7083            test_logical_table(1025, "target")?,
7084            plugins,
7085            None,
7086        )
7087        .await
7088    }
7089
7090    /// An expression that has to be answered by discovering the schema's metric tables: it names
7091    /// no exact metric, only a name matcher.
7092    fn discovery_metric_expr() -> promql_parser::parser::Expr {
7093        promql_parser::parser::parse(r#"{__name__=~"cpu.*"}"#).unwrap()
7094    }
7095
7096    /// The tables a bounded scope allows, sorted so a test can state them.
7097    fn allowed_tables(scope: &MetricDiscoveryScope) -> Vec<String> {
7098        let MetricDiscoveryScope::Allowed(allowed) = scope else {
7099            panic!("expected a table-bounded discovery scope, got {scope:?}");
7100        };
7101        let mut tables = allowed
7102            .iter()
7103            .map(|target| target.table.clone())
7104            .collect::<Vec<_>>();
7105        tables.sort_unstable();
7106        tables
7107    }
7108
7109    /// A session `SET` turns the native route on without any request hint, so the scope has to be
7110    /// bounded by the caller's grants in exactly that case too.
7111    #[tokio::test]
7112    async fn test_discovery_scope_bounds_a_session_enabled_native_route() -> TestResult<()> {
7113        let instance =
7114            test_metric_discovery_instance(Arc::new(RejectUnresolvedPermissionChecker)).await?;
7115        let mut ctx = test_query_ctx(1);
7116        ctx.configuration_parameter()
7117            .set_query_option(NATIVE_PROMQL_OPTION, "true")
7118            .unwrap();
7119        assert!(
7120            ctx.extension(NATIVE_PROMQL_OPTION).is_none(),
7121            "a session SET is not a request hint"
7122        );
7123
7124        instance
7125            .prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
7126            .await
7127            .unwrap();
7128
7129        assert_eq!(
7130            vec!["cpu_usage".to_string(), "target".to_string()],
7131            allowed_tables(ctx.metric_discovery_scope())
7132        );
7133
7134        Ok(())
7135    }
7136
7137    /// With the switch off and nothing stated, the route never reads discovery, so the scope stays
7138    /// unrestricted and no per-table grant is asked for: a query that does not use the route pays
7139    /// nothing here.
7140    #[tokio::test]
7141    async fn test_discovery_scope_is_not_computed_when_the_route_is_off() -> TestResult<()> {
7142        let counter = Arc::new(CountingPermissionChecker::default());
7143        let instance = test_metric_discovery_instance(counter.clone()).await?;
7144        let mut ctx = test_query_ctx(1);
7145        assert!(ctx.extension(NATIVE_PROMQL_OPTION).is_none());
7146        assert_eq!(
7147            None,
7148            ctx.effective_query_options()
7149                .unwrap()
7150                .get(NATIVE_PROMQL_OPTION),
7151            "nothing states the option here"
7152        );
7153
7154        instance
7155            .prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
7156            .await
7157            .unwrap();
7158
7159        assert!(
7160            matches!(
7161                ctx.metric_discovery_scope(),
7162                MetricDiscoveryScope::Unrestricted
7163            ),
7164            "a route that is off reads no scope: {:?}",
7165            ctx.metric_discovery_scope()
7166        );
7167        assert_eq!(
7168            0,
7169            counter.table_target_checks(),
7170            "an off route asked for per-table grants"
7171        );
7172        assert!(
7173            ctx.extension(NATIVE_PROMQL_OPTION).is_none(),
7174            "resolving the switch must not state the option"
7175        );
7176
7177        Ok(())
7178    }
7179
7180    /// A checker that decides without table targets needs no bound: there is nothing to narrow.
7181    #[tokio::test]
7182    async fn test_discovery_scope_stays_unrestricted_without_table_targets() -> TestResult<()> {
7183        let instance =
7184            test_metric_discovery_instance(Arc::new(TargetIndependentPermissionChecker::default()))
7185                .await?;
7186        let mut ctx = test_query_ctx(1);
7187
7188        instance
7189            .prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
7190            .await
7191            .unwrap();
7192
7193        assert!(
7194            matches!(
7195                ctx.metric_discovery_scope(),
7196                MetricDiscoveryScope::Unrestricted
7197            ),
7198            "got {:?}",
7199            ctx.metric_discovery_scope()
7200        );
7201
7202        Ok(())
7203    }
7204
7205    /// Resolving the switch must not state it: the option a query inherits stays inherited, so
7206    /// nothing this function does can change what planning later resolves. With nothing stated and
7207    /// the engine default off the route is off, which leaves discovery unrestricted - the scope is
7208    /// the only thing this function changes, and the route reads the option, not the scope.
7209    ///
7210    /// The routing itself is asserted where the plan is built
7211    /// (`query::planner`'s `test_engine_option_is_the_default_a_request_or_session_overrides`
7212    /// covers the "nothing stated, engine default" case): a catalog of plain in-memory tables
7213    /// cannot plan a discovery expression natively, so a frontend-level plan assertion would only
7214    /// restate the legacy planner's own rejections.
7215    #[tokio::test]
7216    async fn test_discovery_scope_does_not_state_the_native_option() -> TestResult<()> {
7217        let instance =
7218            test_metric_discovery_instance(Arc::new(RejectUnresolvedPermissionChecker)).await?;
7219        let mut ctx = test_query_ctx(1);
7220        assert!(ctx.extension(NATIVE_PROMQL_OPTION).is_none());
7221
7222        instance
7223            .prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
7224            .await
7225            .unwrap();
7226
7227        assert!(
7228            matches!(
7229                ctx.metric_discovery_scope(),
7230                MetricDiscoveryScope::Unrestricted
7231            ),
7232            "an off route reads no scope: {:?}",
7233            ctx.metric_discovery_scope()
7234        );
7235        assert!(
7236            ctx.extension(NATIVE_PROMQL_OPTION).is_none(),
7237            "computing the scope must not state the option"
7238        );
7239        assert_eq!(
7240            None,
7241            ctx.effective_query_options()
7242                .unwrap()
7243                .get(NATIVE_PROMQL_OPTION),
7244            "the route stays on the engine default"
7245        );
7246
7247        Ok(())
7248    }
7249
7250    /// TQL discovers metrics as the Prometheus handler does: bounded by the tables the statement's
7251    /// own request may read, and that scope reaches planning. A table the statement names is still
7252    /// checked by name.
7253    #[tokio::test]
7254    async fn test_tql_discovery_is_bounded_by_the_statement_grants() -> TestResult<()> {
7255        let plugins = Plugins::new();
7256        plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
7257        let instance = test_instance_with_plugins_and_metric_names(
7258            test_logical_table(1024, "denied")?,
7259            test_logical_table(1025, "target")?,
7260            plugins,
7261            None,
7262        )
7263        .await?;
7264        let ctx = test_query_ctx(1);
7265        ctx.configuration_parameter()
7266            .set_query_option(NATIVE_PROMQL_OPTION, "true")
7267            .unwrap();
7268
7269        for sql in [
7270            r#"TQL EVAL (0, 10, '5s') {__name__=~".+"}"#,
7271            r#"TQL EXPLAIN (0, 10, '5s') sum({__name__=~".+"})"#,
7272            r#"WITH t AS (TQL EVAL (0, 10, '5s') {__name__=~".+"}) SELECT * FROM t"#,
7273        ] {
7274            let planning_ctx = instance
7275                .check_sql_permission(&parse_one_sql(sql), &ctx)
7276                .await
7277                .unwrap();
7278            assert_eq!(
7279                vec!["target".to_string()],
7280                allowed_tables(planning_ctx.metric_discovery_scope()),
7281                "{sql}"
7282            );
7283        }
7284
7285        let err = instance
7286            .check_sql_permission(
7287                &parse_one_sql(r#"TQL EVAL (0, 10, '5s') {__name__=~".+"} + denied"#),
7288                &ctx,
7289            )
7290            .await
7291            .unwrap_err();
7292        assert_eq!(StatusCode::PermissionDenied, err.status_code());
7293
7294        Ok(())
7295    }
7296
7297    /// A TQL statement discovers only the tables its own SQL request may read, even where a
7298    /// PromQL grant would also allow one: the HTTP action must not widen what TQL reads.
7299    #[tokio::test]
7300    async fn test_tql_discovery_checks_the_statement_request() -> TestResult<()> {
7301        struct PromqlOnlyDenied;
7302
7303        impl PermissionChecker for PromqlOnlyDenied {
7304            fn check_permission(
7305                &self,
7306                _user_info: UserInfoRef,
7307                _req: PermissionReq,
7308            ) -> auth::error::Result<PermissionResp> {
7309                Ok(PermissionResp::Allow)
7310            }
7311
7312            fn check_permission_with_table_targets(
7313                &self,
7314                _user_info: UserInfoRef,
7315                req: PermissionReq,
7316                targets: PermissionTableTargets,
7317                _current_schema: Option<&str>,
7318            ) -> auth::error::Result<PermissionResp> {
7319                let reject = match targets {
7320                    PermissionTableTargets::Unresolved => true,
7321                    PermissionTableTargets::Resolved(targets) => {
7322                        matches!(req, PermissionReq::SqlStatement(_))
7323                            && targets.iter().any(|target| target.table == "denied")
7324                    }
7325                };
7326                Ok(if reject {
7327                    PermissionResp::Reject
7328                } else {
7329                    PermissionResp::Allow
7330                })
7331            }
7332        }
7333
7334        let plugins = Plugins::new();
7335        plugins.insert::<PermissionCheckerRef>(Arc::new(PromqlOnlyDenied));
7336        let instance = test_instance_with_plugins_and_metric_names(
7337            test_logical_table(1024, "denied")?,
7338            test_logical_table(1025, "target")?,
7339            plugins,
7340            None,
7341        )
7342        .await?;
7343        let ctx = test_query_ctx(1);
7344        ctx.configuration_parameter()
7345            .set_query_option(NATIVE_PROMQL_OPTION, "true")
7346            .unwrap();
7347
7348        let planning_ctx = instance
7349            .check_sql_permission(
7350                &parse_one_sql(r#"TQL EVAL (0, 10, '5s') {__name__=~".+"}"#),
7351                &ctx,
7352            )
7353            .await
7354            .unwrap();
7355        assert_eq!(
7356            vec!["target".to_string()],
7357            allowed_tables(planning_ctx.metric_discovery_scope())
7358        );
7359
7360        Ok(())
7361    }
7362
7363    struct CountingCatalogManager {
7364        inner: Arc<catalog::memory::MemoryCatalogManager>,
7365        table_calls: atomic::AtomicUsize,
7366        table_id_calls: atomic::AtomicUsize,
7367        table_info_by_id_calls: atomic::AtomicUsize,
7368    }
7369
7370    impl CountingCatalogManager {
7371        fn new(inner: Arc<catalog::memory::MemoryCatalogManager>) -> Self {
7372            Self {
7373                inner,
7374                table_calls: atomic::AtomicUsize::new(0),
7375                table_id_calls: atomic::AtomicUsize::new(0),
7376                table_info_by_id_calls: atomic::AtomicUsize::new(0),
7377            }
7378        }
7379
7380        fn reset_counts(&self) {
7381            self.table_calls.store(0, atomic::Ordering::Relaxed);
7382            self.table_id_calls.store(0, atomic::Ordering::Relaxed);
7383            self.table_info_by_id_calls
7384                .store(0, atomic::Ordering::Relaxed);
7385        }
7386
7387        fn table_calls(&self) -> usize {
7388            self.table_calls.load(atomic::Ordering::Relaxed)
7389        }
7390
7391        fn table_id_calls(&self) -> usize {
7392            self.table_id_calls.load(atomic::Ordering::Relaxed)
7393        }
7394
7395        fn table_info_by_id_calls(&self) -> usize {
7396            self.table_info_by_id_calls.load(atomic::Ordering::Relaxed)
7397        }
7398
7399        fn total_table_lookups(&self) -> usize {
7400            self.table_calls() + self.table_id_calls() + self.table_info_by_id_calls()
7401        }
7402    }
7403
7404    #[async_trait::async_trait]
7405    impl catalog::CatalogManager for CountingCatalogManager {
7406        fn as_any(&self) -> &dyn std::any::Any {
7407            self
7408        }
7409
7410        async fn catalog_names(&self) -> catalog::error::Result<Vec<String>> {
7411            self.inner.catalog_names().await
7412        }
7413
7414        async fn schema_names(
7415            &self,
7416            catalog: &str,
7417            query_ctx: Option<&QueryContext>,
7418        ) -> catalog::error::Result<Vec<String>> {
7419            self.inner.schema_names(catalog, query_ctx).await
7420        }
7421
7422        async fn table_names(
7423            &self,
7424            catalog: &str,
7425            schema: &str,
7426            query_ctx: Option<&QueryContext>,
7427        ) -> catalog::error::Result<Vec<String>> {
7428            self.inner.table_names(catalog, schema, query_ctx).await
7429        }
7430
7431        async fn catalog_exists(&self, catalog: &str) -> catalog::error::Result<bool> {
7432            self.inner.catalog_exists(catalog).await
7433        }
7434
7435        async fn schema_exists(
7436            &self,
7437            catalog: &str,
7438            schema: &str,
7439            query_ctx: Option<&QueryContext>,
7440        ) -> catalog::error::Result<bool> {
7441            self.inner.schema_exists(catalog, schema, query_ctx).await
7442        }
7443
7444        async fn table_exists(
7445            &self,
7446            catalog: &str,
7447            schema: &str,
7448            table: &str,
7449            query_ctx: Option<&QueryContext>,
7450        ) -> catalog::error::Result<bool> {
7451            self.inner
7452                .table_exists(catalog, schema, table, query_ctx)
7453                .await
7454        }
7455
7456        async fn table(
7457            &self,
7458            catalog: &str,
7459            schema: &str,
7460            table_name: &str,
7461            query_ctx: Option<&QueryContext>,
7462        ) -> catalog::error::Result<Option<TableRef>> {
7463            self.table_calls.fetch_add(1, atomic::Ordering::Relaxed);
7464            self.inner
7465                .table(catalog, schema, table_name, query_ctx)
7466                .await
7467        }
7468
7469        async fn table_id(
7470            &self,
7471            catalog: &str,
7472            schema: &str,
7473            table_name: &str,
7474            query_ctx: Option<&QueryContext>,
7475        ) -> catalog::error::Result<Option<table::metadata::TableId>> {
7476            self.table_id_calls.fetch_add(1, atomic::Ordering::Relaxed);
7477            self.inner
7478                .table_id(catalog, schema, table_name, query_ctx)
7479                .await
7480        }
7481
7482        async fn table_info_by_id(
7483            &self,
7484            table_id: table::metadata::TableId,
7485        ) -> catalog::error::Result<Option<table::metadata::TableInfoRef>> {
7486            self.table_info_by_id_calls
7487                .fetch_add(1, atomic::Ordering::Relaxed);
7488            self.inner.table_info_by_id(table_id).await
7489        }
7490
7491        async fn tables_by_ids(
7492            &self,
7493            catalog: &str,
7494            schema: &str,
7495            table_ids: &[table::metadata::TableId],
7496        ) -> catalog::error::Result<Vec<TableRef>> {
7497            self.inner.tables_by_ids(catalog, schema, table_ids).await
7498        }
7499
7500        fn tables<'a>(
7501            &'a self,
7502            catalog: &'a str,
7503            schema: &'a str,
7504            query_ctx: Option<&'a QueryContext>,
7505        ) -> futures::stream::BoxStream<'a, catalog::error::Result<TableRef>> {
7506            self.inner.tables(catalog, schema, query_ctx)
7507        }
7508    }
7509
7510    async fn test_instance_with_counting_catalog(
7511        catalog_manager: Arc<CountingCatalogManager>,
7512        plugins: Plugins,
7513    ) -> TestResult<Instance> {
7514        let kv_backend = Arc::new(MemoryKvBackend::new());
7515        let process_manager = Arc::new(ProcessManager::new("test-frontend".to_string(), None));
7516        catalog_manager
7517            .inner
7518            .register_process_list_table(process_manager.clone());
7519        let cache_registry = test_cache_registry(kv_backend.clone())?;
7520
7521        FrontendBuilder::new(
7522            FrontendOptions::default(),
7523            kv_backend,
7524            cache_registry,
7525            catalog_manager,
7526            Arc::new(client::client_manager::NodeClients::default()),
7527            Arc::new(NoopProcedureExecutor),
7528            process_manager,
7529        )
7530        .with_plugin(plugins)
7531        .try_build()
7532        .await
7533        .context(BuildFrontendSnafu)
7534    }
7535
7536    #[tokio::test]
7537    async fn test_precheck_allow_skips_catalog_lookups() -> TestResult<()> {
7538        struct PrecheckAllowChecker;
7539        impl PermissionChecker for PrecheckAllowChecker {
7540            fn check_permission(
7541                &self,
7542                _: UserInfoRef,
7543                _: PermissionReq,
7544            ) -> auth::error::Result<PermissionResp> {
7545                Ok(PermissionResp::Allow)
7546            }
7547
7548            fn precheck_table_targets(
7549                &self,
7550                _: UserInfoRef,
7551                _: PermissionReq,
7552                _: &PermissionTableTargets,
7553                _: Option<&str>,
7554            ) -> auth::error::Result<TableTargetPrecheck> {
7555                Ok(TableTargetPrecheck::Allow)
7556            }
7557
7558            fn check_permission_with_table_targets(
7559                &self,
7560                _: UserInfoRef,
7561                _: PermissionReq,
7562                _: PermissionTableTargets,
7563                _: Option<&str>,
7564            ) -> auth::error::Result<PermissionResp> {
7565                panic!("check_permission_with_table_targets should be skipped on precheck Allow")
7566            }
7567        }
7568
7569        let plugins = Plugins::new();
7570        plugins.insert::<PermissionCheckerRef>(Arc::new(PrecheckAllowChecker));
7571        let catalog =
7572            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
7573        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
7574        let instance =
7575            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
7576        counting_catalog.reset_counts();
7577
7578        instance
7579            .check_resolved_table_permission(
7580                &test_query_ctx(1),
7581                PermissionReq::Action(PROMQL_QUERY),
7582                PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
7583                    "greptime", "public", "target",
7584                )]),
7585            )
7586            .await
7587            .unwrap();
7588        assert_eq!(0, counting_catalog.total_table_lookups());
7589        Ok(())
7590    }
7591
7592    #[tokio::test]
7593    async fn test_precheck_reject_skips_catalog_lookups() -> TestResult<()> {
7594        struct PrecheckRejectChecker;
7595        impl PermissionChecker for PrecheckRejectChecker {
7596            fn check_permission(
7597                &self,
7598                _: UserInfoRef,
7599                _: PermissionReq,
7600            ) -> auth::error::Result<PermissionResp> {
7601                Ok(PermissionResp::Allow)
7602            }
7603
7604            fn precheck_table_targets(
7605                &self,
7606                _: UserInfoRef,
7607                req: PermissionReq,
7608                targets: &PermissionTableTargets,
7609                _: Option<&str>,
7610            ) -> auth::error::Result<TableTargetPrecheck> {
7611                Ok(match (req, targets) {
7612                    (PermissionReq::Action(COPY_TO), PermissionTableTargets::Resolved(_)) => {
7613                        TableTargetPrecheck::Allow
7614                    }
7615                    _ => TableTargetPrecheck::Reject,
7616                })
7617            }
7618
7619            fn check_permission_with_table_targets(
7620                &self,
7621                _: UserInfoRef,
7622                _: PermissionReq,
7623                _: PermissionTableTargets,
7624                _: Option<&str>,
7625            ) -> auth::error::Result<PermissionResp> {
7626                panic!("check_permission_with_table_targets should be skipped on precheck Reject")
7627            }
7628        }
7629
7630        let plugins = Plugins::new();
7631        plugins.insert::<PermissionCheckerRef>(Arc::new(PrecheckRejectChecker));
7632        let catalog =
7633            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
7634        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
7635        let instance =
7636            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
7637        counting_catalog.reset_counts();
7638
7639        let err = instance
7640            .check_resolved_table_permission(
7641                &test_query_ctx(1),
7642                PermissionReq::Action(PROMQL_QUERY),
7643                PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
7644                    "greptime", "public", "target",
7645                )]),
7646            )
7647            .await
7648            .unwrap_err();
7649        assert!(matches!(err, Error::Permission { .. }));
7650        assert_eq!(StatusCode::PermissionDenied, err.status_code());
7651        // A plugin can construct the public variant with an incomplete target.
7652        let err = instance
7653            .check_resolved_table_permission(
7654                &test_query_ctx(1),
7655                PermissionReq::Action(COPY_TO),
7656                PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
7657                    "greptime", "public", "",
7658                )]),
7659            )
7660            .await
7661            .unwrap_err();
7662        assert_eq!(StatusCode::PermissionDenied, err.status_code());
7663        let err = instance
7664            .check_sql_permission(
7665                &parse_one_sql("COPY target TO '/unused.parquet'"),
7666                &test_query_ctx(1),
7667            )
7668            .await
7669            .unwrap_err();
7670        assert_eq!(StatusCode::PermissionDenied, err.status_code());
7671        assert_eq!(0, counting_catalog.total_table_lookups());
7672        Ok(())
7673    }
7674
7675    #[tokio::test]
7676    async fn test_precheck_partial_indices_only_resolves_listed_targets() -> TestResult<()> {
7677        struct PartialPrecheckChecker(std::sync::Mutex<Vec<PermissionTableTargets>>);
7678        impl PermissionChecker for PartialPrecheckChecker {
7679            fn check_permission(
7680                &self,
7681                _: UserInfoRef,
7682                _: PermissionReq,
7683            ) -> auth::error::Result<PermissionResp> {
7684                Ok(PermissionResp::Allow)
7685            }
7686
7687            fn precheck_table_targets(
7688                &self,
7689                _: UserInfoRef,
7690                _: PermissionReq,
7691                targets: &PermissionTableTargets,
7692                _: Option<&str>,
7693            ) -> auth::error::Result<TableTargetPrecheck> {
7694                let PermissionTableTargets::Resolved(targets) = targets else {
7695                    return Ok(TableTargetPrecheck::Reject);
7696                };
7697                if targets.len() == 2 {
7698                    Ok(TableTargetPrecheck::NeedsPhysicalResolution(vec![1]))
7699                } else {
7700                    Ok(TableTargetPrecheck::Allow)
7701                }
7702            }
7703
7704            fn check_permission_with_table_targets(
7705                &self,
7706                _: UserInfoRef,
7707                _: PermissionReq,
7708                targets: PermissionTableTargets,
7709                _: Option<&str>,
7710            ) -> auth::error::Result<PermissionResp> {
7711                self.0.lock().unwrap().push(targets);
7712                Ok(PermissionResp::Allow)
7713            }
7714        }
7715
7716        let checker = Arc::new(PartialPrecheckChecker(Default::default()));
7717        let plugins = Plugins::new();
7718        plugins.insert::<PermissionCheckerRef>(checker.clone());
7719        let catalog =
7720            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "wide")?);
7721        catalog
7722            .register_table_sync(catalog::RegisterTableRequest {
7723                catalog: "greptime".to_string(),
7724                schema: "public".to_string(),
7725                table_name: "narrow".to_string(),
7726                table_id: 1025,
7727                table: test_physical_table(1025, "narrow")?,
7728            })
7729            .with_context(|_| RegisterTableSnafu {
7730                table_name: "narrow".to_string(),
7731            })?;
7732        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
7733        let instance =
7734            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
7735        counting_catalog.reset_counts();
7736
7737        instance
7738            .check_resolved_table_permission(
7739                &test_query_ctx(1),
7740                PermissionReq::Action(PROMQL_QUERY),
7741                PermissionTableTargets::resolved(vec![
7742                    PermissionTableTarget::new("greptime", "public", "wide"),
7743                    PermissionTableTarget::new("greptime", "public", "narrow"),
7744                ]),
7745            )
7746            .await
7747            .unwrap();
7748        assert_eq!(1, counting_catalog.table_calls());
7749        assert_eq!(0, counting_catalog.table_id_calls());
7750        assert_eq!(0, counting_catalog.table_info_by_id_calls());
7751        assert_eq!(
7752            *checker.0.lock().unwrap(),
7753            vec![PermissionTableTargets::Resolved(vec![
7754                PermissionTableTarget::new("greptime", "public", "wide"),
7755                PermissionTableTarget::new("greptime", "public", "narrow")
7756                    .with_physical_metric_table(true),
7757            ])]
7758        );
7759        Ok(())
7760    }
7761
7762    #[tokio::test]
7763    async fn test_precheck_runs_once_for_multi_chunk_resolution() -> TestResult<()> {
7764        struct MultiChunkPrecheckChecker {
7765            precheck_calls: std::sync::Mutex<Vec<PermissionTableTargets>>,
7766            final_calls: std::sync::Mutex<Vec<PermissionTableTargets>>,
7767        }
7768        impl PermissionChecker for MultiChunkPrecheckChecker {
7769            fn check_permission(
7770                &self,
7771                _: UserInfoRef,
7772                _: PermissionReq,
7773            ) -> auth::error::Result<PermissionResp> {
7774                Ok(PermissionResp::Allow)
7775            }
7776
7777            fn precheck_table_targets(
7778                &self,
7779                _: UserInfoRef,
7780                _: PermissionReq,
7781                targets: &PermissionTableTargets,
7782                _: Option<&str>,
7783            ) -> auth::error::Result<TableTargetPrecheck> {
7784                self.precheck_calls.lock().unwrap().push(targets.clone());
7785                let PermissionTableTargets::Resolved(targets) = targets else {
7786                    return Ok(TableTargetPrecheck::Reject);
7787                };
7788                Ok(TableTargetPrecheck::NeedsPhysicalResolution(
7789                    (0..targets.len()).collect(),
7790                ))
7791            }
7792
7793            fn check_permission_with_table_targets(
7794                &self,
7795                _: UserInfoRef,
7796                _: PermissionReq,
7797                targets: PermissionTableTargets,
7798                _: Option<&str>,
7799            ) -> auth::error::Result<PermissionResp> {
7800                self.final_calls.lock().unwrap().push(targets);
7801                Ok(PermissionResp::Allow)
7802            }
7803        }
7804
7805        let checker = Arc::new(MultiChunkPrecheckChecker {
7806            precheck_calls: Default::default(),
7807            final_calls: Default::default(),
7808        });
7809        let plugins = Plugins::new();
7810        plugins.insert::<PermissionCheckerRef>(checker.clone());
7811        let catalog =
7812            catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(1024, "t0")?);
7813        let mut targets = vec![PermissionTableTarget::new("greptime", "public", "t0")];
7814        for i in 1..10u32 {
7815            let name = format!("t{i}");
7816            catalog
7817                .register_table_sync(catalog::RegisterTableRequest {
7818                    catalog: "greptime".to_string(),
7819                    schema: "public".to_string(),
7820                    table_name: name.clone(),
7821                    table_id: 1024 + i,
7822                    table: test_table(1024 + i, &name)?,
7823                })
7824                .with_context(|_| RegisterTableSnafu { table_name: name })?;
7825            targets.push(PermissionTableTarget::new(
7826                "greptime",
7827                "public",
7828                format!("t{i}"),
7829            ));
7830        }
7831        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
7832        let instance =
7833            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
7834        counting_catalog.reset_counts();
7835
7836        let mut request_targets = targets.clone();
7837        request_targets.push(targets[0].clone());
7838        instance
7839            .check_resolved_table_permission(
7840                &test_query_ctx(1),
7841                PermissionReq::Action(PROMQL_QUERY),
7842                PermissionTableTargets::resolved(request_targets),
7843            )
7844            .await
7845            .unwrap();
7846        assert_eq!(10, counting_catalog.table_calls());
7847        assert_eq!(0, counting_catalog.table_id_calls());
7848        assert_eq!(0, counting_catalog.table_info_by_id_calls());
7849
7850        let precheck_calls = checker.precheck_calls.lock().unwrap();
7851        assert_eq!(1, precheck_calls.len());
7852        assert_eq!(
7853            PermissionTableTargets::Resolved(targets.clone()),
7854            precheck_calls[0]
7855        );
7856
7857        let mut expected_final = targets;
7858        expected_final[0].is_physical_metric_table = true;
7859        let final_calls = checker.final_calls.lock().unwrap();
7860        assert_eq!(1, final_calls.len());
7861        assert_eq!(
7862            PermissionTableTargets::Resolved(expected_final),
7863            final_calls[0]
7864        );
7865        Ok(())
7866    }
7867
7868    #[tokio::test]
7869    async fn test_target_independent_checker_preserves_target_hook_without_lookups()
7870    -> TestResult<()> {
7871        struct EndpointHookChecker {
7872            target_hook_calls: atomic::AtomicUsize,
7873        }
7874        impl PermissionChecker for EndpointHookChecker {
7875            fn check_permission(
7876                &self,
7877                _: UserInfoRef,
7878                _: PermissionReq,
7879            ) -> auth::error::Result<PermissionResp> {
7880                Ok(PermissionResp::Allow)
7881            }
7882
7883            fn uses_table_targets(&self) -> bool {
7884                false
7885            }
7886
7887            fn check_permission_with_table_targets(
7888                &self,
7889                _: UserInfoRef,
7890                _: PermissionReq,
7891                _: PermissionTableTargets,
7892                _: Option<&str>,
7893            ) -> auth::error::Result<PermissionResp> {
7894                self.target_hook_calls
7895                    .fetch_add(1, atomic::Ordering::Relaxed);
7896                Ok(PermissionResp::Reject)
7897            }
7898        }
7899
7900        let checker = Arc::new(EndpointHookChecker {
7901            target_hook_calls: atomic::AtomicUsize::new(0),
7902        });
7903        let plugins = Plugins::new();
7904        plugins.insert::<PermissionCheckerRef>(checker.clone());
7905        let catalog =
7906            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
7907        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
7908        let instance =
7909            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
7910        counting_catalog.reset_counts();
7911
7912        let err = instance
7913            .check_resolved_table_permission(
7914                &test_query_ctx(1),
7915                PermissionReq::Action(PROMQL_QUERY),
7916                PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
7917                    "greptime", "public", "target",
7918                )]),
7919            )
7920            .await
7921            .unwrap_err();
7922        assert_eq!(StatusCode::PermissionDenied, err.status_code());
7923        assert_eq!(0, counting_catalog.total_table_lookups());
7924        assert_eq!(1, checker.target_hook_calls.load(atomic::Ordering::Relaxed));
7925        Ok(())
7926    }
7927
7928    #[tokio::test]
7929    async fn test_precheck_out_of_bounds_index_returns_internal_error() -> TestResult<()> {
7930        struct BadIndexChecker;
7931        impl PermissionChecker for BadIndexChecker {
7932            fn check_permission(
7933                &self,
7934                _: UserInfoRef,
7935                _: PermissionReq,
7936            ) -> auth::error::Result<PermissionResp> {
7937                Ok(PermissionResp::Allow)
7938            }
7939
7940            fn precheck_table_targets(
7941                &self,
7942                _: UserInfoRef,
7943                _: PermissionReq,
7944                _: &PermissionTableTargets,
7945                _: Option<&str>,
7946            ) -> auth::error::Result<TableTargetPrecheck> {
7947                Ok(TableTargetPrecheck::NeedsPhysicalResolution(vec![99]))
7948            }
7949
7950            fn check_permission_with_table_targets(
7951                &self,
7952                _: UserInfoRef,
7953                _: PermissionReq,
7954                _: PermissionTableTargets,
7955                _: Option<&str>,
7956            ) -> auth::error::Result<PermissionResp> {
7957                unreachable!("must fail before check_permission_with_table_targets")
7958            }
7959        }
7960
7961        let plugins = Plugins::new();
7962        plugins.insert::<PermissionCheckerRef>(Arc::new(BadIndexChecker));
7963        let catalog =
7964            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
7965        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
7966        let instance =
7967            test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
7968        counting_catalog.reset_counts();
7969        let ctx = test_query_ctx(1);
7970
7971        for targets in [
7972            PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
7973                "greptime", "public", "target",
7974            )]),
7975            PermissionTableTargets::Unresolved,
7976        ] {
7977            let err = instance
7978                .check_resolved_table_permission(&ctx, PermissionReq::Action(PROMQL_QUERY), targets)
7979                .await
7980                .unwrap_err();
7981            assert!(matches!(err, Error::Permission { .. }));
7982            assert_eq!(StatusCode::Unexpected, err.status_code());
7983            assert_eq!(0, counting_catalog.total_table_lookups());
7984        }
7985        Ok(())
7986    }
7987
7988    #[tokio::test]
7989    async fn test_check_sql_permission_normalizes_unquoted_and_preserves_quoted() -> TestResult<()>
7990    {
7991        struct RecordingPhysicalChecker {
7992            resolved_targets: std::sync::Mutex<Vec<PermissionTableTargets>>,
7993        }
7994
7995        impl PermissionChecker for RecordingPhysicalChecker {
7996            fn check_permission(
7997                &self,
7998                _: UserInfoRef,
7999                _: PermissionReq,
8000            ) -> auth::error::Result<PermissionResp> {
8001                Ok(PermissionResp::Allow)
8002            }
8003
8004            fn precheck_table_targets(
8005                &self,
8006                _: UserInfoRef,
8007                _: PermissionReq,
8008                targets: &PermissionTableTargets,
8009                _: Option<&str>,
8010            ) -> auth::error::Result<TableTargetPrecheck> {
8011                let PermissionTableTargets::Resolved(targets) = targets else {
8012                    return Ok(TableTargetPrecheck::Reject);
8013                };
8014                Ok(TableTargetPrecheck::NeedsPhysicalResolution(
8015                    (0..targets.len()).collect(),
8016                ))
8017            }
8018
8019            fn check_permission_with_table_targets(
8020                &self,
8021                _: UserInfoRef,
8022                _: PermissionReq,
8023                targets: PermissionTableTargets,
8024                _: Option<&str>,
8025            ) -> auth::error::Result<PermissionResp> {
8026                let denied = matches!(
8027                    &targets,
8028                    PermissionTableTargets::Resolved(list)
8029                        if list.iter().any(|t| t.schema == "public" && t.table == "readings")
8030                );
8031                self.resolved_targets.lock().unwrap().push(targets);
8032                Ok(if denied {
8033                    PermissionResp::Reject
8034                } else {
8035                    PermissionResp::Allow
8036                })
8037            }
8038        }
8039
8040        let checker = Arc::new(RecordingPhysicalChecker {
8041            resolved_targets: Default::default(),
8042        });
8043        let plugins = Plugins::new();
8044        plugins.insert::<PermissionCheckerRef>(checker.clone());
8045
8046        let catalog = catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(
8047            1024, "readings",
8048        )?);
8049        catalog
8050            .register_table_sync(catalog::RegisterTableRequest {
8051                catalog: "greptime".to_string(),
8052                schema: "public".to_string(),
8053                table_name: "Readings".to_string(),
8054                table_id: 1025,
8055                table: test_table(1025, "Readings")?,
8056            })
8057            .with_context(|_| RegisterTableSnafu {
8058                table_name: "Readings".to_string(),
8059            })?;
8060        let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
8061        let instance = test_instance_with_counting_catalog(counting_catalog, plugins).await?;
8062        let ctx = test_query_ctx(1);
8063
8064        // Both unquoted spellings resolve to `readings`, look up the physical table `readings`,
8065        // and receive the same PermissionDenied decision.
8066        for sql in [
8067            "SELECT * FROM readings",
8068            "SELECT * FROM Readings",
8069            "SELECT * FROM Public.Readings",
8070        ] {
8071            let err = instance
8072                .check_sql_permission(&parse_one_sql(sql), &ctx)
8073                .await
8074                .unwrap_err();
8075            assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{sql}");
8076        }
8077
8078        // Quoted `"Readings"` preserves case, looks up non-physical `"Readings"`, and is allowed.
8079        instance
8080            .check_sql_permission(&parse_one_sql(r#"SELECT * FROM "Readings""#), &ctx)
8081            .await
8082            .unwrap();
8083
8084        // TQL metric names stay case-sensitive.
8085        instance
8086            .check_sql_permission(&parse_one_sql("TQL EVAL (0, 10, '5s') Readings"), &ctx)
8087            .await
8088            .unwrap();
8089
8090        let recorded = checker.resolved_targets.lock().unwrap();
8091        assert_eq!(
8092            *recorded,
8093            vec![
8094                PermissionTableTargets::Resolved(vec![
8095                    PermissionTableTarget::new("greptime", "public", "readings")
8096                        .with_physical_metric_table(true),
8097                ]),
8098                PermissionTableTargets::Resolved(vec![
8099                    PermissionTableTarget::new("greptime", "public", "readings")
8100                        .with_physical_metric_table(true),
8101                ]),
8102                PermissionTableTargets::Resolved(vec![
8103                    PermissionTableTarget::new("greptime", "public", "readings")
8104                        .with_physical_metric_table(true),
8105                ]),
8106                PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
8107                    "greptime", "public", "Readings"
8108                )]),
8109                PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
8110                    "greptime", "public", "Readings"
8111                )]),
8112            ]
8113        );
8114        Ok(())
8115    }
8116
8117    #[tokio::test]
8118    async fn test_create_flow_sink_permission_preserves_checker_errors() -> TestResult<()> {
8119        #[derive(Clone)]
8120        enum SinkCreateMode {
8121            Deny,
8122            InternalError,
8123            BackendError,
8124            DenyOnResultView,
8125            ErrorOnResultView,
8126        }
8127
8128        struct FlowSinkChecker {
8129            mode: std::sync::Mutex<SinkCreateMode>,
8130        }
8131
8132        impl PermissionChecker for FlowSinkChecker {
8133            fn check_permission(
8134                &self,
8135                _: UserInfoRef,
8136                _: PermissionReq,
8137            ) -> auth::error::Result<PermissionResp> {
8138                Ok(PermissionResp::Allow)
8139            }
8140
8141            fn grpc_table_targets(
8142                &self,
8143                request: &Request,
8144                _catalog: &str,
8145                _schema: &str,
8146            ) -> PermissionTableTargets {
8147                match request {
8148                    Request::Ddl(ddl)
8149                        if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
8150                    {
8151                        PermissionTableTargets::resolved(vec![])
8152                    }
8153                    _ => PermissionTableTargets::Unresolved,
8154                }
8155            }
8156
8157            fn check_permission_with_table_targets(
8158                &self,
8159                _: UserInfoRef,
8160                req: PermissionReq,
8161                targets: PermissionTableTargets,
8162                _: Option<&str>,
8163            ) -> auth::error::Result<PermissionResp> {
8164                let PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req else {
8165                    return Ok(PermissionResp::Allow);
8166                };
8167                let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr else {
8168                    return Ok(PermissionResp::Allow);
8169                };
8170                let _ = targets;
8171                match self.mode.lock().unwrap().clone() {
8172                    SinkCreateMode::Deny => Ok(PermissionResp::Reject),
8173                    SinkCreateMode::InternalError => auth::error::InternalStateSnafu {
8174                        msg: "checker internal failure",
8175                    }
8176                    .fail(),
8177                    SinkCreateMode::BackendError => {
8178                        Err::<PermissionResp, _>(BoxedError::new(PlainError::new(
8179                            "auth backend unavailable".to_string(),
8180                            StatusCode::StorageUnavailable,
8181                        )))
8182                        .context(auth::error::AuthBackendSnafu)
8183                    }
8184                    SinkCreateMode::DenyOnResultView => {
8185                        if create_table.table_name.ends_with("_result") {
8186                            Ok(PermissionResp::Reject)
8187                        } else {
8188                            Ok(PermissionResp::Allow)
8189                        }
8190                    }
8191                    SinkCreateMode::ErrorOnResultView => {
8192                        if create_table.table_name.ends_with("_result") {
8193                            auth::error::InternalStateSnafu {
8194                                msg: "result view check failed",
8195                            }
8196                            .fail()
8197                        } else {
8198                            Ok(PermissionResp::Allow)
8199                        }
8200                    }
8201                }
8202            }
8203        }
8204
8205        let checker = Arc::new(FlowSinkChecker {
8206            mode: std::sync::Mutex::new(SinkCreateMode::Deny),
8207        });
8208        let plugins = Plugins::new();
8209        plugins.insert::<PermissionCheckerRef>(checker.clone());
8210
8211        let catalog =
8212            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
8213        let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
8214        let instance = test_instance_with_catalog_manager(
8215            catalog,
8216            test_table(1025, "target")?,
8217            plugins,
8218            None,
8219            executor.clone(),
8220        )
8221        .await?;
8222        let ctx = test_query_ctx(1);
8223
8224        let grpc_create_flow = |name: &str, incremental: bool| {
8225            let mut flow_options = std::collections::HashMap::new();
8226            if incremental {
8227                flow_options.insert("incremental".to_string(), "true".to_string());
8228            }
8229            Request::Ddl(api::v1::DdlRequest {
8230                expr: Some(api::v1::ddl_request::Expr::CreateFlow(
8231                    api::v1::CreateFlowExpr {
8232                        flow_name: name.to_string(),
8233                        source_table_names: vec![api::v1::TableName {
8234                            catalog_name: "greptime".to_string(),
8235                            schema_name: "public".to_string(),
8236                            table_name: "source".to_string(),
8237                        }],
8238                        sink_table_name: Some(api::v1::TableName {
8239                            catalog_name: "greptime".to_string(),
8240                            schema_name: "public".to_string(),
8241                            table_name: "target".to_string(),
8242                        }),
8243                        eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
8244                        sql: "SELECT id, ts FROM source".to_string(),
8245                        flow_options,
8246                        ..Default::default()
8247                    },
8248                )),
8249            })
8250        };
8251
8252        // Denied `table.create` via SQL still submits the flow with `allow_sink_create = false`.
8253        execute_one_sql(
8254            &instance,
8255            "CREATE FLOW sql_denied_sink SINK TO target EVAL INTERVAL '10s' AS SELECT id, ts FROM source",
8256            ctx.clone(),
8257        )
8258        .await?;
8259        // Denied `table.create` via gRPC still submits the flow with `allow_sink_create = false`.
8260        servers::query_handler::grpc::GrpcQueryHandler::do_query(
8261            &instance,
8262            grpc_create_flow("grpc_denied_sink", false),
8263            ctx.clone(),
8264        )
8265        .await
8266        .unwrap();
8267
8268        // Incremental result view denial returns `Ok(false)` instead of `Ok(true)`.
8269        *checker.mode.lock().unwrap() = SinkCreateMode::DenyOnResultView;
8270        assert!(
8271            !instance
8272                .can_create_flow_sinks(
8273                    &ctx,
8274                    "greptime".to_string(),
8275                    "public".to_string(),
8276                    "target".to_string(),
8277                    Some("true"),
8278                    None,
8279                )
8280                .await
8281                .unwrap()
8282        );
8283
8284        {
8285            let mut submitted = executor.submitted.lock().unwrap();
8286            assert_eq!(2, submitted.len());
8287            for task in submitted.drain(..) {
8288                let DdlTask::CreateFlow(flow_task) = task else {
8289                    panic!("expected CreateFlow task");
8290                };
8291                assert!(!flow_task.allow_sink_create);
8292            }
8293        }
8294
8295        // Non-PermissionDenied checker errors must propagate unchanged and submit no DDL task.
8296        for (mode, expected_status) in [
8297            (SinkCreateMode::InternalError, StatusCode::Unexpected),
8298            (SinkCreateMode::BackendError, StatusCode::StorageUnavailable),
8299        ] {
8300            *checker.mode.lock().unwrap() = mode;
8301            let sql_err = instance
8302                .do_query_inner(
8303                    "CREATE FLOW sql_err_sink SINK TO target EVAL INTERVAL '10s' AS SELECT id, ts FROM source",
8304                    ctx.clone(),
8305                )
8306                .await
8307                .remove(0)
8308                .unwrap_err();
8309            assert_eq!(expected_status, sql_err.status_code());
8310
8311            let grpc_err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
8312                &instance,
8313                grpc_create_flow("grpc_err_sink", false),
8314                ctx.clone(),
8315            )
8316            .await
8317            .unwrap_err();
8318            assert_eq!(expected_status, grpc_err.status_code());
8319            assert!(executor.submitted.lock().unwrap().is_empty());
8320        }
8321
8322        // Incremental flow where the second sink probe (`_result` view) fails with a checker error
8323        // also propagates the original error and submits no DDL task.
8324        *checker.mode.lock().unwrap() = SinkCreateMode::ErrorOnResultView;
8325        let probe_err = instance
8326            .can_create_flow_sinks(
8327                &ctx,
8328                "greptime".to_string(),
8329                "public".to_string(),
8330                "target".to_string(),
8331                Some("true"),
8332                None,
8333            )
8334            .await
8335            .unwrap_err();
8336        assert_eq!(StatusCode::Unexpected, probe_err.status_code());
8337
8338        let grpc_err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
8339            &instance,
8340            grpc_create_flow("grpc_err_result", true),
8341            ctx,
8342        )
8343        .await
8344        .unwrap_err();
8345        assert_eq!(StatusCode::Unexpected, grpc_err.status_code());
8346        assert!(executor.submitted.lock().unwrap().is_empty());
8347
8348        Ok(())
8349    }
8350
8351    #[tokio::test]
8352    async fn test_grpc_create_flow_qualifies_sink_once() -> TestResult<()> {
8353        struct RecordingSinkChecker {
8354            checked_sinks: std::sync::Mutex<Vec<(String, String, String)>>,
8355        }
8356
8357        impl PermissionChecker for RecordingSinkChecker {
8358            fn check_permission(
8359                &self,
8360                _: UserInfoRef,
8361                _: PermissionReq,
8362            ) -> auth::error::Result<PermissionResp> {
8363                Ok(PermissionResp::Allow)
8364            }
8365
8366            fn grpc_table_targets(
8367                &self,
8368                request: &Request,
8369                _catalog: &str,
8370                _schema: &str,
8371            ) -> PermissionTableTargets {
8372                match request {
8373                    Request::Ddl(ddl)
8374                        if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
8375                    {
8376                        PermissionTableTargets::resolved(vec![])
8377                    }
8378                    _ => PermissionTableTargets::Unresolved,
8379                }
8380            }
8381
8382            fn check_permission_with_table_targets(
8383                &self,
8384                _: UserInfoRef,
8385                req: PermissionReq,
8386                targets: PermissionTableTargets,
8387                _: Option<&str>,
8388            ) -> auth::error::Result<PermissionResp> {
8389                if let PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req
8390                    && let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr
8391                {
8392                    let PermissionTableTargets::Resolved(resolved) = &targets else {
8393                        panic!("expected resolved sink target");
8394                    };
8395                    assert_eq!(1, resolved.len());
8396                    assert_eq!(resolved[0].catalog, create_table.catalog_name);
8397                    assert_eq!(resolved[0].schema, create_table.schema_name);
8398                    assert_eq!(resolved[0].table, create_table.table_name);
8399                    self.checked_sinks.lock().unwrap().push((
8400                        create_table.catalog_name.clone(),
8401                        create_table.schema_name.clone(),
8402                        create_table.table_name.clone(),
8403                    ));
8404                }
8405                Ok(PermissionResp::Allow)
8406            }
8407        }
8408
8409        let checker = Arc::new(RecordingSinkChecker {
8410            checked_sinks: Default::default(),
8411        });
8412        let plugins = Plugins::new();
8413        plugins.insert::<PermissionCheckerRef>(checker.clone());
8414
8415        let catalog =
8416            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
8417        let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
8418        let instance = test_instance_with_catalog_manager(
8419            catalog,
8420            test_table(1025, "target")?,
8421            plugins,
8422            None,
8423            executor.clone(),
8424        )
8425        .await?;
8426
8427        let ctx = QueryContextBuilder::default()
8428            .current_catalog("greptime".to_string())
8429            .current_schema("analytics".to_string())
8430            .build()
8431            .into();
8432
8433        for (flow_name, sink_catalog, sink_schema, sink_table) in [
8434            ("flow_unqual", "", "", "unqual_sink"),
8435            ("flow_schema_qual", "", "explicit_db", "schema_qual_sink"),
8436            ("flow_full_qual", "other_cat", "other_db", "full_qual_sink"),
8437        ] {
8438            let request = Request::Ddl(api::v1::DdlRequest {
8439                expr: Some(api::v1::ddl_request::Expr::CreateFlow(
8440                    api::v1::CreateFlowExpr {
8441                        flow_name: flow_name.to_string(),
8442                        source_table_names: vec![api::v1::TableName {
8443                            catalog_name: "greptime".to_string(),
8444                            schema_name: "public".to_string(),
8445                            table_name: "source".to_string(),
8446                        }],
8447                        sink_table_name: Some(api::v1::TableName {
8448                            catalog_name: sink_catalog.to_string(),
8449                            schema_name: sink_schema.to_string(),
8450                            table_name: sink_table.to_string(),
8451                        }),
8452                        eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
8453                        sql: "SELECT id, ts FROM greptime.public.source".to_string(),
8454                        ..Default::default()
8455                    },
8456                )),
8457            });
8458            servers::query_handler::grpc::GrpcQueryHandler::do_query(
8459                &instance,
8460                request,
8461                Arc::clone(&ctx),
8462            )
8463            .await
8464            .unwrap();
8465        }
8466
8467        let checked = checker.checked_sinks.lock().unwrap().clone();
8468        assert_eq!(
8469            checked,
8470            vec![
8471                (
8472                    "greptime".to_string(),
8473                    "analytics".to_string(),
8474                    "unqual_sink".to_string(),
8475                ),
8476                (
8477                    "greptime".to_string(),
8478                    "explicit_db".to_string(),
8479                    "schema_qual_sink".to_string(),
8480                ),
8481                (
8482                    "other_cat".to_string(),
8483                    "other_db".to_string(),
8484                    "full_qual_sink".to_string(),
8485                ),
8486            ]
8487        );
8488
8489        let submitted = executor.submitted.lock().unwrap();
8490        assert_eq!(3, submitted.len());
8491        let expected_sinks = [
8492            TableName::new("greptime", "analytics", "unqual_sink"),
8493            TableName::new("greptime", "explicit_db", "schema_qual_sink"),
8494            TableName::new("other_cat", "other_db", "full_qual_sink"),
8495        ];
8496        for (task, expected_sink) in submitted.iter().zip(expected_sinks) {
8497            let DdlTask::CreateFlow(flow_task) = task else {
8498                panic!("expected CreateFlow task");
8499            };
8500            assert_eq!("greptime", flow_task.catalog_name);
8501            assert_eq!(expected_sink, flow_task.sink_table_name);
8502        }
8503
8504        Ok(())
8505    }
8506}