This is an automated email from the ASF dual-hosted git repository. villebro pushed a commit to branch 7.0 in repository https://gitbox.apache.org/repos/asf/superset.git
commit 4b3c307e3e3663ca1553fd550afba24177ebdb99 Author: Ville Brofeldt <[email protected]> AuthorDate: Sat Nov 14 11:00:01 2026 -0800 fix(security): preserve Snowflake catalog identity in SQL Lab (#46055) On 7.0 the two engine-spec test files keep 7.0's content and append this commit's own tests. The UPDATING entry goes under 7.0.0 with a lead on the lowercase-alias permission change. The physical-catalog driver test drops its embedded-credential case, which needs master-only apply_embedded_credentials (#45890). (cherry picked from commit 40a037bc440cfc06bb5cf9b8fccf48fadd5e7939) --- UPDATING.md | 23 + superset/db_engine_specs/base.py | 18 + superset/db_engine_specs/snowflake.py | 101 +++- superset/models/core.py | 4 +- superset/security/manager.py | 218 +++++++- superset/sql/parse.py | 12 + tests/unit_tests/db_engine_specs/test_base.py | 19 + tests/unit_tests/db_engine_specs/test_snowflake.py | 603 ++++++++++++++++++++- tests/unit_tests/security/manager_test.py | 14 +- .../security/snowflake_catalog_case_test.py | 561 +++++++++++++++++++ tests/unit_tests/sql/parse_tests.py | 55 +- tests/unit_tests/sql_lab_test.py | 45 ++ 12 files changed, 1649 insertions(+), 24 deletions(-) diff --git a/UPDATING.md b/UPDATING.md index fc62161e684..8dd3c5559a1 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -26,6 +26,29 @@ assists people when migrating to a new version. ## 7.0.0 +- **Snowflake: lowercase catalog aliases need the uppercase permission.** Before + upgrading, check Snowflake datasets and catalog/schema permissions that use a + lowercase alias of an uppercase database (for example `sales` for `SALES`): + users granted only the lowercase alias lose access until they are granted the + uppercase catalog/schema permission and the dataset catalog is updated. + Snowflake default catalogs from unquoted connection-URI identifiers resolve to + uppercase (`sales` becomes `SALES`); double-quoted identifiers preserve case. + Resolved defaults and catalogs selected from listings are quoted when opening + connections, preserving their physical database identity. + Catalog permissions and dataset catalog fields must use the physical database + name. For an uppercase database, update any lowercase catalog aliases stored + on datasets and grant the corresponding uppercase catalog/schema permissions. + Lowercase and mixed-case physical databases remain distinct; their permissions + are not automatically aliased or migrated. A saved catalog equal to the raw + URI identifier remains a legacy alias only when that exact physical catalog + is absent from the database's catalog listing. If both `sales` and `SALES` + exist, `sales` selects the lowercase physical catalog; update legacy rows to + `SALES` to select the uppercase database explicitly. This ambiguous-alias + check uses a fresh listing under the connecting identity (including user + impersonation or embedded guest credentials), independently of the catalog + dropdown cache settings. Resolved defaults and other unambiguous selections + do not require this additional listing. + - **Guest token identities are validated (warn-first).** The `username`, `first_name` and `last_name` in a guest token's `user` claim are expected to be strings of at most 255 characters with no control characters (including tab, diff --git a/superset/db_engine_specs/base.py b/superset/db_engine_specs/base.py index 38492fd0e79..b4c1adfb1b1 100644 --- a/superset/db_engine_specs/base.py +++ b/superset/db_engine_specs/base.py @@ -738,6 +738,14 @@ class BaseEngineSpec: # pylint: disable=too-many-public-methods # Does the DB engine spec support cross-catalog queries? supports_cross_catalog_queries = False + # Are catalog names case-insensitive? When True, a catalog can appear in + # permissions with different cases (eg, the catalog listing returns `SALES` while + # the connection URI says `sales`), and catalog/schema permissions match when only + # the case of the catalog differs. Database and schema names still match exactly. + # Only set this for engines where catalogs that differ only by case are the same + # catalog, otherwise users would be granted access to a different catalog. + case_insensitive_catalogs = False + # Does the DB engine support schemas? When set to False the schema selector is # hidden in the dataset creation UI and schema is not required for table access. supports_schemas = True @@ -2094,6 +2102,16 @@ class BaseEngineSpec: # pylint: disable=too-many-public-methods ) ] + @classmethod + def get_catalog_for_connection( # pylint: disable=unused-argument + cls, + database: Database, + uri: URL, + catalog: str | None, + ) -> str | None: + """Return the selected catalog, allowing engine-specific legacy aliases.""" + return catalog + @classmethod def adjust_engine_params( # pylint: disable=unused-argument cls, diff --git a/superset/db_engine_specs/snowflake.py b/superset/db_engine_specs/snowflake.py index a11a4635bea..365bd404306 100644 --- a/superset/db_engine_specs/snowflake.py +++ b/superset/db_engine_specs/snowflake.py @@ -409,6 +409,50 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec): return extra + @classmethod + def get_catalog_for_connection( + cls, + database: "Database", + uri: URL, + catalog: str | None, + ) -> str | None: + """Prefer an existing physical catalog over an old saved URI alias.""" + uri_catalog = uri.database.split("/", 1)[0] + # Only ambiguous URI aliases require a listing. Listing itself opens an + # engine without a catalog override, so it cannot recurse here. + if catalog and cls._is_legacy_default_catalog(catalog, uri_catalog, set()): + # Classification must bypass the shared dropdown cache: a newly + # created physical name, or another user's visibility, can change + # which database this selection denotes. get_inspector opens under + # the connecting identity (including impersonation/guest fallback), + # not a separate service account. Reuse only within this app context. + if cls._is_legacy_default_catalog( + catalog, uri_catalog, cls._get_connection_catalogs(database) + ): + return None + return catalog + + @staticmethod + def _get_connection_catalogs(database: "Database") -> set[str]: + """ + List physical catalogs under the connecting identity, once per app context. + + A chart query opens an engine to compile and another to execute; an + uncached listing for each costs two extra Snowflake logins apiece. + Flask g scopes reuse to a request or a Celery task, never a shared cache. + """ + from flask import g, has_app_context + + from superset.utils.core import get_username + + if database.id is None or not has_app_context(): + return database.get_all_catalog_names(cache=False) + listings = g.setdefault("_snowflake_connection_catalogs", {}) + key = (database.id, get_username()) + if key not in listings: + listings[key] = database.get_all_catalog_names(cache=False) + return listings[key] + @classmethod def adjust_engine_params( cls, @@ -422,14 +466,31 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec): else: current_catalog, current_schema = uri.database, None + if catalog: + # Catalog arguments are physical names from listings or the resolved + # default, not SQL identifiers. Quote them before reconnecting so a + # case-sensitive catalog cannot become a different uppercase one. + # The driver percent-decodes the database, so encode the quoted name. + current_catalog = parse.quote( + '"' + catalog.replace('"', '""') + '"', + safe='"', + ) + adjusted_database = "/".join( [ - catalog or current_catalog, + current_catalog, schema or current_schema or "", ] ).rstrip("/") uri = uri.set(database=adjusted_database) + if not (schema or current_schema) and "%" in current_catalog: + # snowflake-sqlalchemy only decodes the database when a schema path + # is present. SQLAlchemy applies connect_args after dialect URL args. + connect_args = { + **connect_args, + "database": parse.unquote_plus(current_catalog), + } return uri, connect_args @@ -454,7 +515,43 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec): """ Return the default catalog. """ - return database.url_object.database.split("/")[0] + # Resolve the URI identifier before it becomes a permission name. Catalog + # listings already contain physical names, including case-sensitive ones. + return cls._resolve_catalog_identifier( + database.url_object.database.split("/")[0] + ) + + @staticmethod + def _resolve_catalog_identifier(identifier: str) -> str: + """ + Resolve a URI catalog identifier to the physical database name. + """ + catalog = parse.unquote(identifier) + if catalog.startswith('"') and catalog.endswith('"'): + return catalog[1:-1].replace('""', '"') + return catalog.upper() + + @classmethod + def _is_legacy_default_catalog( + cls, catalog: str, uri_catalog: str, physical_catalogs: set[str] + ) -> bool: + """ + Return True for a catalog stored by earlier versions as the default. + + Those versions stored the URI identifier verbatim (eg, ``sales`` for the + ``SALES`` database), and connected using it unquoted. Keep the URI + identifier for them only when it is not an existing physical catalog. + If both exist, physical identity wins; guessing would cross catalogs. + """ + return ( + catalog + in { + uri_catalog, + parse.unquote(uri_catalog), + } + and catalog != cls._resolve_catalog_identifier(uri_catalog) + and (catalog not in physical_catalogs) + ) @classmethod def get_catalog_names( diff --git a/superset/models/core.py b/superset/models/core.py index 7c4dde4aa9f..13b0d32cc0e 100755 --- a/superset/models/core.py +++ b/superset/models/core.py @@ -702,7 +702,9 @@ class Database(CoreDatabase, AuditMixinNullable, ImportExportMixin): # pylint: sqlalchemy_url, connect_args = self.db_engine_spec.adjust_engine_params( uri=sqlalchemy_url, connect_args=connect_args, - catalog=catalog, + catalog=self.db_engine_spec.get_catalog_for_connection( + self, sqlalchemy_url, catalog + ), schema=schema, ) engine_kwargs["connect_args"] = connect_args diff --git a/superset/security/manager.py b/superset/security/manager.py index b4ce07860fd..e875d48eb17 100644 --- a/superset/security/manager.py +++ b/superset/security/manager.py @@ -262,6 +262,10 @@ def _render_permission_instructions_link( DATABASE_PERM_REGEX = re.compile(r"^\[.+\]\.\(id\:(?P<id>\d+)\)$") +# Permissions whose view menu names include a catalog: ``[database].[catalog]`` and +# ``[database].[catalog].[schema]``. +CATALOG_SCOPED_PERMISSIONS = frozenset({"catalog_access", "schema_access"}) + class DatabaseCatalogSchema(NamedTuple): database: str @@ -2429,6 +2433,116 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods return self.is_item_public(permission_name, view_name) return self._has_view_access(user, permission_name, view_name) + def can_access_catalog_scoped( + self, + database: "Database", + permission_name: str, + view_name: str, + ) -> bool: + """ + Return True if the user holds the catalog or schema permission ``view_name`` + of ``database``. + + On engines with case-insensitive catalog names the permission also matches + when the user's grant spells the catalog in another case. The permission + sync creates catalog permissions from the catalogs listed by the database, + while the default catalog comes from the connection URI; on Snowflake the + former are uppercase and the latter usually lowercase, so the exact check + alone fails even though both name the same catalog. + + :param database: The database the permission belongs to + :param permission_name: ``catalog_access`` or ``schema_access`` + :param view_name: The catalog or schema permission + :returns: Whether the user can access the catalog or schema + """ + if self.can_access(permission_name, view_name): + return True + if not database.db_engine_spec.case_insensitive_catalogs: + return False + + requested = self._parse_catalog_scoped_perm(permission_name, view_name) + if requested is None: + return False + + database_name, catalog, schema = requested + for granted_name in self._get_user_view_menu_names(permission_name): + granted = self._parse_catalog_scoped_perm(permission_name, granted_name) + if ( + granted is not None + and granted[0] == database_name + and granted[2] == schema + and granted[1].upper() == catalog.upper() + ): + return True + + return False + + @staticmethod + def _parse_catalog_scoped_perm( + permission_name: str, + view_menu_name: str, + ) -> tuple[str, str, str | None] | None: + """ + Split a catalog or schema permission into ``(database, catalog, schema)``. + + Returns ``None`` for other permissions, and for the catalog-less + ``[database].[schema]`` form. + """ + if not (view_menu_name.startswith("[") and view_menu_name.endswith("]")): + return None + parts = view_menu_name[1:-1].split("].[") + if permission_name == "catalog_access" and len(parts) == 2: + return parts[0], parts[1], None + if permission_name == "schema_access" and len(parts) == 3: + return parts[0], parts[1], parts[2] + return None + + def _get_case_insensitive_catalog_databases( + self, + database_names: AbstractSet[str], + ) -> dict[str, "Database"]: + """ + Return the databases, among ``database_names``, whose engine has + case-insensitive catalog names, keyed by name. + """ + # pylint: disable=import-outside-toplevel + from superset.commands.database.exceptions import DatabaseInvalidError + from superset.models.core import Database + + if not database_names: + return {} + + databases = {} + for database in self.session.query(Database).filter( + Database.database_name.in_(database_names) + ): + try: + if database.db_engine_spec.case_insensitive_catalogs: + databases[database.database_name] = database + except DatabaseInvalidError: + # unparsable URI: keep matching its permissions exactly + continue + return databases + + def _catalogs_equal( + self, + database: "Database", + catalog: str | None, + other: str | None, + ) -> bool: + """ + Compare two catalog names of a database, ignoring case when the engine's + catalog names are case-insensitive. + """ + if catalog == other: + return True + return bool( + catalog + and other + and database.db_engine_spec.case_insensitive_catalogs + and catalog.upper() == other.upper() + ) + def can_access_all_queries(self) -> bool: """ Return True if the user can access all SQL Lab queries, False otherwise. @@ -2479,7 +2593,14 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods return bool( self.can_access_all_datasources() or self.can_access_database(database) - or (catalog_perm and self.can_access("catalog_access", catalog_perm)) + or ( + catalog_perm + and self.can_access_catalog_scoped( + database, + "catalog_access", + catalog_perm, + ) + ) ) def can_access_schema(self, datasource: "BaseDatasource | Explorable") -> bool: @@ -2524,7 +2645,11 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods return True # Schema-level permission (SQL only) - if self.can_access("schema_access", datasource.schema_perm or ""): + if self.can_access_catalog_scoped( + database, + "schema_access", + datasource.schema_perm or "", + ): return True # Non-SQL explorables don't have schema hierarchy @@ -2894,6 +3019,56 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods return True def user_view_menu_names(self, permission_name: str) -> set[str]: + """ + Return the names of the view menus the user holds ``permission_name`` on. + + Catalog and schema permissions on engines with case-insensitive catalog + names are returned with the catalog in every spelling Superset uses for + it (as listed, upper and lower case, and as the default catalog), so + callers that match them against stored names, eg, the ``schema_perm`` of + datasets, find them regardless of the case. + """ + view_menu_names = self._get_user_view_menu_names(permission_name) + if permission_name in CATALOG_SCOPED_PERMISSIONS: + return self._add_catalog_case_variants(permission_name, view_menu_names) + return view_menu_names + + def _add_catalog_case_variants( + self, + permission_name: str, + view_menu_names: set[str], + ) -> set[str]: + """ + Add the other spellings of the catalog to the catalog/schema permissions of + databases whose engine has case-insensitive catalog names. + """ + parsed = { + name: perm + for name in view_menu_names + if (perm := self._parse_catalog_scoped_perm(permission_name, name)) + } + databases = self._get_case_insensitive_catalog_databases( + {database_name for database_name, _, _ in parsed.values()} + ) + if not databases: + return view_menu_names + + expanded = set(view_menu_names) + for database_name, catalog, schema in parsed.values(): + if database_name not in databases: + continue + spellings = {catalog.upper(), catalog.lower()} + default_catalog = databases[database_name].get_default_catalog() + if default_catalog and default_catalog.upper() == catalog.upper(): + spellings.add(default_catalog) + for spelling in spellings: + if schema is None: + expanded.add(f"[{database_name}].[{spelling}]") + else: + expanded.add(f"[{database_name}].[{spelling}].[{schema}]") + return expanded + + def _get_user_view_menu_names(self, permission_name: str) -> set[str]: base_query = ( self.session.query(self.viewmenu_model.name) .join(self.permissionview_model) @@ -3014,13 +3189,16 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods # [database].[schema] matches when no catalog is specified, or when the user # specifies the default catalog - if len(parts) == 2 and (catalog is None or catalog == default_catalog): + if len(parts) == 2 and ( + catalog is None + or self._catalogs_equal(database, catalog, default_catalog) + ): accessible_schemas.add(parts[1]) # [database].[catalog].[schema] matches when the catalog is equal to the # requested catalog or, when no catalog specified, it's equal to the default # catalog. - elif len(parts) == 3 and parts[1] == catalog: + elif len(parts) == 3 and self._catalogs_equal(database, parts[1], catalog): accessible_schemas.add(parts[2]) # datasource_access @@ -3092,7 +3270,7 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods # datasource_access if perms := self.user_view_menu_names("datasource_access"): tables = ( - self.session.query(SqlaTable.schema) + self.session.query(SqlaTable.catalog) .filter(SqlaTable.database_id == database.id) .filter(or_(SqlaTable.perm.in_(perms))) # type: ignore[union-attr] .distinct() @@ -3105,6 +3283,12 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods } ) + if database.db_engine_spec.case_insensitive_catalogs: + # the candidates come from the catalog listing, while the default + # catalog and the catalog of datasets can be spelled in another case + accessible = {catalog.upper() for catalog in accessible_catalogs} + return {catalog for catalog in catalogs if catalog.upper() in accessible} + return catalogs & accessible_catalogs def get_datasources_accessible_by_user( # pylint: disable=invalid-name @@ -3135,7 +3319,11 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods catalog = catalog or database.get_default_catalog() if catalog: catalog_perm = self.get_catalog_perm(database.database_name, catalog) - if catalog_perm and self.can_access("catalog_access", catalog_perm): + if catalog_perm and self.can_access_catalog_scoped( + database, + "catalog_access", + catalog_perm, + ): return datasource_names if schema: @@ -3144,7 +3332,11 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods catalog, schema, ) - if schema_perm and self.can_access("schema_access", schema_perm): + if schema_perm and self.can_access_catalog_scoped( + database, + "schema_access", + schema_perm, + ): return datasource_names user_perms = self.user_view_menu_names("datasource_access") @@ -5352,7 +5544,11 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods database.database_name, effective_catalog, ) - if catalog_perm and self.can_access("catalog_access", catalog_perm): + if catalog_perm and self.can_access_catalog_scoped( + database, + "catalog_access", + catalog_perm, + ): continue schema_perm = self.get_schema_perm( @@ -5360,7 +5556,11 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods effective_catalog, table_.schema, ) - if schema_perm and self.can_access("schema_access", schema_perm): + if schema_perm and self.can_access_catalog_scoped( + database, + "schema_access", + schema_perm, + ): continue # Under strict scoping, refuse tables whose schema we could diff --git a/superset/sql/parse.py b/superset/sql/parse.py index e9f8a11e87e..86c1b589f59 100644 --- a/superset/sql/parse.py +++ b/superset/sql/parse.py @@ -3059,6 +3059,18 @@ def extract_tables_from_statement( """ Extract all distinct table references in a single statement. """ + if dialect == Dialects.SNOWFLAKE: + # Permissions use physical catalog names. Fold only unquoted SQL inputs, + # before extracting strings and losing the quoting information. Fold the + # statement itself, not a copy: RLS rules are keyed by these tables and + # matched against this AST, so both must spell the catalog the same way. + # Snowflake resolves an unquoted name to uppercase, so the query is + # equivalent. + for source in statement.find_all(exp.Table): + catalog = source.args.get("catalog") + if isinstance(catalog, exp.Identifier) and not catalog.quoted: + catalog.set("this", catalog.name.upper()) + if isinstance(statement, exp.Show): return _find_show_statement_tables(statement) diff --git a/tests/unit_tests/db_engine_specs/test_base.py b/tests/unit_tests/db_engine_specs/test_base.py index 6abc9d5ab6d..69bbf9418e2 100644 --- a/tests/unit_tests/db_engine_specs/test_base.py +++ b/tests/unit_tests/db_engine_specs/test_base.py @@ -1968,3 +1968,22 @@ def test_fetch_data_with_result_set(mocker: MockerFixture) -> None: cursor.fetchall.return_value = [(1,), (2,)] assert BaseEngineSpec.fetch_data(cursor) == [(1,), (2,)] + + [email protected]("catalog", [None, "sales", "Sales_Db", "a%b"]) +def test_catalog_for_connection_preserves_other_engine_catalogs( + catalog: str | None, mocker: MockerFixture +) -> None: + """The database-aware hook changes no catalog outside Snowflake.""" + from sqlalchemy.engine.url import make_url + + from superset.db_engine_specs.base import BaseEngineSpec + + database = mocker.Mock() + assert ( + BaseEngineSpec.get_catalog_for_connection( + database, make_url("postgresql://user@host/sales"), catalog + ) + == catalog + ) + database.get_all_catalog_names.assert_not_called() diff --git a/tests/unit_tests/db_engine_specs/test_snowflake.py b/tests/unit_tests/db_engine_specs/test_snowflake.py index f96680eea07..6499ec4b007 100644 --- a/tests/unit_tests/db_engine_specs/test_snowflake.py +++ b/tests/unit_tests/db_engine_specs/test_snowflake.py @@ -17,8 +17,9 @@ # pylint: disable=import-outside-toplevel +from contextvars import Context from datetime import datetime -from typing import Optional +from typing import Any, Optional, TYPE_CHECKING from unittest import mock import pytest @@ -30,9 +31,297 @@ from superset.app import SupersetApp from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.superset_typing import OAuth2ClientConfig from superset.utils import json +from tests.unit_tests.conftest import with_feature_flags from tests.unit_tests.db_engine_specs.utils import assert_convert_dttm from tests.unit_tests.fixtures.common import dttm # noqa: F401 +if TYPE_CHECKING: + from superset.models.core import Database + + [email protected] +def catalog_connection_cache( + app: SupersetApp, mocker: MockerFixture +) -> tuple["Database", dict[str, set[str]], mock.MagicMock]: + """Use real catalog memoization and driver decoding, without a warehouse.""" + from flask_caching.backends import SimpleCache + + from superset.extensions import cache_manager + from superset.models.core import Database + + mocker.patch.dict(app.extensions["cache"], {cache_manager.cache: SimpleCache()}) + database = Database( + database_name="my_db", + sqlalchemy_uri="snowflake://service:pass@account/sales", + ) + # Unsaved databases skip the process engine cache, not catalog memoization. + visible_catalogs = {"service": {"SALES"}} + + def create_engine(uri: URL, **kwargs: Any) -> mock.MagicMock: + """Only database execution is simulated; inspect the effective identity.""" + engine = mocker.MagicMock() + engine.url = uri + engine.connect.return_value.__enter__.return_value.execute.side_effect = ( + lambda statement: [(name,) for name in visible_catalogs[uri.username]] + ) + return engine + + mocker.patch.object(database.db_engine_spec, "validate_database_uri") + engine_factory = mocker.patch( + "superset.models.core.create_engine", side_effect=create_engine + ) + mocker.patch("superset.models.core.sqla.event.listen") + mocker.patch( + "superset.models.core.sqla.inspect", + side_effect=lambda engine: mocker.Mock(engine=engine), + ) + return database, visible_catalogs, engine_factory + + [email protected]("catalog_cache_enabled", [False, True]) +def test_catalog_connection_ignores_stale_listing( + catalog_connection_cache: tuple["Database", dict[str, set[str]], mock.MagicMock], + catalog_cache_enabled: bool, +) -> None: + """A newly created physical name wins even while the shared listing is stale.""" + dialect = pytest.importorskip("snowflake.sqlalchemy.snowdialect") + from superset.extensions import cache_manager + + database, visible_catalogs, engine_factory = catalog_connection_cache + if catalog_cache_enabled: + database.extra = '{"metadata_cache_timeout": {"catalog_cache_timeout": 86400}}' + assert database.catalog_cache_enabled is catalog_cache_enabled + assert database.get_all_catalog_names() == {"SALES"} + assert cache_manager.cache.get("db:None:catalog_list") == {"SALES"} + visible_catalogs["service"].add("sales") + assert database.get_all_catalog_names(cache=False) == {"SALES", "sales"} + assert database.get_all_catalog_names() == {"SALES"} + + database._get_sqla_engine(catalog="sales") + uri = engine_factory.call_args.args[0] + _, driver_args = dialect.SnowflakeDialect().create_connect_args(uri) + driver_args.update(engine_factory.call_args.kwargs["connect_args"]) + assert driver_args["database"] == '"sales"' + # Classification neither reads nor overwrites the dropdown's shared cache. + assert cache_manager.cache.get("db:None:catalog_list") == {"SALES"} + + [email protected]("physical_visible", [False, True]) +@with_feature_flags(IMPERSONATE_WITH_EMAIL_PREFIX=True) +def test_catalog_connection_listing_uses_connecting_identity( + app: SupersetApp, + mocker: MockerFixture, + catalog_connection_cache: tuple["Database", dict[str, set[str]], mock.MagicMock], + physical_visible: bool, +) -> None: + """One user's cached visibility must not decide another user's catalog.""" + from flask import g + + dialect = pytest.importorskip("snowflake.sqlalchemy.snowdialect") + database, visible_catalogs, engine_factory = catalog_connection_cache + database.impersonate_user = True + visible_catalogs["first"] = {"SALES"} if physical_visible else {"SALES", "sales"} + visible_catalogs["second"] = {"SALES", "sales"} if physical_visible else {"SALES"} + mocker.patch.object(database, "get_oauth2_config", return_value={"id": "test"}) + mocker.patch.object(database, "is_oauth2_enabled", return_value=True) + mocker.patch( + "superset.models.core.get_oauth2_access_token", return_value="test_token" + ) + mocker.patch.object( + database, "get_impersonation_username", side_effect=lambda uri: g.user.username + ) + with app.test_request_context("/"): + g.user = mocker.Mock(id=1, username="first") + assert database.get_all_catalog_names() == visible_catalogs["first"] + g.user = mocker.Mock(id=2, username="second") + assert database.get_all_catalog_names() == visible_catalogs["first"] + database._get_sqla_engine(catalog="sales") + + uri = engine_factory.call_args.args[0] + _, driver_args = dialect.SnowflakeDialect().create_connect_args(uri) + driver_args.update(engine_factory.call_args.kwargs["connect_args"]) + assert driver_args["user"] == "second" + assert driver_args["database"] == ('"sales"' if physical_visible else "sales") + # Discovery must authenticate as the second user, not the URI service user. + assert [call.args[0].username for call in engine_factory.call_args_list] == [ + "first", + "second", + "second", + ] + + [email protected]("physical_catalogs", [set(), {"SALES"}, {"SALES", "sales"}]) +def test_connection_catalogs_memoized_per_identity( + mocker: MockerFixture, physical_catalogs: set[str] +) -> None: + """Repeated legacy selections list once, including an empty listing.""" + from flask import g + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database(id=1, sqlalchemy_uri="snowflake://user:pass@account/sales") + g.user = mocker.Mock(username="first") + listing = mocker.patch.object( + database, "get_all_catalog_names", return_value=physical_catalogs + ) + expected = "sales" if "sales" in physical_catalogs else None + for _ in range(2): + assert ( + SnowflakeEngineSpec.get_catalog_for_connection( + database, database.url_object, "sales" + ) + == expected + ) + listing.assert_called_once_with(cache=False) + + [email protected]("different_identity", ["user", "database"]) +def test_connection_catalogs_separate_identities( + mocker: MockerFixture, different_identity: str +) -> None: + """A request cannot reuse another user's or database's physical names.""" + from flask import g + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + first = Database(id=1, sqlalchemy_uri="snowflake://user:pass@account/sales") + second = Database( + id=2 if different_identity == "database" else 1, + sqlalchemy_uri="snowflake://user:pass@account/sales", + ) + first_listing = mocker.patch.object( + first, "get_all_catalog_names", return_value={"SALES"} + ) + second_listing = mocker.patch.object( + second, "get_all_catalog_names", return_value={"SALES", "sales"} + ) + g.user = mocker.Mock(username="first") + assert SnowflakeEngineSpec._get_connection_catalogs(first) == {"SALES"} + g.user = mocker.Mock(username="second" if different_identity == "user" else "first") + for _ in range(2): + assert SnowflakeEngineSpec._get_connection_catalogs(second) == { + "SALES", + "sales", + } + g.user = mocker.Mock(username="first") + assert SnowflakeEngineSpec._get_connection_catalogs(first) == {"SALES"} + first_listing.assert_called_once_with(cache=False) + second_listing.assert_called_once_with(cache=False) + + +def test_connection_catalogs_without_app_context(mocker: MockerFixture) -> None: + """Without Flask g, every lookup uses uncached identity-scoped discovery.""" + from flask import has_app_context + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database(id=1, sqlalchemy_uri="snowflake://user:pass@account/sales") + listing = mocker.patch.object( + database, "get_all_catalog_names", side_effect=[{"SALES"}, {"SALES", "sales"}] + ) + + def lookup() -> None: + """Run without inheriting the test fixture's application context.""" + assert not has_app_context() + assert SnowflakeEngineSpec._get_connection_catalogs(database) == {"SALES"} + assert SnowflakeEngineSpec._get_connection_catalogs(database) == { + "SALES", + "sales", + } + + Context().run(lookup) + assert listing.call_args_list == [mock.call(cache=False), mock.call(cache=False)] + + +def test_connection_catalogs_unsaved_database(mocker: MockerFixture) -> None: + """Unsaved database objects must not collide or store listings on g.""" + from flask import g + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database(sqlalchemy_uri="snowflake://user:pass@account/sales") + listing = mocker.patch.object( + database, "get_all_catalog_names", side_effect=[{"SALES"}, {"SALES", "sales"}] + ) + assert database.id is None + assert SnowflakeEngineSpec._get_connection_catalogs(database) == {"SALES"} + assert SnowflakeEngineSpec._get_connection_catalogs(database) == {"SALES", "sales"} + assert listing.call_args_list == [mock.call(cache=False), mock.call(cache=False)] + assert "_snowflake_connection_catalogs" not in g + + +def test_connection_catalogs_new_app_context( + app: SupersetApp, mocker: MockerFixture +) -> None: + """Another request discovers fresh physical names, not an earlier listing.""" + from flask import g + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database(id=1, sqlalchemy_uri="snowflake://user:pass@account/sales") + listing = mocker.patch.object( + database, "get_all_catalog_names", side_effect=[{"SALES"}, {"SALES", "sales"}] + ) + for physical_catalogs in ({"SALES"}, {"SALES", "sales"}): + with app.app_context(): + g.user = mocker.Mock(username="first") + assert "_snowflake_connection_catalogs" not in g + for _ in range(2): + assert ( + SnowflakeEngineSpec._get_connection_catalogs(database) + == physical_catalogs + ) + assert listing.call_args_list == [mock.call(cache=False), mock.call(cache=False)] + assert "_snowflake_connection_catalogs" not in g + + +def test_connection_catalogs_celery_task_context(mocker: MockerFixture) -> None: + """AppContextTask reuses discovery inside a task, but not across tasks.""" + from flask import g, has_app_context + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.extensions import celery_app + from superset.models.core import Database + from superset.utils.core import override_user + + database = Database(id=1, sqlalchemy_uri="snowflake://user:pass@account/sales") + listing = mocker.patch.object( + database, "get_all_catalog_names", side_effect=[{"SALES"}, {"SALES", "sales"}] + ) + + class CatalogTask(celery_app.Task): + """Exercise the application's real task context wrapper without a broker.""" + + def run(self) -> set[str]: + """Discover twice under the identity restored by async query tasks.""" + assert has_app_context() + assert "_snowflake_connection_catalogs" not in g + with override_user(mocker.Mock(username="first")): + catalogs = SnowflakeEngineSpec._get_connection_catalogs(database) + assert ( + SnowflakeEngineSpec._get_connection_catalogs(database) == catalogs + ) + return catalogs + + CatalogTask.bind(celery_app) + task = CatalogTask() + + def run_tasks() -> None: + """Enter each task without the fixture's ambient application context.""" + assert not has_app_context() + assert task() == {"SALES"} + assert not has_app_context() + assert task() == {"SALES", "sales"} + assert not has_app_context() + + Context().run(run_tasks) + assert listing.call_args_list == [mock.call(cache=False), mock.call(cache=False)] + @pytest.mark.parametrize("name", ["lowercase", "UPPERCASE"]) def test_prepare_identifier_quotes_exact_case_names(name: str) -> None: @@ -267,7 +556,7 @@ def test_adjust_engine_params_fully_qualified() -> None: )[0] assert ( uri.render_as_string(hide_password=False) - == "snowflake://user:pass@account/new_catalog/default" + == 'snowflake://user:pass@account/"new_catalog"/default' ) uri = SnowflakeEngineSpec.adjust_engine_params( @@ -278,7 +567,7 @@ def test_adjust_engine_params_fully_qualified() -> None: )[0] assert ( uri.render_as_string(hide_password=False) - == "snowflake://user:pass@account/new_catalog/new_schema" + == 'snowflake://user:pass@account/"new_catalog"/new_schema' ) @@ -313,7 +602,7 @@ def test_adjust_engine_params_catalog_only() -> None: )[0] assert ( uri.render_as_string(hide_password=False) - == "snowflake://user:pass@account/new_catalog" + == 'snowflake://user:pass@account/"new_catalog"' ) uri = SnowflakeEngineSpec.adjust_engine_params( @@ -324,7 +613,7 @@ def test_adjust_engine_params_catalog_only() -> None: )[0] assert ( uri.render_as_string(hide_password=False) - == "snowflake://user:pass@account/new_catalog/new_schema" + == 'snowflake://user:pass@account/"new_catalog"/new_schema' ) @@ -339,13 +628,190 @@ def test_get_default_catalog() -> None: database_name="my_db", sqlalchemy_uri="snowflake://user:pass@account/database_name", ) - assert SnowflakeEngineSpec.get_default_catalog(database) == "database_name" + assert SnowflakeEngineSpec.get_default_catalog(database) == "DATABASE_NAME" database = Database( database_name="my_db", sqlalchemy_uri="snowflake://user:pass@account/database_name/default", ) - assert SnowflakeEngineSpec.get_default_catalog(database) == "database_name" + assert SnowflakeEngineSpec.get_default_catalog(database) == "DATABASE_NAME" + + [email protected]( + "identifier,expected", + [ + ("sales", "SALES"), + ("Sales", "SALES"), + ("SALES", "SALES"), + ('"sales"', "sales"), + ('"Sales"', "Sales"), + ("%22Sales%22", "Sales"), + ('"a""b"', 'a"b'), + ], +) [email protected]("schema", ["", "/public"]) +def test_default_catalog_resolves_only_unquoted_identifiers( + identifier: str, expected: str, schema: str +) -> None: + """Resolve URI catalog identifiers without folding quoted database names.""" + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database( + database_name="my_db", + sqlalchemy_uri=f"snowflake://user:pass@account/{identifier}{schema}", + ) + assert SnowflakeEngineSpec.get_default_catalog(database) == expected + + [email protected]( + "uri_catalog,selected_catalog,expected", + [ + ('"Sales_Db"', None, "Sales_Db"), + ("%22Sales_Db%22", None, "Sales_Db"), + ('"sales_db"', None, "sales_db"), + ("Sales_Db", None, "SALES_DB"), + ("sales_db", None, "SALES_DB"), + ("SALES_DB", "Sales_Db", "Sales_Db"), + ("SALES_DB", "sales_db", "sales_db"), + ("SALES_DB", "SALES_DB", "SALES_DB"), + ("SALES_DB", 'a"b', 'a"b'), + ("SALES_DB", '"Sales_Db"', '"Sales_Db"'), + ], +) [email protected]("schema", [None, "public"]) +def test_connection_catalog_preserves_physical_identity( + uri_catalog: str, + selected_catalog: str | None, + expected: str, + schema: str | None, + mocker: MockerFixture, +) -> None: + """SQL Lab reconnects using the exact default or listed physical catalog.""" + from urllib.parse import unquote + + from superset.models.core import Database + + database = Database( + database_name="my_db", + sqlalchemy_uri=f"snowflake://user:pass@account/{uri_catalog}", + ) + # SQL Lab fills an omitted catalog from the default before opening an engine. + catalog = selected_catalog or database.get_default_catalog() + assert catalog == expected + # Driver installation validation is independent of catalog selection. + mocker.patch.object(database.db_engine_spec, "validate_database_uri") + create_engine = mocker.patch("superset.models.core.create_engine") + mocker.patch("superset.models.core.sqla.event.listen") + database._get_sqla_engine(catalog=catalog, schema=schema) + uri = create_engine.call_args.args[0] + quoted_catalog = '"' + expected.replace('"', '""') + '"' + assert unquote(uri.database.split("/", 1)[0]) == quoted_catalog + assert ( + database.db_engine_spec.get_default_catalog( + Database(sqlalchemy_uri=uri.render_as_string(hide_password=False)) + ) + == expected + ) + assert database.db_engine_spec.get_schema_from_engine_params(uri, {}) == schema + + [email protected]( + "uri_database,catalog,schema,expected", + [ + # rows saved by earlier versions hold the URI identifier verbatim: keep it + # unquoted, instead of connecting to a "sales" database that doesn't exist + ("sales", "sales", None, "sales"), + ("sales/marts", "sales", None, "sales/marts"), + ("sales/marts", "sales", "other", "sales/other"), + ("Sales_Db", "Sales_Db", None, "Sales_Db"), + ("%22sales%22/marts", "sales", None, '"sales"/marts'), + # resolved defaults and listed catalogs are physical names: quote them + ("sales", "SALES", None, '"SALES"'), + ("sales/marts", "SALES", None, '"SALES"/marts'), + ("SALES", "SALES", None, '"SALES"'), + ('"Sales_Db"', "Sales_Db", None, '"Sales_Db"'), + ("%22Sales_Db%22", "Sales_Db", None, '"Sales_Db"'), + ("%22Sales_Db%22/marts", "Sales_Db", None, '"Sales_Db"/marts'), + ("sales", "other_db", None, '"other_db"'), + ("sales", "a%b", None, '"a%25b"'), + ("sales", 'a"b', None, '"a""b"'), + ("sales", "my db/x", None, '"my%20db%2Fx"'), + ], +) +def test_adjust_engine_params_legacy_default_catalog( + uri_database: str, + catalog: str, + schema: str | None, + expected: str, + mocker: MockerFixture, +) -> None: + """ + Keep the URI identifier of a legacy default catalog, and percent-encode the + quoted name otherwise. Driver arguments are tested separately. + """ + from sqlalchemy.engine.url import make_url + + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + + url = make_url(f"snowflake://user:pass@account/{uri_database}") + database = mocker.Mock() + database.get_all_catalog_names.return_value = set() + selected = SnowflakeEngineSpec.get_catalog_for_connection(database, url, catalog) + uri = SnowflakeEngineSpec.adjust_engine_params(url, {}, selected, schema)[0] + assert uri.database == expected + + [email protected]("schema", [None, "other"]) +def test_legacy_lowercase_catalog_connects_with_uri_identifier( + schema: str | None, mocker: MockerFixture +) -> None: + """ + A dataset or query saved before catalog quoting stores the lowercase URI + identifier (``sales``) as its catalog. It must still connect with the + unquoted ``database='sales'``, not the non-existent ``"sales"`` database. + """ + from superset.models.core import Database + + database = Database( + database_name="my_db", + sqlalchemy_uri="snowflake://u:p@acct/sales/marts", + ) + mocker.patch.object(database.db_engine_spec, "validate_database_uri") + create_engine = mocker.patch("superset.models.core.create_engine") + mocker.patch("superset.models.core.sqla.event.listen") + + mocker.patch.object(database, "get_all_catalog_names", return_value={"SALES"}) + database._get_sqla_engine(catalog="sales", schema=schema) + + uri = create_engine.call_args.args[0] + assert uri.database == f"sales/{schema or 'marts'}" + assert uri.database.split("/")[0] == "sales" + + [email protected]( + "catalog,uri_catalog,expected", + [ + ("sales", "sales", True), + ("Sales", "Sales", True), + ("sales", "%22sales%22", False), + ("sales", "SALES", False), + ("SALES", "sales", False), + ("SALES", "SALES", False), + ("Sales_Db", '"Sales_Db"', False), + ("Sales_Db", "%22Sales_Db%22", False), + ("other", "sales", False), + ], +) +def test_is_legacy_default_catalog( + catalog: str, uri_catalog: str, expected: bool +) -> None: + """Only the verbatim URI identifier that differs from the physical name.""" + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + + assert SnowflakeEngineSpec._is_legacy_default_catalog( + catalog, uri_catalog, set() + ) is (expected) def test_mask_encrypted_extra() -> None: @@ -854,3 +1320,126 @@ def test_snowflake_oauth2_exception_catches_refresh_token_error() -> None: "OAuth2TokenRefreshError must be caught by " "SnowflakeEngineSpec.oauth2_exception" ) + + [email protected]("schema", [None, "marts"]) [email protected]("catalog", ["sales", "Sales_Db"]) [email protected]("physical_exists", [False, True]) +def test_uri_alias_or_selected_physical_catalog( + catalog: str, schema: str | None, physical_exists: bool, mocker: MockerFixture +) -> None: + """Only a missing physical catalog can be a legacy URI alias.""" + from superset.models.core import Database + + database = Database( + database_name="my_db", + sqlalchemy_uri=f"snowflake://user:pass@account/{catalog}", + ) + mocker.patch.object( + database, + "get_all_catalog_names", + return_value={catalog.upper(), catalog} + if physical_exists + else {catalog.upper()}, + ) + mocker.patch.object(database.db_engine_spec, "validate_database_uri") + create_engine = mocker.patch("superset.models.core.create_engine") + mocker.patch("superset.models.core.sqla.event.listen") + database._get_sqla_engine(catalog=catalog, schema=schema, cacheable=False) + uri = create_engine.call_args.args[0] + expected = f'"{catalog}"' if physical_exists else catalog + assert uri.database == expected + (f"/{schema}" if schema else "") + + [email protected]("schema", [None, "marts"]) [email protected]("catalog", ["a%b", "a%25b", "a+b", "my db/x", 'a"b']) +def test_physical_catalog_driver_arguments(catalog: str, schema: str | None) -> None: + """Exercise real dialect decoding and SQLAlchemy connect_args precedence.""" + dialect = pytest.importorskip("snowflake.sqlalchemy.snowdialect") + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + + uri, connect_args = SnowflakeEngineSpec.adjust_engine_params( + make_url("snowflake://user:pass@account/SALES"), {}, catalog, schema + ) + _, driver_args = dialect.SnowflakeDialect().create_connect_args(uri) + driver_args.update(connect_args) + assert driver_args["database"] == '"' + catalog.replace('"', '""') + '"' + assert driver_args.get("schema") == schema + + [email protected]("schema", [None, "marts"]) [email protected]( + "uri_catalog,stored_catalog,expected", + [ + ("sales", "sales", "sales"), + ("Sales_Db", "Sales_Db", "Sales_Db"), + ("%22a%25b%22", "a%b", '"a%b"'), + ("%22Sales_Db%22", "Sales_Db", '"Sales_Db"'), + ], +) +def test_saved_catalog_driver_arguments( + uri_catalog: str, + stored_catalog: str, + expected: str, + schema: str | None, + mocker: MockerFixture, +) -> None: + """Saved aliases and quoted URI defaults reach the real driver unchanged.""" + dialect = pytest.importorskip("snowflake.sqlalchemy.snowdialect") + from superset.models.core import Database + + database = Database( + database_name="my_db", + sqlalchemy_uri=f"snowflake://user:pass@account/{uri_catalog}", + ) + mocker.patch.object( + database, "get_all_catalog_names", return_value={"SALES", "SALES_DB", "a%b"} + ) + mocker.patch.object(database.db_engine_spec, "validate_database_uri") + create_engine = mocker.patch("superset.models.core.create_engine") + mocker.patch("superset.models.core.sqla.event.listen") + database._get_sqla_engine(catalog=stored_catalog, schema=schema, cacheable=False) + _, driver_args = dialect.SnowflakeDialect().create_connect_args( + create_engine.call_args.args[0] + ) + driver_args.update(create_engine.call_args.kwargs["connect_args"]) + assert driver_args["database"] == expected + assert driver_args.get("schema") == schema + + +def test_ambiguous_catalog_listing_error_does_not_select_default( + mocker: MockerFixture, +) -> None: + """A failed lookup must not silently route a physical selection elsewhere.""" + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database(sqlalchemy_uri="snowflake://user:pass@account/sales") + mocker.patch.object( + database, + "get_all_catalog_names", + side_effect=RuntimeError("listing unavailable"), + ) + with pytest.raises(RuntimeError, match="listing unavailable"): + SnowflakeEngineSpec.get_catalog_for_connection( + database, database.url_object, "sales" + ) + + [email protected]("catalog", [None, "SALES", "other"]) +def test_unambiguous_catalog_does_not_need_listing( + catalog: str | None, mocker: MockerFixture +) -> None: + """Default/listing connections do not recursively enumerate catalogs.""" + from superset.db_engine_specs.snowflake import SnowflakeEngineSpec + from superset.models.core import Database + + database = Database(sqlalchemy_uri="snowflake://user:pass@account/sales") + listing = mocker.patch.object(database, "get_all_catalog_names") + assert ( + SnowflakeEngineSpec.get_catalog_for_connection( + database, database.url_object, catalog + ) + == catalog + ) + listing.assert_not_called() diff --git a/tests/unit_tests/security/manager_test.py b/tests/unit_tests/security/manager_test.py index d351daa35e3..d41c93a1c4f 100644 --- a/tests/unit_tests/security/manager_test.py +++ b/tests/unit_tests/security/manager_test.py @@ -3453,6 +3453,7 @@ def test_raise_for_access_catalog( SqlaTable.query_datasources_by_name.return_value = [] database = mocker.MagicMock() + database.db_engine_spec.case_insensitive_catalogs = False database.get_default_catalog.return_value = "db1" database.get_default_schema_for_query.return_value = "public" query = mocker.MagicMock() @@ -4054,6 +4055,7 @@ def test_raise_for_access_catalog_supporting_engine_still_requires_catalog( SqlaTable.query_datasources_by_name.return_value = [] database = mocker.MagicMock() + database.db_engine_spec.case_insensitive_catalogs = False database.database_name = "examples" database.db_engine_spec.supports_catalog = True database.get_default_catalog.return_value = "examples" @@ -4223,8 +4225,9 @@ def test_raise_for_access_allow_editorship_false_keeps_catalog_access( mocker.patch.object( sm, "can_access", - side_effect=lambda perm, vm: perm == "catalog_access" - and vm == f"[{MSSQL_CONN_NAME}].[other]", + side_effect=lambda perm, vm: ( + perm == "catalog_access" and vm == f"[{MSSQL_CONN_NAME}].[other]" + ), ) sm.raise_for_access(query=query, allow_editorship=False) @@ -4259,8 +4262,10 @@ def test_raise_for_access_allow_editorship_false_keeps_datasource_access( mocker.patch.object( sm, "can_access", - side_effect=lambda perm, vm: perm == "datasource_access" - and vm == f"[{MSSQL_CONN_NAME}].[dbo].[foo](id:1)", + side_effect=lambda perm, vm: ( + perm == "datasource_access" + and vm == f"[{MSSQL_CONN_NAME}].[dbo].[foo](id:1)" + ), ) sm.raise_for_access(query=query, allow_editorship=False) @@ -4301,6 +4306,7 @@ def test_get_datasources_accessible_by_user_schema_access( mocker.patch.object(sm, "can_access_database", return_value=False) database = mocker.MagicMock() + database.db_engine_spec.case_insensitive_catalogs = False database.database_name = "db1" database.get_default_catalog.return_value = "catalog2" diff --git a/tests/unit_tests/security/snowflake_catalog_case_test.py b/tests/unit_tests/security/snowflake_catalog_case_test.py new file mode 100644 index 00000000000..25f43e5a550 --- /dev/null +++ b/tests/unit_tests/security/snowflake_catalog_case_test.py @@ -0,0 +1,561 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Snowflake catalog grants match physical database names exactly. + +Only unquoted URI and SQL identifiers fold to uppercase. Catalog listings, +dataset catalog fields and permission names retain their exact case. +These tests use real permission sync, roles, users and the security manager; +the live catalog/schema listings and the optional SQLAlchemy dialect are mocked. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from typing import TYPE_CHECKING + +import pytest +from sqlalchemy.orm.session import Session + +from superset import db, security_manager +from superset.exceptions import SupersetSecurityException +from superset.sql.parse import Table +from superset.utils.core import DatasourceName, override_user + +if TYPE_CHECKING: + from flask_appbuilder.security.sqla.models import User + from pytest_mock import MockerFixture + + from superset.connectors.sqla.models import SqlaTable + from superset.models.core import Database + + +DATABASE_NAME = "sales_db" +LISTED_CATALOG = "SALES_DB" # as Snowflake lists it +DEFAULT_CATALOG = "SALES_DB" # resolved from the unquoted URI identifier + + [email protected] +def metadata_session(session: Session, mocker: MockerFixture) -> Session: + """ + The in-memory session, used by the security manager for writes too, so + the permissions, roles and users created below are real rows. + """ + from superset.connectors.sqla.models import SqlaTable + + mocker.patch("superset.security.SupersetSecurityManager.session", session) + SqlaTable.metadata.create_all(session.get_bind()) # pylint: disable=no-member + return session + + [email protected] +def snowflake_database(metadata_session: Session, mocker: MockerFixture) -> Database: + """ + A Snowflake database whose catalog/schema permissions were created by the + real permission sync, with Snowflake's uppercase catalog listing. + """ + from sqlalchemy.engine.default import DefaultDialect + + from superset.commands.database.utils import add_permissions + from superset.models.core import Database + + database = Database( + database_name=DATABASE_NAME, + sqlalchemy_uri="snowflake://user:pass@account/sales_db", + ) + db.session.add(database) + db.session.flush() + + mocker.patch.object( + Database, + "get_all_catalog_names", + return_value={LISTED_CATALOG, "Sales_Db", "sales_db", "OTHER_DB"}, + ) + mocker.patch.object( + Database, + "get_all_schema_names", + return_value={"marts", "finance"}, + ) + mocker.patch.object(Database, "get_default_schema", return_value="public") + # SQLGlot parses the SQL; these tests do not render dialect-specific macros. + # Avoid requiring the optional Snowflake driver just to build Jinja context. + mocker.patch.object(Database, "get_dialect", return_value=DefaultDialect()) + add_permissions(database) + db.session.flush() + return database + + +def _user_with(*grants: tuple[str, str]) -> User: + """ + A user whose only role holds the given ``(permission, view_menu)`` grants, + which must already exist (as they would after a permission sync). + """ + role = security_manager.add_role("dar") + for permission_name, view_menu_name in grants: + pvm = security_manager.find_permission_view_menu( + permission_name, view_menu_name + ) + assert pvm is not None, f"{permission_name} {view_menu_name} not synced" + role.permissions.append(pvm) + user = security_manager.user_model( + username="analyst", + first_name="A", + last_name="B", + email="[email protected]", + active=True, + roles=[role], + ) + db.session.add(user) + db.session.flush() + return user + + [email protected] +def schema_grant_user(snowflake_database: Database) -> Iterator[User]: + """A user holding only the synced (uppercase-catalog) schema permission.""" + user = _user_with( + ("schema_access", f"[{DATABASE_NAME}].[{LISTED_CATALOG}].[marts]"), + ) + with override_user(user): + yield user + + +def _dataset(database: Database, schema: str, catalog: str) -> SqlaTable: + from superset.connectors.sqla.models import SqlaTable + + dataset = SqlaTable( + table_name="orders", + schema=schema, + catalog=catalog, + database=database, + ) + db.session.add(dataset) + db.session.flush() + return dataset + + +def test_sqllab_schema_list_uses_synced_grant( + snowflake_database: Database, + schema_grant_user: User, +) -> None: + """ + SQL Lab asks for the schemas of the default catalog (no catalog selector + without multi-catalog). The synced grant names the same catalog in + uppercase, so its schema must be listed. + """ + assert snowflake_database.get_default_catalog() == DEFAULT_CATALOG + assert security_manager.get_schemas_accessible_by_user( + snowflake_database, + None, + {"marts", "finance"}, + ) == {"marts"} + + +def test_sqllab_catalog_and_schema_lists_with_multi_catalog( + snowflake_database: Database, + schema_grant_user: User, +) -> None: + """With the catalog selector, the listed catalog and its schema show up.""" + assert security_manager.get_catalogs_accessible_by_user( + snowflake_database, + {LISTED_CATALOG, "OTHER_DB"}, + ) == {LISTED_CATALOG} + assert security_manager.get_schemas_accessible_by_user( + snowflake_database, + LISTED_CATALOG, + {"marts", "finance"}, + ) == {"marts"} + + +def test_sqllab_table_list_and_table_access( + snowflake_database: Database, + schema_grant_user: User, +) -> None: + """ + After picking the schema, SQL Lab lists its tables and reads their + metadata, both under the default catalog. + """ + tables = [ + DatasourceName("orders", "marts", DEFAULT_CATALOG), + DatasourceName("items", "marts", DEFAULT_CATALOG), + ] + assert ( + security_manager.get_datasources_accessible_by_user( + snowflake_database, + tables, + catalog=None, + schema="marts", + ) + == tables + ) + security_manager.raise_for_access( + database=snowflake_database, + table=Table("orders", "marts"), + ) + + +def test_dataset_in_default_catalog_is_accessible( + snowflake_database: Database, + schema_grant_user: User, +) -> None: + """ + Datasets use the resolved default catalog, so the synced grant covers + them in both the per-dataset check and the dataset list filter. + """ + from superset.connectors.sqla.models import SqlaTable + from superset.utils.filters import get_dataset_access_filters + + dataset = _dataset(snowflake_database, "marts", DEFAULT_CATALOG) + other = _dataset(snowflake_database, "finance", DEFAULT_CATALOG) + assert dataset.schema_perm == f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}].[marts]" + + assert security_manager.can_access_schema(dataset) + assert not security_manager.can_access_schema(other) + visible = ( + db.session.query(SqlaTable).filter(get_dataset_access_filters(SqlaTable)).all() + ) + assert visible == [dataset] + + +def test_dataset_derived_grant_covers_physical_catalog( + snowflake_database: Database, +) -> None: + """ + A grant on a dataset-created permission covers its physical catalog + in the multi-catalog selector. + """ + _dataset(snowflake_database, "marts", DEFAULT_CATALOG) + user = _user_with( + ("schema_access", f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}].[marts]"), + ) + with override_user(user): + assert security_manager.get_catalogs_accessible_by_user( + snowflake_database, + {LISTED_CATALOG, "OTHER_DB"}, + ) == {LISTED_CATALOG} + assert security_manager.get_schemas_accessible_by_user( + snowflake_database, + LISTED_CATALOG, + {"marts", "finance"}, + ) == {"marts"} + + +def test_catalog_grant_covers_default_catalog( + snowflake_database: Database, +) -> None: + """A synced ``catalog_access`` grant covers the URI spelling of the catalog.""" + user = _user_with(("catalog_access", f"[{DATABASE_NAME}].[{LISTED_CATALOG}]")) + with override_user(user): + assert security_manager.can_access_catalog(snowflake_database, DEFAULT_CATALOG) + assert security_manager.get_schemas_accessible_by_user( + snowflake_database, + None, + {"marts", "finance"}, + ) == {"marts", "finance"} + assert not security_manager.can_access_catalog(snowflake_database, "OTHER_DB") + + +def test_catalog_list_with_dataset_access( + snowflake_database: Database, +) -> None: + """ + The catalog list for a user who only holds dataset access returns the + dataset's catalog (it used to read ``catalog`` off a row that only + selected ``schema``). + """ + dataset = _dataset(snowflake_database, "marts", DEFAULT_CATALOG) + user = _user_with(("datasource_access", dataset.perm)) + with override_user(user): + assert security_manager.get_catalogs_accessible_by_user( + snowflake_database, + {LISTED_CATALOG, "OTHER_DB"}, + ) == {LISTED_CATALOG} + + +def test_catalog_grant_does_not_widen_access( + snowflake_database: Database, + schema_grant_user: User, +) -> None: + """ + Another catalog or schema, including names differing only by case, + the whole catalog and the whole connection stay denied. + """ + sm = security_manager + assert ( + sm.get_schemas_accessible_by_user( + snowflake_database, "OTHER_DB", {"marts", "finance"} + ) + == set() + ) + assert ( + sm.get_schemas_accessible_by_user( + snowflake_database, None, {"MARTS", "finance"} + ) + == set() + ) + assert not sm.can_access_catalog(snowflake_database, DEFAULT_CATALOG) + assert not sm.can_access_database(snowflake_database) + + def can_access_schema_perm(view_name: str) -> bool: + return sm.can_access_catalog_scoped( + snowflake_database, "schema_access", view_name + ) + + assert can_access_schema_perm(f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}].[marts]") + assert not can_access_schema_perm(f"[{DATABASE_NAME}].[Sales_Db].[marts]") + assert not can_access_schema_perm( + f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}].[finance]" + ) + assert not can_access_schema_perm(f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}].[MARTS]") + assert not can_access_schema_perm(f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}2].[marts]") + assert not can_access_schema_perm(f"[{DATABASE_NAME}].[OTHER_DB].[marts]") + assert not can_access_schema_perm( + f"[{DATABASE_NAME.upper()}].[{DEFAULT_CATALOG}].[marts]" + ) + assert not can_access_schema_perm(f"[{DATABASE_NAME}].[marts]") + assert not sm.can_access_catalog_scoped( + snowflake_database, "catalog_access", f"[{DATABASE_NAME}].[{DEFAULT_CATALOG}]" + ) + with pytest.raises(SupersetSecurityException): + sm.raise_for_access( + database=snowflake_database, + table=Table("orders", "finance"), + ) + + +def test_case_sensitive_engine_still_matches_exactly( + metadata_session: Session, + mocker: MockerFixture, +) -> None: + """ + Engines without case-insensitive catalogs keep exact matching: on + Postgres ``SALES_DB`` and ``sales_db`` are two different catalogs. + """ + from superset.commands.database.utils import add_permissions + from superset.models.core import Database + + database = Database( + database_name=DATABASE_NAME, + sqlalchemy_uri="postgresql://user:pass@host/sales_db", + extra='{"allow_multi_catalog": true}', + ) + db.session.add(database) + db.session.flush() + mocker.patch.object( + Database, "get_all_catalog_names", return_value={LISTED_CATALOG} + ) + mocker.patch.object(Database, "get_all_schema_names", return_value={"marts"}) + mocker.patch.object(Database, "get_default_schema", return_value="public") + add_permissions(database) + db.session.flush() + + user = _user_with( + ("schema_access", f"[{DATABASE_NAME}].[{LISTED_CATALOG}].[marts]"), + ) + with override_user(user): + assert ( + security_manager.get_schemas_accessible_by_user(database, None, {"marts"}) + == set() + ) + assert not security_manager.can_access_catalog_scoped( + database, + "schema_access", + f"[{DATABASE_NAME}].[sales_db].[marts]", + ) + assert security_manager.user_view_menu_names("schema_access") == { + f"[{DATABASE_NAME}].[{LISTED_CATALOG}].[marts]" + } + + [email protected]("permission", ["catalog_access", "schema_access"]) [email protected]( + "granted_catalog,denied_catalog", + [ + ("Sales_Db", "SALES_DB"), + ("sales_db", "SALES_DB"), + ("SALES_DB", "Sales_Db"), + ("SALES_DB", "sales_db"), + ], +) [email protected]( + "entrypoint", + [ + "catalog_list", + "schema_list", + "table_list", + "permission", + "dataset", + "dataset_list", + "table_access", + "sql", + ], +) +def test_quoted_catalog_grant_is_isolated( + snowflake_database: Database, + permission: str, + granted_catalog: str, + denied_catalog: str, + entrypoint: str, +) -> None: + """Distinct physical databases differing only by case must not share grants.""" + from superset.connectors.sqla.models import SqlaTable + from superset.utils.filters import get_dataset_access_filters + + suffix = ".[marts]" if permission == "schema_access" else "" + user = _user_with((permission, f"[{DATABASE_NAME}].[{granted_catalog}]{suffix}")) + dataset = _dataset(snowflake_database, "marts", denied_catalog) + sm = security_manager + with override_user(user): + if entrypoint == "catalog_list": + assert sm.get_catalogs_accessible_by_user( + snowflake_database, {granted_catalog, denied_catalog} + ) == {granted_catalog} + elif entrypoint == "schema_list": + assert ( + sm.get_schemas_accessible_by_user( + snowflake_database, denied_catalog, {"marts"} + ) + == set() + ) + elif entrypoint == "table_list": + assert ( + sm.get_datasources_accessible_by_user( + snowflake_database, + [DatasourceName("orders", "marts", denied_catalog)], + catalog=denied_catalog, + schema="marts", + ) + == [] + ) + elif entrypoint == "permission": + assert not sm.can_access_catalog_scoped( + snowflake_database, + permission, + f"[{DATABASE_NAME}].[{denied_catalog}]{suffix}", + ) + elif entrypoint == "dataset": + assert not sm.can_access_schema(dataset) + elif entrypoint == "dataset_list": + assert ( + db.session.query(SqlaTable) + .filter(get_dataset_access_filters(SqlaTable)) + .all() + == [] + ) + elif entrypoint == "table_access": + with pytest.raises(SupersetSecurityException): + sm.raise_for_access( + database=snowflake_database, + table=Table("orders", "marts", denied_catalog), + ) + else: + with pytest.raises(SupersetSecurityException): + sm.raise_for_access( + database=snowflake_database, + sql=f'SELECT * FROM "{denied_catalog}".marts.orders', # noqa: S608 + ) + + [email protected]("catalog", ["sales_db", "Sales_Db", "SALES_DB", '"SALES_DB"']) +def test_unquoted_sql_catalog_uses_uppercase_grant( + snowflake_database: Database, + schema_grant_user: User, + catalog: str, +) -> None: + """Unquoted SQL catalog spellings all resolve to the uppercase database.""" + security_manager.raise_for_access( + database=snowflake_database, + sql=f"SELECT * FROM {catalog}.marts.orders", # noqa: S608 + ) + + [email protected]("catalog", ['"sales_db"', '"Sales_Db"', "%22sales_db%22"]) +def test_quoted_default_catalog_does_not_use_uppercase_grant( + snowflake_database: Database, + schema_grant_user: User, + catalog: str, +) -> None: + """A quoted URI default cannot inherit a grant on its uppercase sibling.""" + snowflake_database.sqlalchemy_uri = f"snowflake://user:pass@account/{catalog}" + assert ( + security_manager.get_schemas_accessible_by_user( + snowflake_database, None, {"marts"} + ) + == set() + ) + + [email protected]("catalog", ["sales_db", "Sales_Db"]) +def test_quoted_catalog_grant_does_not_cover_unquoted_sql( + snowflake_database: Database, + catalog: str, +) -> None: + """An unquoted SQL identifier resolves to uppercase, not its quoted sibling.""" + user = _user_with(("catalog_access", f"[{DATABASE_NAME}].[{catalog}]")) + with override_user(user): + security_manager.raise_for_access( + database=snowflake_database, + sql=f'SELECT * FROM "{catalog}".marts.orders', # noqa: S608 + ) + with pytest.raises(SupersetSecurityException): + security_manager.raise_for_access( + database=snowflake_database, + sql=f"SELECT * FROM {catalog}.marts.orders", # noqa: S608 + ) + + [email protected]("permission", ["catalog_access", "schema_access"]) [email protected]("schema", [None, "marts"]) +def test_authorized_physical_catalog_matches_connection( + snowflake_database: Database, + mocker: MockerFixture, + permission: str, + schema: str | None, +) -> None: + """A listed physical lowercase catalog must not connect to uppercase.""" + physical = "sales_db" + dataset = _dataset(snowflake_database, "marts", physical) + suffix = ".[marts]" if permission == "schema_access" else "" + user = _user_with( + (permission, f"[{DATABASE_NAME}].[{physical}]{suffix}"), + ("datasource_access", dataset.perm), + ) + with override_user(user): + assert security_manager.can_access_catalog_scoped( + snowflake_database, permission, f"[{DATABASE_NAME}].[{physical}]{suffix}" + ) + assert not security_manager.can_access_catalog_scoped( + snowflake_database, permission, f"[{DATABASE_NAME}].[SALES_DB]{suffix}" + ) + security_manager.raise_for_access( + database=snowflake_database, table=Table("orders", "marts", physical) + ) + security_manager.raise_for_access( + database=snowflake_database, + sql="SELECT * FROM marts.orders", + catalog=physical, + schema="marts", + force_dataset_match=True, + ) + mocker.patch.object(snowflake_database.db_engine_spec, "validate_database_uri") + create_engine = mocker.patch("superset.models.core.create_engine") + mocker.patch("superset.models.core.sqla.event.listen") + snowflake_database._get_sqla_engine( + catalog=physical, schema=schema, cacheable=False + ) + uri = create_engine.call_args.args[0] + assert uri.database.split("/")[0] == '"sales_db"' diff --git a/tests/unit_tests/sql/parse_tests.py b/tests/unit_tests/sql/parse_tests.py index 8ae06b88fa0..5e408bd0518 100644 --- a/tests/unit_tests/sql/parse_tests.py +++ b/tests/unit_tests/sql/parse_tests.py @@ -198,6 +198,59 @@ def extract_tables_from_sql(sql: str, engine: str = "postgresql") -> set[Table]: } [email protected]( + "engine,catalog,expected", + [ + ("snowflake", "sales", "SALES"), + ("snowflake", "Sales", "SALES"), + ("snowflake", "SALES", "SALES"), + ("snowflake", '"sales"', "sales"), + ("snowflake", '"Sales"', "Sales"), + ("snowflake", '"SALES"', "SALES"), + ("postgresql", "sales", "sales"), + ("postgresql", '"Sales"', "Sales"), + ], +) +def test_extract_catalog_preserves_quoted_snowflake_case( + engine: str, catalog: str, expected: str +) -> None: + """Only unquoted Snowflake SQL catalogs are folded.""" + prefixes = ["SELECT * FROM"] + if engine == "snowflake": + prefixes.append("SHOW COLUMNS IN TABLE") + for prefix in prefixes: + statement = SQLStatement(f"{prefix} {catalog}.marts.orders", engine) + assert extract_tables_from_statement( + statement._parsed, SQLGLOT_DIALECTS.get(engine) + ) == {Table("orders", "marts", expected)} + + [email protected]( + "catalog,expected", + [ + ("sales", "SALES"), + ("Sales", "SALES"), + ("SALES", "SALES"), + ('"sales"', '"sales"'), + ('"Sales"', '"Sales"'), + ], +) +def test_snowflake_statement_spells_catalog_like_its_tables( + catalog: str, expected: str +) -> None: + """ + The statement itself is folded, not a copy, so the AST and ``tables`` agree. + + RLS rules are keyed by ``tables`` and matched against the AST, so an AST that + still spells the catalog in lowercase silently drops the predicate. + """ + sql = f"SELECT * FROM {catalog}.marts.orders" # noqa: S608 + statement = SQLStatement(sql, "snowflake") + assert statement._parsed.find(exp.Table).catalog == expected.strip('"') + assert statement.format().endswith(f"{expected}.marts.orders") + assert {t.catalog for t in statement.tables} == {expected.strip('"')} + + def test_extract_tables_from_sql() -> None: """ Test that referenced tables are parsed correctly from the SQL. @@ -1028,7 +1081,7 @@ def test_extract_tables_cte_name_shared_with_table() -> None: "WITH orders AS (SELECT 1 AS amt, 'a' AS mth) " "SELECT * FROM cat..orders PIVOT(SUM(amt) FOR mth IN ('a'))", engine="snowflake", - ) == {Table("orders", None, "cat")} + ) == {Table("orders", None, "CAT")} def test_extract_tables_cte_reference_not_table() -> None: diff --git a/tests/unit_tests/sql_lab_test.py b/tests/unit_tests/sql_lab_test.py index a118fc70db0..d35ab4a6eaa 100644 --- a/tests/unit_tests/sql_lab_test.py +++ b/tests/unit_tests/sql_lab_test.py @@ -32,6 +32,7 @@ from sqlalchemy.orm import Session from superset.app import SupersetApp from superset.common.db_query_status import QueryStatus from superset.db_engine_specs.postgres import PostgresEngineSpec +from superset.db_engine_specs.snowflake import SnowflakeEngineSpec from superset.errors import ErrorLevel, SupersetErrorType from superset.exceptions import OAuth2Error, SupersetErrorException from superset.models.core import Database @@ -729,6 +730,50 @@ FROM ( ) [email protected]( + "sql,expected_tables", + [ + ("SELECT * FROM SALES_DB.marts.orders", ["orders"]), + ("SELECT * FROM sales_db.marts.orders", ["orders"]), + ("SELECT * FROM Sales_Db.marts.orders", ["orders"]), + ( + "SELECT * FROM SALES_DB.marts.a JOIN sales_db.marts.b ON a.id = b.id", + ["a", "b"], + ), + ( + "SELECT * FROM sales_db.marts.a JOIN Sales_Db.marts.b ON a.id = b.id", + ["a", "b"], + ), + ], +) +def test_apply_rls_snowflake_catalog_case( + mocker: MockerFixture, sql: str, expected_tables: list[str] +) -> None: + """ + RLS applies to every table when the catalog is written in another case. + + The rules are keyed by the physical (uppercase) catalog, so the statement must + spell the catalog the same way, or the lookup misses and the predicate is + silently dropped (also in a join, where ``apply_rls`` still returns True). + """ + database = mocker.MagicMock() + database.get_default_catalog.return_value = "SALES_DB" + database.db_engine_spec = SnowflakeEngineSpec + + def predicates(table: Table, *args: Any, **kwargs: Any) -> list[str]: + assert table.catalog == "SALES_DB" + return [f"{table.table}_flag = 1"] + + mocker.patch("superset.utils.rls.get_predicates_for_table", side_effect=predicates) + + parsed_statement = SQLStatement(sql, "snowflake") + assert apply_rls(database, "SALES_DB", "marts", parsed_statement) is True + + formatted = parsed_statement.format() + for table in expected_tables: + assert f"{table}_flag = 1" in formatted + + def test_get_predicates_for_table(mocker: MockerFixture) -> None: """ Test the ``get_predicates_for_table`` helper function.
