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