Skip to main content

frontend/instance/
schema_selection.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
15use std::collections::HashSet;
16
17use common_error::ext::{BoxedError, ErrorExt};
18use common_error::status_code::StatusCode;
19use common_query::Output;
20use common_telemetry::{debug, warn};
21use session::context::{Channel, QueryContextRef};
22use session::table_name::table_idents_to_full_name;
23use snafu::{IntoError, ResultExt};
24use sql::ast::ObjectNamePartExt;
25use sql::statements::copy::{Copy, CopyDatabase};
26use sql::statements::statement::Statement;
27use sql::util::extract_tables_from_statement_checked;
28
29use crate::error::{
30    Error, ExternalSnafu, InvalidSqlSnafu, PermissionSnafu, Result, TableOperationSnafu,
31};
32use crate::instance::Instance;
33
34impl Instance {
35    /// Filters unauthorized candidates before selecting an existing schema.
36    pub(crate) async fn set_search_path(
37        &self,
38        schemas: Vec<String>,
39        query_ctx: QueryContextRef,
40    ) -> Result<Output> {
41        let mut authorized = Vec::with_capacity(schemas.len());
42        let provider = self.plugins.get::<auth::UserProviderRef>();
43        let user = query_ctx.current_user();
44        for schema in schemas {
45            let schema = if schema == "$user" {
46                user.username().to_string()
47            } else {
48                schema
49            };
50            if schema.is_empty() {
51                continue;
52            }
53            if let Some(provider) = &provider {
54                match provider
55                    .authorize(query_ctx.current_catalog(), &schema, &user)
56                    .await
57                {
58                    Ok(()) => {}
59                    Err(error)
60                        if matches!(
61                            error.status_code(),
62                            StatusCode::PermissionDenied | StatusCode::AccessDenied
63                        ) =>
64                    {
65                        debug!(user = user.username(), protocol = %query_ctx.channel(),
66                            catalog = query_ctx.current_catalog(), schema = %schema,
67                            process_id = query_ctx.process_id(), reason = %error.status_code(),
68                            "Skipping unauthorized search_path candidate");
69                        continue;
70                    }
71                    Err(error) => return Err(error).context(PermissionSnafu),
72                }
73            }
74            authorized.push(schema);
75        }
76        self.statement_executor
77            .set_search_path(authorized, query_ctx)
78            .await
79            .context(TableOperationSnafu)
80    }
81
82    /// Authorizes an explicit database access without changing the session.
83    pub(crate) async fn authorize_database(
84        &self,
85        catalog: &str,
86        schema: &str,
87        query_ctx: &QueryContextRef,
88    ) -> Result<()> {
89        let Some(provider) = self.plugins.get::<auth::UserProviderRef>() else {
90            return Ok(());
91        };
92        let user = query_ctx.current_user();
93        if let Err(error) = provider.authorize(catalog, schema, &user).await {
94            if matches!(
95                error.status_code(),
96                StatusCode::PermissionDenied | StatusCode::AccessDenied
97            ) {
98                warn!(user = user.username(), protocol = %query_ctx.channel(), catalog, schema,
99                    previous_schema = %query_ctx.current_schema(), process_id = query_ctx.process_id(),
100                    reason = %error.status_code(), "Database access denied");
101            }
102            return Err(error).context(PermissionSnafu);
103        }
104        Ok(())
105    }
106
107    /// Checks explicit targets before planning when no default scope is authorized.
108    pub(crate) async fn check_unselected_mysql_database(
109        &self,
110        stmt: &Statement,
111        query_ctx: &QueryContextRef,
112    ) -> Result<()> {
113        if query_ctx.channel() != Channel::Mysql || !query_ctx.current_schema().is_empty() {
114            return Ok(());
115        }
116        for (catalog, schema) in resolve_mysql_database_scopes(stmt, query_ctx)? {
117            self.authorize_database(&catalog, &schema, query_ctx)
118                .await?;
119        }
120        Ok(())
121    }
122}
123
124fn resolve_mysql_database_scopes(
125    stmt: &Statement,
126    query_ctx: &QueryContextRef,
127) -> Result<HashSet<(String, String)>> {
128    let mut stmt = stmt;
129    while let Statement::Explain(explain) = stmt {
130        stmt = &explain.statement;
131    }
132    let mut scopes = HashSet::new();
133    let tables = extract_tables_from_statement_checked(stmt).ok_or_else(no_database_selected)?;
134    for table in tables {
135        let (catalog, schema, _) = table_idents_to_full_name(&table, query_ctx)
136            .map_err(BoxedError::new)
137            .context(ExternalSnafu)?;
138        if schema.is_empty() {
139            return Err(no_database_selected());
140        }
141        scopes.insert((catalog, schema));
142    }
143    if let Some(scope) = resolve_statement_database_scope(stmt, query_ctx)? {
144        scopes.insert(scope);
145    }
146    if scopes.is_empty()
147        && !matches!(
148            stmt,
149            Statement::Query(_)
150                | Statement::Use(_)
151                | Statement::SetVariables(_)
152                | Statement::ShowVariables(_)
153                | Statement::ShowDatabases(_)
154                | Statement::ShowCharset(_)
155                | Statement::ShowCollation(_)
156                | Statement::ShowStatus(_)
157                | Statement::ShowProcesslist(_)
158                | Statement::Kill(_)
159        )
160    {
161        return Err(no_database_selected());
162    }
163    Ok(scopes)
164}
165
166fn resolve_statement_database_scope(
167    stmt: &Statement,
168    query_ctx: &QueryContextRef,
169) -> Result<Option<(String, String)>> {
170    let database = match stmt {
171        Statement::ShowTables(show) => Some(show.database.as_deref()),
172        Statement::ShowTableStatus(show) => Some(show.database.as_deref()),
173        Statement::ShowViews(show) => Some(show.database.as_deref()),
174        _ => None,
175    };
176    if let Some(database) = database {
177        let schema = database
178            .filter(|schema| !schema.is_empty())
179            .ok_or_else(no_database_selected)?;
180        return Ok(Some((
181            query_ctx.current_catalog().to_string(),
182            schema.to_string(),
183        )));
184    }
185    let name = match stmt {
186        Statement::CreateDatabase(create) => &create.name,
187        Statement::AlterDatabase(alter) => alter.database_name(),
188        Statement::DropDatabase(drop) => drop.name(),
189        Statement::ShowCreateDatabase(show) => &show.database_name,
190        Statement::Copy(Copy::CopyDatabase(copy)) => match copy {
191            CopyDatabase::To(args) | CopyDatabase::From(args) => &args.database_name,
192        },
193        _ => return Ok(None),
194    };
195    let scope = match &name.0[..] {
196        [schema] => (
197            query_ctx.current_catalog().to_string(),
198            schema.to_string_unquoted(),
199        ),
200        [catalog, schema] => (catalog.to_string_unquoted(), schema.to_string_unquoted()),
201        _ => {
202            return InvalidSqlSnafu {
203                err_msg: format!("Invalid database name: {name}"),
204            }
205            .fail();
206        }
207    };
208    if scope.1.is_empty() {
209        return Err(no_database_selected());
210    }
211    Ok(Some(scope))
212}
213
214fn no_database_selected() -> Error {
215    ExternalSnafu.into_error(BoxedError::new(
216        session::SessionError::NoDatabaseSelected {},
217    ))
218}