From 0d75655ed619fde9b6a10a89ec5f62d57e2ca09d Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 4 Nov 2026 12:14:51 +0800 Subject: [PATCH] feat(promql): bound metric discovery by the caller's table grants (#10107) Discovery enumerates the schema's logical metric tables, which is a wider read than a caller's grants necessarily allow. The frontend now answers "which of these may this request see" before the planner touches the catalog, and the planner filters on that answer rather than on its own enumeration. The scope is process-local state on the query context, skipped by the builder the same way the other local-only fields are: a remote node must not receive a scope that widens what it may read. It defaults to `Unavailable`, so a path that did not prepare authorization cannot discover, and the validator turns "should have been set and was not" into an internal error instead of a silent unfiltered read. The named tables of a mixed query are checked too. The complete extractor answers "no tables at all" when any selector is unresolvable, and that was exactly the selector that made the query enter the discovery branch - so `beta_total{job="api"} or {job="api"}` used to lose `beta_total` from the check. Both the allowed and the unrestricted arms now take the partial answer. A denied metric is skipped rather than failing the query, which is what makes discovery mean "every metric you can see". The split route rejects a query whose name matchers reach a denied table, so the same query answers differently depending on the request header; that difference is stated where the skip is made. The planner's retain runs before any source is prepared, so a denied table's name reaches neither the plan nor an error message. It filters with borrowed keys, one pass to build the set and one lookup per metric. Signed-off-by: discord9 --- src/frontend/src/instance.rs | 250 ++++++++++++++++++++++++- src/query/src/promql/planner/native.rs | 34 +++- src/query/src/promql/planner/test.rs | 52 ++++- src/session/src/context.rs | 44 +++++ src/sql/src/util.rs | 8 + 5 files changed, 375 insertions(+), 13 deletions(-) diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index 59559950aef..97820797580 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -67,6 +67,7 @@ use dashmap::DashMap; use datafusion::dataframe::DataFrame; use datafusion::physical_plan::ExecutionPlan; use datafusion_expr::LogicalPlan; +use futures::TryStreamExt; use futures::{Stream, StreamExt, future}; use lazy_static::lazy_static; use operator::delete::DeleterRef; @@ -75,7 +76,8 @@ use operator::statement::{StatementExecutor, StatementExecutorRef}; use partition::manager::PartitionRuleManagerRef; use pipeline::pipeline_operator::PipelineOperator; use prometheus::HistogramTimer; -use promql_parser::label::Matcher; +use promql_parser::label::{METRIC_NAME, MatchOp, Matcher}; +use promql_parser::util::{ExprVisitor, walk_expr}; use query::QueryEngineRef; use query::metrics::OnDone; use query::parser::{PromQuery, QueryStatement}; @@ -94,7 +96,7 @@ use servers::prometheus_handler::{ ParsedPromQuery, PrometheusHandler, resolve_schema_from_matchers, }; use servers::query_handler::sql::SqlQueryHandler; -use session::context::{Channel, QueryContextRef}; +use session::context::{Channel, MetricDiscoveryScope, QueryContextRef}; use session::table_name::table_idents_to_full_name; use snafu::prelude::*; use sql::ast::ObjectNamePartExt; @@ -104,7 +106,10 @@ use sql::statements::comment::CommentObject; use sql::statements::copy::{CopyDatabase, CopyTable}; use sql::statements::statement::Statement; use sql::statements::tql::Tql; -use sql::util::{extract_tables_from_prom_expr_checked, extract_tables_from_statement_checked}; +use sql::util::{ + extract_tables_from_prom_expr_checked, extract_tables_from_prom_expr_partial, + extract_tables_from_statement_checked, +}; use sqlparser::ast::{AnalyzeFormat, ObjectName}; use table::requests::{OTLP_METRIC_COMPAT_KEY, OTLP_METRIC_COMPAT_PROM}; use tracing::Span; @@ -1438,6 +1443,204 @@ impl Instance { } } +/// What one PromQL expression needs in order to be answered by discovering metrics. +#[derive(Default)] +struct MetricDiscoveryVisitor { + needs_discovery: bool, + /// True only while every selector that names no exact table is one discovery can answer. If + /// any selector is not discoverable, the check must stay unresolved rather than be replaced by + /// a set that silently stops naming a table the query reads. + all_unresolved_are_discoverable: bool, + schemas: HashSet, + current_schema: String, +} + +impl MetricDiscoveryVisitor { + /// Whether this selector is answered by enumerating the schema's metric tables. + /// + /// The planner decides the same thing before it scans anything, and the two answers have to + /// match: this walk authorizes what the planner will scan, so a selector the planner declines + /// must not authorize a whole schema here. It is one function in `query`, called from both. + fn is_discovery_selector(selector: &promql_parser::parser::VectorSelector) -> bool { + query::promql::planner::discovers_metric_name(selector) + } + + fn inspect_selector(&mut self, selector: &promql_parser::parser::VectorSelector) { + let names = selector.matchers.find_matchers(METRIC_NAME); + let exact_name = + selector.name.is_some() || (names.len() == 1 && names[0].op == MatchOp::Equal); + let discover = Self::is_discovery_selector(selector); + if !exact_name { + self.all_unresolved_are_discoverable &= discover; + } + if !discover { + return; + } + self.needs_discovery = true; + let effective_schema = selector + .matchers + .matchers + .iter() + .rev() + .find(|m| { + (m.name == "__schema__" || m.name == "__database__") && m.op == MatchOp::Equal + }) + .map(|m| m.value.clone()) + .unwrap_or_else(|| self.current_schema.clone()); + self.schemas.insert(effective_schema); + } +} + +impl ExprVisitor for MetricDiscoveryVisitor { + type Error = std::convert::Infallible; + + fn pre_visit( + &mut self, + expr: &promql_parser::parser::Expr, + ) -> std::result::Result { + match expr { + promql_parser::parser::Expr::VectorSelector(selector) => { + self.inspect_selector(selector); + } + promql_parser::parser::Expr::MatrixSelector(selector) => { + self.inspect_selector(&selector.vs); + } + _ => {} + } + Ok(true) + } +} + +impl Instance { + /// Bounds the metric tables this request may discover by the caller's grants, before anything + /// reads the catalog. `Unavailable` would make the planner decline discovery entirely, so this + /// always resolves to something explicit. + async fn prepare_metric_discovery_scope( + &self, + expr: &promql_parser::parser::Expr, + query_ctx: &mut QueryContextRef, + ) -> server_error::Result<()> { + // Discovery scope is consumed by the native PromQL route only. The extension + // is deliberately opt-in, matching `native_promql_requested` in query's planner. + if !query_ctx + .extension(query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY) + .is_some_and(|value| value.eq_ignore_ascii_case("true")) + { + Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted); + return Ok(()); + } + let checker = self.plugins.get::(); + if !checker.as_ref().uses_table_targets() { + Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted); + return Ok(()); + } + let mut visitor = MetricDiscoveryVisitor { + needs_discovery: false, + all_unresolved_are_discoverable: true, + schemas: HashSet::new(), + current_schema: query_ctx.current_schema(), + }; + let _ = walk_expr(&mut visitor, expr); + if !visitor.needs_discovery { + return Ok(()); + } + let schemas = visitor.schemas; + let mut allowed = HashSet::new(); + for schema in schemas { + let mut tables = self + .catalog_manager + .tables(query_ctx.current_catalog(), &schema, Some(query_ctx)) + .try_collect::>() + .await + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu)?; + tables.sort_by_key(|table| table.table_info().name.clone()); + for table in tables { + let info = table.table_info(); + if info.meta.engine != store_api::metric_engine_consts::METRIC_ENGINE_NAME + || info.is_physical_table() + { + continue; + } + if info.catalog_name != query_ctx.current_catalog() || info.schema_name != schema { + continue; + } + let target = PermissionTableTarget::new( + query_ctx.current_catalog(), + &schema, + info.name.as_str(), + ); + match checker + .as_ref() + .check_permission_with_table_targets( + query_ctx.current_user(), + PermissionReq::Action(PROMQL_QUERY), + PermissionTableTargets::resolved(vec![target.clone()]), + ) + .context(AuthSnafu) + { + Ok(_) => { + allowed.insert(target); + } + // A rejected metric is skipped rather than failing the query, which is what + // makes discovery mean "every metric you can see": a table the caller cannot + // read is one the expression never mentions, the same way a query naming it + // would be rejected only where it names it. The split route instead rejects a + // query whose name matchers reach a denied table, so the same regex query + // answers with the readable metrics here and with `PermissionDenied` there. + Err(error) + if error.status_code() + == common_error::status_code::StatusCode::PermissionDenied => {} + Err(error) => return Err(error), + } + } + } + Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Allowed(allowed)); + Ok(()) + } + + /// Fails closed: a path that must have set the scope and did not is an internal error, not a + /// silent return to an unfiltered discovery. + fn validate_metric_discovery_scope( + expr: &promql_parser::parser::Expr, + scope: &MetricDiscoveryScope, + ) -> server_error::Result<()> { + let mut visitor = MetricDiscoveryVisitor { + needs_discovery: false, + all_unresolved_are_discoverable: true, + schemas: HashSet::new(), + current_schema: String::new(), + }; + let _ = walk_expr(&mut visitor, expr); + if visitor.needs_discovery && matches!(scope, MetricDiscoveryScope::Unavailable) { + return Err(server_error::Error::Internal { + err_msg: "Metric discovery reached without an authorization scope".to_string(), + }); + } + Ok(()) + } + + /// The statically named tables of an expression, kept even when another selector cannot be + /// resolved. The complete extractor would answer "no tables at all" for that expression and + /// drop these, which is how a mixed query lost the tables it names explicitly. + fn prom_expr_permission_targets_partial( + &self, + expr: &promql_parser::parser::Expr, + query_ctx: &QueryContextRef, + ) -> server_error::Result> { + extract_tables_from_prom_expr_partial(expr) + .into_iter() + .map(|name| { + table_idents_to_full_name(&name, query_ctx).map(|(catalog, schema, table)| { + PermissionTableTarget::new(catalog, schema, table) + }) + }) + .collect::, _>>() + .map_err(BoxedError::new) + .context(ExecuteQuerySnafu) + } +} + #[async_trait] impl PrometheusHandler for Instance { #[tracing::instrument(skip_all)] @@ -1462,8 +1665,47 @@ impl PrometheusHandler for Instance { self.check_prom_query_privilege(&query_ctx)?; - let targets = + let parsed_expr = match query.statement() { + QueryStatement::Promql(eval_stmt, _) => &eval_stmt.expr, + _ => unreachable!("query is parsed from promql"), + }; + // Authorization precedes any catalog read for discovery, so a denied name never reaches + // the plan, an error message, or an output column. + let mut scoped_ctx = query_ctx.clone(); + self.prepare_metric_discovery_scope(parsed_expr, &mut scoped_ctx) + .await?; + let query_ctx = scoped_ctx; + Self::validate_metric_discovery_scope(parsed_expr, query_ctx.metric_discovery_scope())?; + let mut targets = self.prom_queries_permission_targets(std::slice::from_ref(&query), &query_ctx)?; + if matches!(targets, PermissionTableTargets::Unresolved) { + let mut visitor = MetricDiscoveryVisitor { + needs_discovery: false, + all_unresolved_are_discoverable: true, + schemas: HashSet::new(), + current_schema: query_ctx.current_schema(), + }; + let _ = walk_expr(&mut visitor, parsed_expr); + if visitor.needs_discovery && visitor.all_unresolved_are_discoverable { + match query_ctx.metric_discovery_scope() { + MetricDiscoveryScope::Allowed(allowed) => { + let mut resolved = + self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?; + resolved.extend(allowed.iter().cloned()); + targets = PermissionTableTargets::resolved(resolved); + } + // The partial answer, because a selector that cannot be resolved statically + // is what brought the query here: the complete one would answer "no tables", + // dropping the named ones that the same query also reads. + MetricDiscoveryScope::Unrestricted => { + targets = PermissionTableTargets::resolved( + self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?, + ); + } + MetricDiscoveryScope::Unavailable => {} + } + } + } self.check_query_target_permission(targets, &query_ctx) .await?; diff --git a/src/query/src/promql/planner/native.rs b/src/query/src/promql/planner/native.rs index 1688fd97b87..d09729333f4 100644 --- a/src/query/src/promql/planner/native.rs +++ b/src/query/src/promql/planner/native.rs @@ -64,7 +64,7 @@ use promql_parser::parser::{ BinModifier, EvalStmt, Expr as PromExpr, LabelModifier, MatrixSelector, ParenExpr, VectorMatchCardinality, VectorSelector, token, }; -use session::context::QueryContextRef; +use session::context::{MetricDiscoveryScope, QueryContextRef}; use snafu::ResultExt; use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME}; @@ -506,12 +506,44 @@ impl PromPlanner { .schema_name .clone() .unwrap_or_else(|| self.table_provider.query_ctx().current_schema()); + // Authorization is decided before anything is read: a table the caller may not + // see never becomes a source, so its name reaches neither the plan nor an error. + let scope = self.table_provider.query_ctx().metric_discovery_scope(); + if matches!(scope, MetricDiscoveryScope::Unavailable) { + return Ok(None); + } let mut metrics = self .table_provider .logical_metric_tables(&effective_schema) .await .map_err(|error| DataFusionError::External(Box::new(error))) .context(DataFusionPlanningSnafu)?; + if let MetricDiscoveryScope::Allowed(allowed) = scope { + let catalog = self.table_provider.query_ctx().current_catalog(); + // Borrowed keys, so a wide allowlist is one pass to build and one lookup + // per metric rather than a scan of the allowlist for each of them. + let permitted = allowed + .iter() + .map(|target| { + ( + target.catalog.as_str(), + target.schema.as_str(), + target.table.as_str(), + ) + }) + .collect::>(); + metrics.retain(|table| { + let info = table.table_info(); + // Reject metadata that disagrees with where the table was enumerated. + info.catalog_name == catalog + && info.schema_name == effective_schema + && permitted.contains(&( + info.catalog_name.as_str(), + info.schema_name.as_str(), + info.name.as_str(), + )) + }); + } metrics.retain(|table| { name_matchers .iter() diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index 34d5caf0e81..e9023b18ead 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -48,7 +48,7 @@ use promql::extension_plan::{AggregateFinalize, FusedSeries, HistogramFold, RawS use promql::native::plan::NativeExpr; use promql_parser::label::Labels; use promql_parser::parser; -use session::context::QueryContext; +use session::context::{MetricDiscoveryScope, QueryContext}; use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan}; use table::Table; use table::metadata::{FilterPushDownType, TableInfoBuilder, TableMetaBuilder}; @@ -1129,14 +1129,27 @@ async fn build_test_table_provider_with_tsid_tag_fields_and_field_order_and_time .is_ok() ); } + // The scope is what discovery consults before it reads anything, and its default declines, so + // a fixture that wants discovery to run has to say so. + let query_ctx = { + let base = QueryContext::arc(); + let mut ctx = (*base).clone(); + ctx.set_metric_discovery_scope(SCOPE.with(|scope| { + scope + .borrow() + .clone() + .unwrap_or(MetricDiscoveryScope::Unrestricted) + })); + Arc::new(ctx) + }; + DfTableSourceProvider::new(catalog_list, false, query_ctx, DummyDecoder::arc(), false) +} - DfTableSourceProvider::new( - catalog_list, - false, - QueryContext::arc(), - DummyDecoder::arc(), - false, - ) +thread_local! { + /// What the metric fixture's provider reports as the request's discovery scope, so a test can + /// deny a table without rebuilding the catalog. + static SCOPE: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; } /// A schema of logical metric tables, one tag and one field each, all served through the one @@ -2078,6 +2091,29 @@ async fn native_metric_discovery_names_each_metric_where_the_operator_keeps_it() } } +/// The scope is the authority on which of the discovered metrics a caller may see. A denied table +/// never becomes a source, so its name reaches neither the plan nor the answer. +#[tokio::test] +async fn native_metric_discovery_reads_only_what_the_scope_allows() { + SCOPE.with(|scope| { + *scope.borrow_mut() = Some(MetricDiscoveryScope::allowed([( + DEFAULT_CATALOG_NAME.to_string(), + DEFAULT_SCHEMA_NAME.to_string(), + "alpha_total".to_string(), + )])) + }); + let plan = build_native_fused_plan_with_provider( + "{tag_0=\"x\"}", + true, + metric_discovery_provider(&["alpha_total", "beta_total"]).await, + ) + .await; + let formatted = format!("{plan:?}"); + assert!(formatted.contains("alpha_total"), "{formatted}"); + assert!(!formatted.contains("beta_total"), "{formatted}"); + SCOPE.with(|scope| *scope.borrow_mut() = None); +} + /// One input per discovered metric, and each names the metric it reads. #[tokio::test] async fn native_metric_discovery_prepares_one_source_per_metric() { diff --git a/src/session/src/context.rs b/src/session/src/context.rs index 20462933a39..e7dc41b8def 100644 --- a/src/session/src/context.rs +++ b/src/session/src/context.rs @@ -45,6 +45,33 @@ use crate::session_config::{ }; use crate::{MutableInner, ReadPreference}; +/// Which logical metric tables this request's selector may discover, decided by the frontend +/// against the caller's grants. It is process-local authorization state and is never carried by +/// `api::v1::QueryContext`: a remote node must not receive a scope that widens what it may read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum MetricDiscoveryScope { + /// Discovery is unavailable on paths that do not prepare frontend authorization. + #[default] + Unavailable, + /// Every metric table may be discovered. + Unrestricted, + /// Only these tables may be discovered. + Allowed(std::collections::HashSet), +} + +impl MetricDiscoveryScope { + pub fn allowed(targets: impl IntoIterator) -> Self { + Self::Allowed( + targets + .into_iter() + .map(|(catalog, schema, table)| { + auth::PermissionTableTarget::new(catalog, schema, table) + }) + .collect(), + ) + } +} + pub type QueryContextRef = Arc; pub type ConnInfoRef = Arc; @@ -102,6 +129,22 @@ pub struct QueryContext { /// Protocol specific context #[builder(default)] protocol_ctx: ProtocolCtx, + /// Process-local discovery allowlist, set by the frontend before planning. Skipped by the + /// builder for the same reason as `admitted_write`: it is not part of the request's identity. + #[builder(setter(skip))] + metric_discovery_scope: MetricDiscoveryScope, +} + +impl QueryContext { + /// The metric discovery scope this request's frontend authorization produced. + pub fn metric_discovery_scope(&self) -> &MetricDiscoveryScope { + &self.metric_discovery_scope + } + + /// Sets the metric discovery scope for this request. + pub fn set_metric_discovery_scope(&mut self, scope: MetricDiscoveryScope) { + self.metric_discovery_scope = scope; + } } /// This fields hold data that is only valid to current query context @@ -677,6 +720,7 @@ impl QueryContextBuilder { channel, batching_enabled: self.batching_enabled.unwrap_or_default(), admitted_write: None, + metric_discovery_scope: MetricDiscoveryScope::default(), logical_batching_enabled: self.logical_batching_enabled.unwrap_or_default(), process_id: self.process_id.unwrap_or_default(), conn_info: self.conn_info.unwrap_or_default(), diff --git a/src/sql/src/util.rs b/src/sql/src/util.rs index a33c2576bbe..bd6b7be5e7b 100644 --- a/src/sql/src/util.rs +++ b/src/sql/src/util.rs @@ -467,6 +467,14 @@ pub fn extract_tables_from_prom_expr_checked( extract_tables_from_prom_expr(expr, &mut names).then_some(names.into_iter()) } +/// Extracts the tables referenced by a [`PromExpr`] that can be resolved statically, +/// ignoring the ones that cannot. +pub fn extract_tables_from_prom_expr_partial(expr: &PromExpr) -> Vec { + let mut names = HashSet::new(); + extract_tables_from_prom_expr(expr, &mut names); + names.into_iter().collect() +} + fn extract_tables_from_prom_expr(expr: &PromExpr, names: &mut HashSet) -> bool { struct TableCollector<'a> { names: &'a mut HashSet,