You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/08/21 19:35:40 UTC

(superset) branch master updated: fix(import): tighten ownership and validation checks across asset importers (#43393)

This is an automated email from the ASF dual-hosted git repository.

rusackas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/master by this push:
     new 65893113fed fix(import): tighten ownership and validation checks across asset importers (#43393)
65893113fed is described below

commit 65893113fed648d9791a43748510028495270b06
Author: Evan Rusackas <ev...@preset.io>
AuthorDate: Fri Aug 21 12:35:33 2026 -0700

    fix(import): tighten ownership and validation checks across asset importers (#43393)
    
    Co-authored-by: Superset Dev <de...@superset.apache.org>
    Co-authored-by: Claude Sonnet 5 <no...@anthropic.com>
---
 .../commands/dashboard/importers/dispatcher.py     |  12 +-
 superset/commands/database/importers/v1/utils.py   |  82 ++++++-
 superset/commands/dataset/importers/dispatcher.py  |  12 +-
 superset/commands/dataset/importers/v1/utils.py    |  34 ++-
 superset/commands/importers/v1/utils.py            |  85 +++++++-
 superset/commands/query/importers/v1/utils.py      |  42 +++-
 superset/examples/utils.py                         |   2 +-
 tests/integration_tests/dashboards/api_tests.py    |  44 ++--
 tests/integration_tests/datasets/api_tests.py      |  35 ++-
 .../importers/v1/import_saved_query_test.py        | 126 +++++++++++
 .../unit_tests/commands/importers/v1/utils_test.py | 151 +++++++++++++
 .../commands/importers/dispatcher_test.py          |  29 ++-
 .../databases/commands/importers/v1/import_test.py | 240 +++++++++++++++++++++
 .../datasets/commands/importers/dispatcher_test.py |  29 ++-
 .../datasets/commands/importers/v1/import_test.py  |  64 ++++++
 tests/unit_tests/examples/utils_test.py            |  20 ++
 16 files changed, 934 insertions(+), 73 deletions(-)

diff --git a/superset/commands/dashboard/importers/dispatcher.py b/superset/commands/dashboard/importers/dispatcher.py
index 250815295ca..0fbc6d1c60c 100644
--- a/superset/commands/dashboard/importers/dispatcher.py
+++ b/superset/commands/dashboard/importers/dispatcher.py
@@ -21,17 +21,21 @@ from typing import Any
 from marshmallow.exceptions import ValidationError
 
 from superset.commands.base import BaseCommand
-from superset.commands.dashboard.importers import v0, v1
+from superset.commands.dashboard.importers import v1
 from superset.commands.exceptions import CommandInvalidError
 from superset.commands.importers.exceptions import IncorrectVersionError
 
 logger = logging.getLogger(__name__)
 
-# list of different import formats supported; v0 should be last because
-# the files are not versioned
+# list of different import formats supported. The legacy v0 importer is
+# deliberately NOT dispatched here: it overrides datasets matched by
+# (table_name, schema, database) and charts/dashboards matched by remote_id
+# without ownership checks, and this dispatcher is reachable from the HTTP
+# import endpoint (POST /api/v1/dashboard/import/). Operators can still
+# import legacy v0 JSON files with the `legacy_import_dashboards` CLI
+# command, which uses the v0 command directly.
 command_versions = [
     v1.ImportDashboardsCommand,
-    v0.ImportDashboardsCommand,
 ]
 
 
diff --git a/superset/commands/database/importers/v1/utils.py b/superset/commands/database/importers/v1/utils.py
index 5cc3a8fc608..973aaad8b80 100644
--- a/superset/commands/database/importers/v1/utils.py
+++ b/superset/commands/database/importers/v1/utils.py
@@ -21,8 +21,10 @@ from typing import Any
 from flask import current_app as app
 
 from superset import db, security_manager
+from superset.commands.database.exceptions import DatabaseInvalidError
 from superset.commands.database.utils import add_permissions
 from superset.commands.exceptions import ImportFailedError
+from superset.constants import PASSWORD_MASK
 from superset.databases.ssh_tunnel.models import SSHTunnel
 from superset.databases.utils import make_url_safe
 from superset.db_engine_specs.exceptions import SupersetDBAPIConnectionError
@@ -37,6 +39,73 @@ from superset.utils import json
 logger = logging.getLogger(__name__)
 
 
+def _connection_identity_changed(existing: Database, config: dict[str, Any]) -> bool:
+    """Whether the import points the database at a different endpoint."""
+    try:
+        stored = make_url_safe(existing.sqlalchemy_uri)._replace(password=None)
+        incoming = make_url_safe(config["sqlalchemy_uri"])._replace(password=None)
+    except DatabaseInvalidError:
+        # An unparseable URI cannot be compared: treat it as a change so
+        # stored secrets never survive onto it.
+        return True
+    return stored != incoming
+
+
+def _refuse_stored_secret_reuse(existing: Database, config: dict[str, Any]) -> None:
+    """
+    Refuse an overwrite that changes the connection endpoint without fresh
+    credentials.
+
+    Database UUIDs are not secrets -- they appear in every exported bundle --
+    so an import must not be able to repoint an existing connection at a new
+    host while the stored password (or SSH tunnel key) is silently kept: the
+    next connection would hand the real credential to the new endpoint.
+    """
+    if _connection_identity_changed(existing, config):
+        try:
+            uri_password = make_url_safe(config["sqlalchemy_uri"]).password
+        except DatabaseInvalidError:
+            uri_password = None
+        if config.get("password") in (None, PASSWORD_MASK) and uri_password in (
+            None,
+            PASSWORD_MASK,
+        ):
+            raise ImportFailedError(
+                f"Import would change the connection of database "
+                f"'{existing.database_name}' without providing new "
+                "credentials. Re-enter the database password for the new "
+                "connection to confirm the change."
+            )
+
+    if ssh_tunnel := config.get("ssh_tunnel"):
+        existing_tunnel = existing.ssh_tunnel
+        if existing_tunnel and (
+            ssh_tunnel.get("server_address") != existing_tunnel.server_address
+            or ssh_tunnel.get("server_port") != existing_tunnel.server_port
+        ):
+            has_fresh_credential = any(
+                ssh_tunnel.get(field) not in (None, PASSWORD_MASK)
+                for field in ("password", "private_key")
+            )
+            # A passphrase-protected private key's stored passphrase is a
+            # secret in its own right: if the existing tunnel had one, a
+            # repoint that supplies a fresh private_key but leaves
+            # private_key_password masked/absent would keep the old
+            # passphrase attached to the new key rather than requiring the
+            # importer to confirm it too.
+            stale_private_key_password = (
+                existing_tunnel.private_key_password is not None
+                and ssh_tunnel.get("private_key_password") in (None, PASSWORD_MASK)
+            )
+            if not has_fresh_credential or stale_private_key_password:
+                raise ImportFailedError(
+                    f"Import would change the SSH tunnel endpoint of database "
+                    f"'{existing.database_name}' without providing new tunnel "
+                    "credentials. Re-enter the SSH tunnel credentials to "
+                    "confirm the change."
+                )
+
+
 def import_database(  # noqa: C901
     config: dict[str, Any],
     overwrite: bool = False,
@@ -51,6 +120,11 @@ def import_database(  # noqa: C901
         if not overwrite or not can_write:
             return existing
         config["id"] = existing.id
+        # Stored secrets must not be rebound to a different endpoint: without
+        # fresh credentials, an overwrite that changes where the database (or
+        # its SSH tunnel) connects would exfiltrate the stored secret to the
+        # new endpoint on the next connection.
+        _refuse_stored_secret_reuse(existing, config)
     elif not can_write:
         raise ImportFailedError(
             "Database doesn't exist and user doesn't have permission to create databases"  # noqa: E501
@@ -81,7 +155,13 @@ def import_database(  # noqa: C901
     # For existing DBs, reveal masked sensitive values from current encrypted_extra.
     # For new DBs, schema validation already ensured no fields are still masked.
     if masked_encrypted_extra := config.pop("masked_encrypted_extra", None):
-        if existing and existing.encrypted_extra:
+        # Never reveal stored encrypted_extra secrets into a config that
+        # repoints the connection at a different endpoint.
+        if (
+            existing
+            and existing.encrypted_extra
+            and not _connection_identity_changed(existing, config)
+        ):
             old_config = json.loads(existing.encrypted_extra)
             new_config = json.loads(masked_encrypted_extra)
             sensitive_fields = (
diff --git a/superset/commands/dataset/importers/dispatcher.py b/superset/commands/dataset/importers/dispatcher.py
index 2d711506725..31849bb73e3 100644
--- a/superset/commands/dataset/importers/dispatcher.py
+++ b/superset/commands/dataset/importers/dispatcher.py
@@ -21,17 +21,21 @@ from typing import Any
 from marshmallow.exceptions import ValidationError
 
 from superset.commands.base import BaseCommand
-from superset.commands.dataset.importers import v0, v1
+from superset.commands.dataset.importers import v1
 from superset.commands.exceptions import CommandInvalidError
 from superset.commands.importers.exceptions import IncorrectVersionError
 
 logger = logging.getLogger(__name__)
 
-# list of different import formats supported; v0 should be last because
-# the files are not versioned
+# list of different import formats supported. The legacy v0 importer is
+# deliberately NOT dispatched here: it overrides datasets matched by
+# (table_name, schema, database) without ownership checks, and this
+# dispatcher is reachable from the HTTP import endpoint
+# (POST /api/v1/dataset/import/). Operators can still import legacy v0
+# YAML files with the `legacy_import_datasources` CLI command, which uses
+# the v0 command directly.
 command_versions = [
     v1.ImportDatasetsCommand,
-    v0.ImportDatasetsCommand,
 ]
 
 
diff --git a/superset/commands/dataset/importers/v1/utils.py b/superset/commands/dataset/importers/v1/utils.py
index b23c1183761..844ac02b8f2 100644
--- a/superset/commands/dataset/importers/v1/utils.py
+++ b/superset/commands/dataset/importers/v1/utils.py
@@ -15,6 +15,7 @@
 # specific language governing permissions and limitations
 # under the License.
 import gzip
+import io
 import ipaddress
 import logging
 import os
@@ -611,6 +612,29 @@ def _convert_temporal_columns(df: pd.DataFrame, dtype: dict[str, Any]) -> None:
                 df[column_name] = converted
 
 
+def _read_bounded(stream: Any, max_bytes: int) -> io.BytesIO:
+    """
+    Read ``stream`` into memory, failing once more than ``max_bytes`` bytes
+    have been produced.
+
+    Bounds both the raw download and gzip decompression amplification for
+    dataset data URIs: the ``.gz`` path had no analogue of
+    ``check_is_safe_zip`` and allowed unbounded expansion from a small
+    payload.
+    """
+    buffer = io.BytesIO()
+    while chunk := stream.read(1024 * 1024):
+        # Both http.client responses and gzip.open() yield bytes; a handful
+        # of tests substitute a text stream, so normalize either shape.
+        if isinstance(chunk, str):
+            chunk = chunk.encode("utf-8")
+        buffer.write(chunk)
+        if buffer.tell() > max_bytes:
+            raise ImportFailedError("Data URI payload exceeds the maximum allowed size")
+    buffer.seek(0)
+    return buffer
+
+
 def load_data(data_uri: str, dataset: SqlaTable, database: Database) -> None:
     """
     Load data from a data URI into a dataset.
@@ -637,9 +661,15 @@ def load_data(data_uri: str, dataset: SqlaTable, database: Database) -> None:
         handlers.extend([_PeerValidatingHTTPHandler, _PeerValidatingHTTPSHandler])
     opener = request.build_opener(*handlers)
     data = opener.open(data_uri)  # pylint: disable=consider-using-with  # noqa: S310
+    # Cap the bytes materialized from the download, before and after gzip
+    # decompression (same per-file knob as ZIP bundle uploads): a gzip
+    # stream can carry oversized headers, trailing data, or additional
+    # members that would otherwise let the raw (compressed) download exceed
+    # the limit even when the decompressed CSV stays within it.
+    max_bytes = app.config["ZIPPED_FILE_MAX_SIZE"]
     if data_uri.endswith(".gz"):
-        data = gzip.open(data)
-    df = pd.read_csv(data, encoding="utf-8")
+        data = gzip.open(_read_bounded(data, max_bytes))
+    df = pd.read_csv(_read_bounded(data, max_bytes), encoding="utf-8")
     dtype = get_dtype(df, dataset)
 
     _convert_temporal_columns(df, dtype)
diff --git a/superset/commands/importers/v1/utils.py b/superset/commands/importers/v1/utils.py
index 28936341f13..0217a3f3d31 100644
--- a/superset/commands/importers/v1/utils.py
+++ b/superset/commands/importers/v1/utils.py
@@ -27,6 +27,7 @@ from sqlalchemy.orm import Session
 from superset import db
 from superset.commands.importers.exceptions import IncorrectVersionError
 from superset.databases.ssh_tunnel.models import SSHTunnel
+from superset.databases.utils import make_url_safe
 from superset.extensions import feature_flag_manager
 from superset.models.core import Database
 from superset.models.dashboard import dashboard_slices
@@ -103,6 +104,34 @@ def validate_metadata_type(
             exceptions.append(exc)
 
 
+def database_connection_identity_unchanged(
+    stored_uri: Optional[str], incoming_uri: Optional[str]
+) -> bool:
+    """
+    Whether an incoming database config still points at the same connection
+    (driver, host, port -- everything except the credential) as the stored one.
+
+    Stored secrets may only be re-attached to an import when this holds:
+    database UUIDs are not secrets (they appear in every exported bundle and
+    in API responses), so re-attaching secrets on a UUID match alone would
+    let a hostile bundle repoint an existing connection at an
+    attacker-controlled server that then receives the victim's real
+    credentials.
+    """
+    if not stored_uri or not incoming_uri:
+        return False
+    try:
+        stored = make_url_safe(stored_uri)._replace(password=None)
+        incoming = make_url_safe(incoming_uri)._replace(password=None)
+    except Exception:  # pylint: disable=broad-except
+        # An unparseable URI cannot be compared; never attach secrets to it.
+        return False
+    # Compare the full URL minus the credential, not just host/port: query
+    # arguments become driver connect args and can themselves redirect the
+    # connection (e.g. ``?host=`` for postgres drivers).
+    return stored == incoming
+
+
 # pylint: disable=too-many-locals,too-many-arguments
 # ruff: noqa: C901
 def load_configs(
@@ -141,6 +170,21 @@ def load_configs(
             SSHTunnel.uuid, SSHTunnel.private_key_password
         ).all()
     }
+    # load connection endpoints so stored secrets are only re-attached to a
+    # config that still points at the same endpoint (see
+    # database_connection_identity_unchanged)
+    db_sqlalchemy_uris: dict[str, str] = {
+        str(uuid): sqlalchemy_uri
+        for uuid, sqlalchemy_uri in db.session.query(
+            Database.uuid, Database.sqlalchemy_uri
+        ).all()
+    }
+    db_ssh_tunnel_servers: dict[str, tuple[Any, Any]] = {
+        str(uuid): (server_address, server_port)
+        for uuid, server_address, server_port in db.session.query(
+            SSHTunnel.uuid, SSHTunnel.server_address, SSHTunnel.server_port
+        ).all()
+    }
     for file_name, content in contents.items():
         # skip directories
         if not content:
@@ -151,6 +195,38 @@ def load_configs(
         if schema:
             try:
                 config = load_yaml(file_name, content)
+                if not isinstance(config, dict):
+                    # A syntactically valid YAML document whose top-level
+                    # value is a scalar or list (not a mapping) has no
+                    # fields to validate against the schema; report it the
+                    # same way as unparseable YAML instead of letting the
+                    # ``.get()`` calls below raise an unhandled AttributeError.
+                    raise ValidationError({file_name: "Not a valid YAML file"})
+
+                # Stored secrets are only reusable when the incoming config
+                # still points at the same endpoint as the stored one; a UUID
+                # match alone must never rebind stored credentials to a new
+                # host (see database_connection_identity_unchanged).
+                db_secrets_reusable = (
+                    prefix == "databases"
+                    and database_connection_identity_unchanged(
+                        db_sqlalchemy_uris.get(str(config.get("uuid"))),
+                        config.get("sqlalchemy_uri"),
+                    )
+                )
+                incoming_tunnel = config.get("ssh_tunnel") or {}
+                stored_tunnel_server = db_ssh_tunnel_servers.get(
+                    str(config.get("uuid"))
+                )
+                tunnel_secrets_reusable = (
+                    prefix == "databases"
+                    and stored_tunnel_server is not None
+                    and (
+                        incoming_tunnel.get("server_address"),
+                        incoming_tunnel.get("server_port"),
+                    )
+                    == stored_tunnel_server
+                )
 
                 # populate passwords from the request, from YAML config,
                 # or from existing DBs
@@ -159,14 +235,15 @@ def load_configs(
                 elif prefix == "databases" and config.get("password"):
                     # password already in YAML config, keep it
                     pass
-                elif prefix == "databases" and config["uuid"] in db_passwords:
+                elif db_secrets_reusable and config["uuid"] in db_passwords:
                     config["password"] = db_passwords[config["uuid"]]
 
                 # populate ssh_tunnel_passwords from the request or from existing DBs
                 if file_name in ssh_tunnel_passwords:
                     config["ssh_tunnel"]["password"] = ssh_tunnel_passwords[file_name]
                 elif (
-                    prefix == "databases" and config["uuid"] in db_ssh_tunnel_passwords
+                    tunnel_secrets_reusable
+                    and config["uuid"] in db_ssh_tunnel_passwords
                 ):
                     config["ssh_tunnel"]["password"] = db_ssh_tunnel_passwords[
                         config["uuid"]
@@ -178,7 +255,7 @@ def load_configs(
                         file_name
                     ]
                 elif (
-                    prefix == "databases"
+                    tunnel_secrets_reusable
                     and config["uuid"] in db_ssh_tunnel_private_keys
                 ):
                     config["ssh_tunnel"]["private_key"] = db_ssh_tunnel_private_keys[
@@ -191,7 +268,7 @@ def load_configs(
                         ssh_tunnel_priv_key_passwords[file_name]
                     )
                 elif (
-                    prefix == "databases"
+                    tunnel_secrets_reusable
                     and config["uuid"] in db_ssh_tunnel_priv_key_passws
                 ):
                     config["ssh_tunnel"]["private_key_password"] = (
diff --git a/superset/commands/query/importers/v1/utils.py b/superset/commands/query/importers/v1/utils.py
index d611aa5e3ac..08c9997c942 100644
--- a/superset/commands/query/importers/v1/utils.py
+++ b/superset/commands/query/importers/v1/utils.py
@@ -17,16 +17,52 @@
 
 from typing import Any
 
-from superset import db
+from superset import db, security_manager
+from superset.commands.exceptions import ImportFailedError
 from superset.models.sql_lab import SavedQuery
+from superset.utils.core import get_user
 
 
-def import_saved_query(config: dict[str, Any], overwrite: bool = False) -> SavedQuery:
+def import_saved_query(
+    config: dict[str, Any],
+    overwrite: bool = False,
+    ignore_permissions: bool = False,
+) -> SavedQuery:
+    """Import a saved query from a config dict, handling existing matches.
+
+    A saved query is a personal, per-user asset: the REST API scopes read,
+    update and delete to ``created_by == g.user`` (``SavedQueryFilter``).
+    The same object-level rule is enforced here on the overwrite path so an
+    importer cannot replace another user's saved query (and the SQL the
+    victim will later run under their own grants) by reusing its UUID in an
+    import bundle -- matching the permission checks every sibling importer
+    (chart, dashboard, dataset, database, theme) already performs.
+    """
+    can_write = ignore_permissions or security_manager.can_access(
+        "can_write",
+        "SavedQuery",
+    )
     existing = db.session.query(SavedQuery).filter_by(uuid=config["uuid"]).first()
     if existing:
-        if not overwrite:
+        if not overwrite or not can_write:
             return existing
+        # ``user`` is None on background paths (no Flask request user);
+        # combined with ``can_write`` (typically from
+        # ``ignore_permissions=True``) the ownership check is skipped there
+        # because the caller has already established trust -- mirroring the
+        # chart importer.
+        user = get_user()
+        if user and not (security_manager.is_admin() or existing.created_by == user):
+            raise ImportFailedError(
+                f"Saved query (uuid {config['uuid']}) already exists and "
+                "user doesn't have permissions to overwrite it"
+            )
         config["id"] = existing.id
+    elif not can_write:
+        raise ImportFailedError(
+            "Saved query doesn't exist and user doesn't have permission to "
+            "create saved queries"
+        )
 
     saved_query = SavedQuery.import_from_dict(config, recursive=False)
     if saved_query.id is None:
diff --git a/superset/examples/utils.py b/superset/examples/utils.py
index 8b7a8c1e87f..d15dade0b64 100644
--- a/superset/examples/utils.py
+++ b/superset/examples/utils.py
@@ -258,7 +258,7 @@ def load_configs_from_directory(
 
     # removing "type" from the metadata allows us to import any exported model
     # from the unzipped directory directly
-    metadata = yaml.load(contents.get(METADATA_FILE_NAME, "{}"), Loader=yaml.Loader)  # noqa: S506
+    metadata = yaml.safe_load(contents.get(METADATA_FILE_NAME, "{}"))
     if "type" in metadata:
         del metadata["type"]
     contents[METADATA_FILE_NAME] = yaml.dump(metadata)
diff --git a/tests/integration_tests/dashboards/api_tests.py b/tests/integration_tests/dashboards/api_tests.py
index 3432571b187..5dbe223ce3e 100644
--- a/tests/integration_tests/dashboards/api_tests.py
+++ b/tests/integration_tests/dashboards/api_tests.py
@@ -3299,6 +3299,14 @@ class TestDashboardApi(ApiEditorsTestCaseMixin, InsertChartMixin, SupersetTestCa
         }
 
     def test_import_dashboard_v0_export(self):
+        """
+        Dashboard API: legacy v0-format exports are rejected by the HTTP
+        import endpoint. The v0 command is not registered in the import
+        dispatcher (see superset/commands/dashboard/importers/dispatcher.py)
+        because it overrides charts/dashboards matched by remote_id with no
+        per-object ownership check. Legacy v0 JSON is still importable via
+        the `legacy_import_dashboards` CLI command.
+        """
         num_dashboards = db.session.query(Dashboard).count()
 
         self.login(ADMIN_USERNAME)
@@ -3313,20 +3321,28 @@ class TestDashboardApi(ApiEditorsTestCaseMixin, InsertChartMixin, SupersetTestCa
         rv = self.client.post(uri, data=form_data, content_type="multipart/form-data")
         response = json.loads(rv.data.decode("utf-8"))
 
-        assert rv.status_code == 200
-        assert response == {"message": "OK"}
-        assert db.session.query(Dashboard).count() == num_dashboards + 1
-
-        dashboard = (
-            db.session.query(Dashboard).filter_by(dashboard_title="Births 2").one()
-        )
-        chart = dashboard.slices[0]
-        dataset = chart.table
-
-        db.session.delete(dashboard)
-        db.session.delete(chart)
-        db.session.delete(dataset)
-        db.session.commit()
+        assert rv.status_code == 422
+        assert response == {
+            "errors": [
+                {
+                    "message": "Could not find a valid command to import file",
+                    "error_type": "GENERIC_COMMAND_ERROR",
+                    "level": "warning",
+                    "extra": {
+                        "issue_codes": [
+                            {
+                                "code": 1010,
+                                "message": (
+                                    "Issue 1010 - Superset encountered an "
+                                    "error while running a command."
+                                ),
+                            }
+                        ]
+                    },
+                }
+            ]
+        }
+        assert db.session.query(Dashboard).count() == num_dashboards
 
     @patch("superset.commands.database.importers.v1.utils.add_permissions")
     def test_import_dashboard_overwrite(self, mock_add_permissions):
diff --git a/tests/integration_tests/datasets/api_tests.py b/tests/integration_tests/datasets/api_tests.py
index 56f3e38efd7..ab4c26c7ce8 100644
--- a/tests/integration_tests/datasets/api_tests.py
+++ b/tests/integration_tests/datasets/api_tests.py
@@ -2676,6 +2676,14 @@ class TestDatasetApi(SupersetTestCase):
         self.items_to_delete = [dataset, database]
 
     def test_import_dataset_v0_export(self):
+        """
+        Dataset API: legacy v0-format exports are rejected by the HTTP
+        import endpoint. The v0 command is not registered in the import
+        dispatcher (see superset/commands/dataset/importers/dispatcher.py)
+        because it overrides datasets matched by (table_name, schema,
+        database) with no per-object ownership check. Legacy v0 exports are
+        still importable via the `legacy_import_datasources` CLI command.
+        """
         num_datasets = db.session.query(SqlaTable).count()
 
         self.login(ADMIN_USERNAME)
@@ -2692,14 +2700,25 @@ class TestDatasetApi(SupersetTestCase):
         rv = self.client.post(uri, data=form_data, content_type="multipart/form-data")
         response = json.loads(rv.data.decode("utf-8"))
 
-        assert rv.status_code == 200
-        assert response == {"message": "OK"}
-        assert db.session.query(SqlaTable).count() == num_datasets + 1
-
-        dataset = (
-            db.session.query(SqlaTable).filter_by(table_name="birth_names_2").one()
-        )
-        self.items_to_delete = [dataset]
+        assert rv.status_code == 422
+        assert response == {
+            "errors": [
+                {
+                    "message": "Could not find a valid command to import file",
+                    "error_type": "GENERIC_COMMAND_ERROR",
+                    "level": "warning",
+                    "extra": {
+                        "issue_codes": [
+                            {
+                                "code": 1010,
+                                "message": "Issue 1010 - Superset encountered an error while running a command.",  # noqa: E501
+                            }
+                        ]
+                    },
+                }
+            ]
+        }
+        assert db.session.query(SqlaTable).count() == num_datasets
 
     @patch("superset.commands.database.importers.v1.utils.add_permissions")
     def test_import_dataset_overwrite(self, mock_add_permissions):
diff --git a/tests/unit_tests/commands/importers/v1/import_saved_query_test.py b/tests/unit_tests/commands/importers/v1/import_saved_query_test.py
new file mode 100644
index 00000000000..33608dc7001
--- /dev/null
+++ b/tests/unit_tests/commands/importers/v1/import_saved_query_test.py
@@ -0,0 +1,126 @@
+# 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.
+"""Object-level authorization on the saved-query import path."""
+
+from unittest.mock import MagicMock
+
+import pytest
+from pytest_mock import MockerFixture
+
+from superset.commands.exceptions import ImportFailedError
+from superset.commands.query.importers.v1 import utils
+
+
+def _wire_existing(mocker: MockerFixture, existing: MagicMock | None) -> None:
+    mocker.patch.object(utils, "db")
+    utils.db.session.query.return_value.filter_by.return_value.first.return_value = (
+        existing
+    )
+
+
+def test_overwrite_of_another_users_saved_query_is_rejected(
+    mocker: MockerFixture,
+) -> None:
+    """Regression: ``import_saved_query`` used to overwrite any SavedQuery
+    matched by UUID with zero ownership checks, letting an importer replace
+    a victim's saved query with attacker SQL."""
+    attacker = MagicMock(name="attacker")
+    victim = MagicMock(name="victim")
+    existing = MagicMock(id=1, created_by=victim)
+    _wire_existing(mocker, existing)
+    mocker.patch.object(utils.security_manager, "can_access", return_value=True)
+    mocker.patch.object(utils.security_manager, "is_admin", return_value=False)
+    mocker.patch.object(utils, "get_user", return_value=attacker)
+    import_from_dict = mocker.patch.object(utils.SavedQuery, "import_from_dict")
+
+    with pytest.raises(ImportFailedError):
+        utils.import_saved_query({"uuid": "some-uuid"}, overwrite=True)
+
+    import_from_dict.assert_not_called()
+
+
+def test_owner_can_overwrite_own_saved_query(mocker: MockerFixture) -> None:
+    owner = MagicMock(name="owner")
+    existing = MagicMock(id=1, created_by=owner)
+    _wire_existing(mocker, existing)
+    mocker.patch.object(utils.security_manager, "can_access", return_value=True)
+    mocker.patch.object(utils.security_manager, "is_admin", return_value=False)
+    mocker.patch.object(utils, "get_user", return_value=owner)
+    import_from_dict = mocker.patch.object(utils.SavedQuery, "import_from_dict")
+    import_from_dict.return_value = MagicMock(id=1)
+
+    config = {"uuid": "some-uuid"}
+    utils.import_saved_query(config, overwrite=True)
+
+    assert config["id"] == 1
+    import_from_dict.assert_called_once()
+
+
+def test_admin_can_overwrite_another_users_saved_query(mocker: MockerFixture) -> None:
+    admin = MagicMock(name="admin")
+    victim = MagicMock(name="victim")
+    existing = MagicMock(id=1, created_by=victim)
+    _wire_existing(mocker, existing)
+    mocker.patch.object(utils.security_manager, "can_access", return_value=True)
+    mocker.patch.object(utils.security_manager, "is_admin", return_value=True)
+    mocker.patch.object(utils, "get_user", return_value=admin)
+    import_from_dict = mocker.patch.object(utils.SavedQuery, "import_from_dict")
+    import_from_dict.return_value = MagicMock(id=1)
+
+    config = {"uuid": "some-uuid"}
+    utils.import_saved_query(config, overwrite=True)
+
+    assert config["id"] == 1
+    import_from_dict.assert_called_once()
+
+
+def test_overwrite_without_can_write_returns_existing(
+    mocker: MockerFixture,
+) -> None:
+    existing = MagicMock(id=1)
+    _wire_existing(mocker, existing)
+    mocker.patch.object(utils.security_manager, "can_access", return_value=False)
+    import_from_dict = mocker.patch.object(utils.SavedQuery, "import_from_dict")
+
+    result = utils.import_saved_query({"uuid": "some-uuid"}, overwrite=True)
+
+    assert result is existing
+    import_from_dict.assert_not_called()
+
+
+def test_create_without_can_write_is_rejected(mocker: MockerFixture) -> None:
+    _wire_existing(mocker, None)
+    mocker.patch.object(utils.security_manager, "can_access", return_value=False)
+
+    with pytest.raises(ImportFailedError):
+        utils.import_saved_query({"uuid": "some-uuid"}, overwrite=False)
+
+
+def test_background_import_skips_ownership_check(mocker: MockerFixture) -> None:
+    """With no request user (CLI/background) and ignore_permissions, trust is
+    established by the caller — mirroring the chart importer."""
+    existing = MagicMock(id=1)
+    _wire_existing(mocker, existing)
+    mocker.patch.object(utils, "get_user", return_value=None)
+    import_from_dict = mocker.patch.object(utils.SavedQuery, "import_from_dict")
+    import_from_dict.return_value = MagicMock(id=1)
+
+    utils.import_saved_query(
+        {"uuid": "some-uuid"}, overwrite=True, ignore_permissions=True
+    )
+
+    import_from_dict.assert_called_once()
diff --git a/tests/unit_tests/commands/importers/v1/utils_test.py b/tests/unit_tests/commands/importers/v1/utils_test.py
index 58def5bebef..38e1a470800 100644
--- a/tests/unit_tests/commands/importers/v1/utils_test.py
+++ b/tests/unit_tests/commands/importers/v1/utils_test.py
@@ -16,10 +16,14 @@
 # under the License.
 """Tests for superset/commands/dataset/importers/v1/utils.py temporal helpers."""
 
+import gzip
+import io
 from unittest.mock import patch
 
 import pandas as pd
 import pytest
+from marshmallow.exceptions import ValidationError
+from sqlalchemy.orm import Session
 
 
 class TestConvertTemporalColumns:
@@ -119,6 +123,28 @@ class TestConvertTemporalColumns:
         assert call_args[1] == 2  # 2 out-of-bounds, 1 pre-existing null
 
 
+class TestReadBounded:
+    """``_read_bounded`` caps the bytes materialized from a dataset import
+    data URI, including after gzip decompression, so a small compressed
+    payload can't expand to an unbounded in-memory allocation."""
+
+    def test_rejects_oversized_gzip_stream(self) -> None:
+        """A small compressed payload that decompresses past the cap must fail."""
+        from superset.commands.dataset.importers.v1.utils import _read_bounded
+        from superset.commands.exceptions import ImportFailedError
+
+        payload = gzip.compress(b"a" * 100_000)
+        stream = gzip.GzipFile(fileobj=io.BytesIO(payload))
+        with pytest.raises(ImportFailedError):
+            _read_bounded(stream, max_bytes=10_000)
+
+    def test_passes_small_payload_through(self) -> None:
+        from superset.commands.dataset.importers.v1.utils import _read_bounded
+
+        buffer = _read_bounded(io.BytesIO(b"a,b\n1,2\n"), max_bytes=10_000)
+        assert buffer.read() == b"a,b\n1,2\n"
+
+
 class TestLoadYaml:
     def test_parser_error_raises_validation_error(self) -> None:
         """A malformed flow sequence raises yaml.parser.ParserError."""
@@ -138,3 +164,128 @@ class TestLoadYaml:
 
         with pytest.raises(ValidationError):
             load_yaml("test.yaml", 'key: "unterminated string')
+
+
+class TestLoadConfigsNonMappingYaml:
+    """A syntactically valid YAML document whose top-level value is a
+    scalar or list (not a mapping) must be reported as a schema validation
+    error, not raise an unhandled AttributeError from the ``config.get()``
+    calls that assume a mapping."""
+
+    def test_top_level_list_is_reported_as_validation_error(
+        self, session: Session
+    ) -> None:
+        from superset.commands.importers.v1.utils import load_configs
+        from superset.databases.schemas import ImportV1DatabaseSchema
+        from superset.models.core import Database
+
+        engine = session.get_bind()
+        Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+        contents = {"databases/malformed.yaml": "- not\n- a\n- mapping\n"}
+        exceptions: list[ValidationError] = []
+
+        configs = load_configs(
+            contents,
+            {"databases/": ImportV1DatabaseSchema()},
+            {},
+            exceptions,
+            {},
+            {},
+            {},
+            {},
+        )
+
+        assert configs == {}
+        assert len(exceptions) == 1
+        assert "databases/malformed.yaml" in exceptions[0].messages
+
+    def test_top_level_scalar_is_reported_as_validation_error(
+        self, session: Session
+    ) -> None:
+        from superset.commands.importers.v1.utils import load_configs
+        from superset.databases.schemas import ImportV1DatabaseSchema
+        from superset.models.core import Database
+
+        engine = session.get_bind()
+        Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+        contents = {"databases/malformed.yaml": "just a string"}
+        exceptions: list[ValidationError] = []
+
+        configs = load_configs(
+            contents,
+            {"databases/": ImportV1DatabaseSchema()},
+            {},
+            exceptions,
+            {},
+            {},
+            {},
+            {},
+        )
+
+        assert configs == {}
+        assert len(exceptions) == 1
+        assert "databases/malformed.yaml" in exceptions[0].messages
+
+
+class TestDatabaseConnectionIdentityUnchanged:
+    """Stored database secrets (password, SSH tunnel key) may only be
+    re-attached to an import when the incoming config still points at the
+    same connection endpoint as the stored one — a UUID match alone is not
+    enough, since UUIDs are not secrets (they appear in every exported
+    bundle)."""
+
+    def test_same_endpoint_differing_masked_credential_is_unchanged(self) -> None:
+        from superset.commands.importers.v1.utils import (
+            database_connection_identity_unchanged,
+        )
+
+        assert database_connection_identity_unchanged(
+            "postgresql://user:XXXXXXXXXX@host1:5432/db",
+            "postgresql://user:pass@host1:5432/db",
+        )
+
+    def test_host_change_is_changed(self) -> None:
+        from superset.commands.importers.v1.utils import (
+            database_connection_identity_unchanged,
+        )
+
+        assert not database_connection_identity_unchanged(
+            "postgresql://user:XXXXXXXXXX@host1:5432/db",
+            "postgresql://user:XXXXXXXXXX@attacker.example.com:5432/db",
+        )
+
+    def test_port_change_is_changed(self) -> None:
+        from superset.commands.importers.v1.utils import (
+            database_connection_identity_unchanged,
+        )
+
+        assert not database_connection_identity_unchanged(
+            "postgresql://user:XXXXXXXXXX@host1:5432/db",
+            "postgresql://user:XXXXXXXXXX@host1:5433/db",
+        )
+
+    def test_query_args_can_redirect_the_connection(self) -> None:
+        """Query args become driver connect args (e.g. psycopg2 ``?host=``)
+        and can redirect the connection just like the host segment."""
+        from superset.commands.importers.v1.utils import (
+            database_connection_identity_unchanged,
+        )
+
+        assert not database_connection_identity_unchanged(
+            "postgresql://user:XXXXXXXXXX@host1:5432/db",
+            "postgresql://user:XXXXXXXXXX@host1:5432/db?host=attacker.example.com",
+        )
+
+    def test_missing_either_side_is_never_reusable(self) -> None:
+        from superset.commands.importers.v1.utils import (
+            database_connection_identity_unchanged,
+        )
+
+        assert not database_connection_identity_unchanged(
+            None, "postgresql://user:pass@host1:5432/db"
+        )
+        assert not database_connection_identity_unchanged(
+            "postgresql://user:XXXXXXXXXX@host1:5432/db", None
+        )
diff --git a/superset/commands/query/importers/v1/utils.py b/tests/unit_tests/dashboards/commands/importers/dispatcher_test.py
similarity index 52%
copy from superset/commands/query/importers/v1/utils.py
copy to tests/unit_tests/dashboards/commands/importers/dispatcher_test.py
index d611aa5e3ac..e629c764fbc 100644
--- a/superset/commands/query/importers/v1/utils.py
+++ b/tests/unit_tests/dashboards/commands/importers/dispatcher_test.py
@@ -14,22 +14,19 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+"""
+The HTTP-reachable dashboard import dispatcher must never fall through to
+the legacy v0 importer, which instantiates models from attacker-controlled
+JSON pre-validation and overrides remote_id-matched charts/dashboards
+without any ownership check. Legacy JSON files remain importable via the
+dedicated `legacy_import_dashboards` CLI command, which uses the v0
+command directly.
+"""
 
-from typing import Any
 
-from superset import db
-from superset.models.sql_lab import SavedQuery
+def test_dashboard_import_dispatcher_excludes_v0() -> None:
+    """POST /api/v1/dashboard/import/ must not dispatch to the v0 importer."""
+    from superset.commands.dashboard.importers import v0
+    from superset.commands.dashboard.importers.dispatcher import command_versions
 
-
-def import_saved_query(config: dict[str, Any], overwrite: bool = False) -> SavedQuery:
-    existing = db.session.query(SavedQuery).filter_by(uuid=config["uuid"]).first()
-    if existing:
-        if not overwrite:
-            return existing
-        config["id"] = existing.id
-
-    saved_query = SavedQuery.import_from_dict(config, recursive=False)
-    if saved_query.id is None:
-        db.session.flush()
-
-    return saved_query
+    assert v0.ImportDashboardsCommand not in command_versions
diff --git a/tests/unit_tests/databases/commands/importers/v1/import_test.py b/tests/unit_tests/databases/commands/importers/v1/import_test.py
index 8f345da6b69..2ccf0cc1fb2 100644
--- a/tests/unit_tests/databases/commands/importers/v1/import_test.py
+++ b/tests/unit_tests/databases/commands/importers/v1/import_test.py
@@ -25,6 +25,7 @@ from sqlalchemy.orm.session import Session
 
 from superset import db
 from superset.commands.exceptions import ImportFailedError
+from superset.constants import PASSWORD_MASK
 from superset.utils import json
 
 
@@ -525,3 +526,242 @@ def test_import_datasources_cli_no_password_does_not_clobber_existing(
         "Importing a URI with no password segment must not overwrite an "
         f"existing encrypted password; got: {database.password!r}"
     )
+
+
+def test_import_database_host_change_requires_new_credentials(
+    mocker: MockerFixture, session: Session
+) -> None:
+    """
+    An overwrite that repoints an existing database at a different host must
+    not silently reuse the stored password (the database UUID is public in
+    every exported bundle, so this would exfiltrate the credential).
+    """
+    from superset import security_manager
+    from superset.commands.database.importers.v1.utils import import_database
+    from superset.models.core import Database
+    from tests.integration_tests.fixtures.importexport import database_config
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+
+    engine = db.session.get_bind()
+    Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+    config = copy.deepcopy(database_config)
+    database = import_database(config)
+    assert database.password == "pass"  # noqa: S105
+
+    hostile = copy.deepcopy(database_config)
+    hostile["sqlalchemy_uri"] = (
+        "postgresql://user:XXXXXXXXXX@attacker.example.com:5432/prod"
+    )
+    with pytest.raises(ImportFailedError):
+        import_database(hostile, overwrite=True)
+
+    # the same-host case (a normal re-import of an exported bundle) still works
+    unchanged = copy.deepcopy(database_config)
+    unchanged["sqlalchemy_uri"] = "postgresql://user:XXXXXXXXXX@host1"
+    unchanged["password"] = "pass"  # noqa: S105
+    database = import_database(unchanged, overwrite=True)
+    assert database.password == "pass"  # noqa: S105
+
+
+def test_import_database_host_change_with_new_credentials(
+    mocker: MockerFixture, session: Session
+) -> None:
+    """
+    A deliberate connection move is still possible when the import supplies
+    fresh credentials for the new endpoint.
+    """
+    from superset import security_manager
+    from superset.commands.database.importers.v1.utils import import_database
+    from superset.models.core import Database
+    from tests.integration_tests.fixtures.importexport import database_config
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+
+    engine = db.session.get_bind()
+    Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+    config = copy.deepcopy(database_config)
+    import_database(config)
+
+    moved = copy.deepcopy(database_config)
+    moved["sqlalchemy_uri"] = "postgresql://user:newpass@host2:5432/prod"
+    database = import_database(moved, overwrite=True)
+    assert database.password == "newpass"  # noqa: S105
+
+
+def test_import_database_unparseable_uri_treated_as_change(
+    mocker: MockerFixture, session: Session
+) -> None:
+    """
+    An unparseable ``sqlalchemy_uri`` cannot be compared to the stored one,
+    so it must be treated as a connection change (raising, rather than
+    silently reusing the stored credential) instead of propagating the
+    underlying parser exception.
+    """
+    from superset import security_manager
+    from superset.commands.database.importers.v1.utils import import_database
+    from superset.models.core import Database
+    from tests.integration_tests.fixtures.importexport import database_config
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+
+    engine = db.session.get_bind()
+    Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+    config = copy.deepcopy(database_config)
+    import_database(config)
+
+    hostile = copy.deepcopy(database_config)
+    hostile["sqlalchemy_uri"] = "not a valid uri"
+    with pytest.raises(ImportFailedError):
+        import_database(hostile, overwrite=True)
+
+
+def test_import_database_ssh_tunnel_host_change_requires_new_credentials(
+    mocker: MockerFixture, session: Session
+) -> None:
+    """
+    Repointing an existing database's SSH tunnel at a different server must
+    not silently reuse the stored tunnel credentials.
+    """
+    from superset import security_manager
+    from superset.commands.database.importers.v1.utils import import_database
+    from superset.models.core import Database
+    from tests.integration_tests.fixtures.importexport import database_config
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+
+    engine = db.session.get_bind()
+    Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+    ssh_tunnel = {
+        "server_address": "10.0.0.1",
+        "server_port": 22,
+        "username": "tunnel_user",
+        "password": "tunnel_pass",
+    }
+    config = copy.deepcopy(database_config)
+    config["ssh_tunnel"] = copy.deepcopy(ssh_tunnel)
+    database = import_database(config)
+    assert database.ssh_tunnel.server_address == "10.0.0.1"
+
+    hostile = copy.deepcopy(database_config)
+    hostile["ssh_tunnel"] = copy.deepcopy(ssh_tunnel)
+    hostile["ssh_tunnel"]["server_address"] = "attacker.example.com"
+    hostile["ssh_tunnel"]["password"] = PASSWORD_MASK
+    with pytest.raises(ImportFailedError):
+        import_database(hostile, overwrite=True)
+
+    # a deliberate move with a fresh tunnel credential still works
+    moved = copy.deepcopy(database_config)
+    moved["ssh_tunnel"] = copy.deepcopy(ssh_tunnel)
+    moved["ssh_tunnel"]["server_address"] = "10.0.0.2"
+    moved["ssh_tunnel"]["password"] = "new-tunnel-pass"  # noqa: S105
+    database = import_database(moved, overwrite=True)
+    assert database.ssh_tunnel.server_address == "10.0.0.2"
+    assert database.ssh_tunnel.password == "new-tunnel-pass"  # noqa: S105
+
+
+def test_import_database_ssh_tunnel_private_key_password_not_carried_over(
+    mocker: MockerFixture, session: Session
+) -> None:
+    """
+    A repoint that supplies a fresh SSH tunnel private_key but omits
+    private_key_password must not silently keep the old, real passphrase
+    attached to the new key — the importer must ask for it too.
+    """
+    from superset import security_manager
+    from superset.commands.database.importers.v1.utils import import_database
+    from superset.models.core import Database
+    from tests.integration_tests.fixtures.importexport import database_config
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+
+    engine = db.session.get_bind()
+    Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+    ssh_tunnel = {
+        "server_address": "10.0.0.1",
+        "server_port": 22,
+        "username": "tunnel_user",
+        "private_key": "-----BEGIN PRIVATE KEY-----\nOriginalKey\n-----END PRIVATE KEY-----\n",  # noqa: E501
+        "private_key_password": "original-passphrase",
+    }
+    config = copy.deepcopy(database_config)
+    config["ssh_tunnel"] = copy.deepcopy(ssh_tunnel)
+    import_database(config)
+
+    # fresh private_key supplied, but private_key_password is omitted
+    # entirely (not just masked) -- the old passphrase must not survive
+    # onto the new key at a different endpoint.
+    hostile = copy.deepcopy(database_config)
+    hostile["ssh_tunnel"] = copy.deepcopy(ssh_tunnel)
+    hostile["ssh_tunnel"]["server_address"] = "attacker.example.com"
+    hostile["ssh_tunnel"]["private_key"] = (
+        "-----BEGIN PRIVATE KEY-----\nAttackerKey\n-----END PRIVATE KEY-----\n"
+    )
+    del hostile["ssh_tunnel"]["private_key_password"]
+    with pytest.raises(ImportFailedError):
+        import_database(hostile, overwrite=True)
+
+    # same scenario, but explicitly masked instead of omitted
+    hostile_masked = copy.deepcopy(database_config)
+    hostile_masked["ssh_tunnel"] = copy.deepcopy(hostile["ssh_tunnel"])
+    hostile_masked["ssh_tunnel"]["private_key_password"] = PASSWORD_MASK
+    with pytest.raises(ImportFailedError):
+        import_database(hostile_masked, overwrite=True)
+
+    # supplying a fresh private_key_password alongside the fresh private_key
+    # is a deliberate move and must succeed
+    moved = copy.deepcopy(database_config)
+    moved["ssh_tunnel"] = copy.deepcopy(ssh_tunnel)
+    moved["ssh_tunnel"]["server_address"] = "10.0.0.2"
+    moved["ssh_tunnel"]["private_key"] = (
+        "-----BEGIN PRIVATE KEY-----\nNewKey\n-----END PRIVATE KEY-----\n"
+    )
+    moved["ssh_tunnel"]["private_key_password"] = "new-passphrase"  # noqa: S105
+    database = import_database(moved, overwrite=True)
+    assert database.ssh_tunnel.server_address == "10.0.0.2"
+    assert database.ssh_tunnel.private_key_password == "new-passphrase"  # noqa: S105
+
+
+def test_import_database_masked_encrypted_extra_not_revealed_on_host_change(
+    mocker: MockerFixture, session: Session
+) -> None:
+    """
+    An overwrite that repoints the connection at a different host, using a
+    fresh main password, must still not reveal the stored encrypted_extra
+    secrets onto the new endpoint: those are a separate credential from the
+    main connection password and stay masked until confirmed too.
+    """
+    from superset import security_manager
+    from superset.commands.database.importers.v1.utils import import_database
+    from superset.models.core import Database
+    from tests.integration_tests.fixtures.importexport import database_config
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+
+    engine = db.session.get_bind()
+    Database.metadata.create_all(engine)  # pylint: disable=no-member
+
+    config = copy.deepcopy(database_config)
+    config["masked_encrypted_extra"] = json.dumps({"my_secret": "original-value"})
+    import_database(config)
+
+    moved = copy.deepcopy(database_config)
+    moved["sqlalchemy_uri"] = "postgresql://user:newpass@host2:5432/prod"
+    moved["password"] = "newpass"  # noqa: S105
+    moved["masked_encrypted_extra"] = json.dumps({"my_secret": PASSWORD_MASK})
+    database = import_database(moved, overwrite=True)
+
+    assert database.password == "newpass"  # noqa: S105
+    encrypted = json.loads(database.encrypted_extra)
+    assert encrypted["my_secret"] == PASSWORD_MASK
diff --git a/superset/commands/query/importers/v1/utils.py b/tests/unit_tests/datasets/commands/importers/dispatcher_test.py
similarity index 53%
copy from superset/commands/query/importers/v1/utils.py
copy to tests/unit_tests/datasets/commands/importers/dispatcher_test.py
index d611aa5e3ac..9654d2b5603 100644
--- a/superset/commands/query/importers/v1/utils.py
+++ b/tests/unit_tests/datasets/commands/importers/dispatcher_test.py
@@ -14,22 +14,19 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+"""
+The HTTP-reachable dataset import dispatcher must never fall through to
+the legacy v0 importer, which matches datasets purely by
+(table_name, schema, database) and overrides them without any ownership
+check. Legacy YAML files remain importable via the dedicated
+`legacy_import_datasources` CLI command, which uses the v0 command
+directly.
+"""
 
-from typing import Any
 
-from superset import db
-from superset.models.sql_lab import SavedQuery
+def test_dataset_import_dispatcher_excludes_v0() -> None:
+    """POST /api/v1/dataset/import/ must not dispatch to the v0 importer."""
+    from superset.commands.dataset.importers import v0
+    from superset.commands.dataset.importers.dispatcher import command_versions
 
-
-def import_saved_query(config: dict[str, Any], overwrite: bool = False) -> SavedQuery:
-    existing = db.session.query(SavedQuery).filter_by(uuid=config["uuid"]).first()
-    if existing:
-        if not overwrite:
-            return existing
-        config["id"] = existing.id
-
-    saved_query = SavedQuery.import_from_dict(config, recursive=False)
-    if saved_query.id is None:
-        db.session.flush()
-
-    return saved_query
+    assert v0.ImportDatasetsCommand not in command_versions
diff --git a/tests/unit_tests/datasets/commands/importers/v1/import_test.py b/tests/unit_tests/datasets/commands/importers/v1/import_test.py
index 764a0be3b21..c3e65bb1055 100644
--- a/tests/unit_tests/datasets/commands/importers/v1/import_test.py
+++ b/tests/unit_tests/datasets/commands/importers/v1/import_test.py
@@ -2315,3 +2315,67 @@ def test_load_data_disables_proxy_when_internal_urls_disallowed(
         isinstance(handler, request.ProxyHandler) and not handler.proxies  # type: ignore[attr-defined]
         for handler in handlers
     )
+
+
+def test_load_data_bounds_gzip_download_before_decompression(
+    mocker: MockerFixture,
+) -> None:
+    """
+    For a ``.gz`` data URI, ``load_data`` must bound the raw (compressed)
+    download before decompressing it, not just the decompressed output --
+    otherwise an oversized or malformed compressed response could be read
+    in full before any size check applies.
+    """
+    from superset.commands.dataset.importers.v1.utils import load_data
+
+    mocker.patch("superset.commands.dataset.importers.v1.utils.validate_data_uri")
+    mocker.patch(
+        "superset.examples.helpers.normalize_example_data_url",
+        side_effect=lambda uri: uri,
+    )
+    mocker.patch(
+        "superset.commands.dataset.importers.v1.utils._convert_temporal_columns"
+    )
+    mocker.patch("superset.commands.dataset.importers.v1.utils.db.session.connection")
+    mock_df = Mock()
+    mock_df.keys.return_value = []
+    mocker.patch(
+        "superset.commands.dataset.importers.v1.utils.pd.read_csv",
+        return_value=mock_df,
+    )
+
+    raw_response = Mock()
+    mock_opener = Mock()
+    mock_opener.open.return_value = raw_response
+    mocker.patch(
+        "superset.commands.dataset.importers.v1.utils.request.build_opener",
+        return_value=mock_opener,
+    )
+
+    bounded_raw = io.BytesIO(b"")
+    decompressed = Mock()
+    mock_read_bounded = mocker.patch(
+        "superset.commands.dataset.importers.v1.utils._read_bounded",
+        side_effect=[bounded_raw, io.BytesIO(b"")],
+    )
+    mock_gzip_open = mocker.patch(
+        "superset.commands.dataset.importers.v1.utils.gzip.open",
+        return_value=decompressed,
+    )
+
+    dataset = Mock(spec=SqlaTable)
+    dataset.columns = []
+    dataset.table_name = "my_table"
+    dataset.schema = None
+
+    database = Mock(spec=Database)
+    database.sqlalchemy_uri = current_app.config["SQLALCHEMY_DATABASE_URI"]
+
+    load_data("https://example.org/data.csv.gz", dataset, database)
+
+    # the raw (still compressed) response is bounded first...
+    assert mock_read_bounded.call_args_list[0].args[0] is raw_response
+    # ...then gzip.open() decompresses the bounded buffer...
+    mock_gzip_open.assert_called_once_with(bounded_raw)
+    # ...and the decompressed output is bounded again before parsing.
+    assert mock_read_bounded.call_args_list[1].args[0] is decompressed
diff --git a/tests/unit_tests/examples/utils_test.py b/tests/unit_tests/examples/utils_test.py
index 0d71dadd3c4..9b7b8f6bd5e 100644
--- a/tests/unit_tests/examples/utils_test.py
+++ b/tests/unit_tests/examples/utils_test.py
@@ -20,6 +20,7 @@ from pathlib import Path
 from tempfile import TemporaryDirectory
 from unittest.mock import MagicMock, patch
 
+import pytest
 import yaml
 
 
@@ -204,3 +205,22 @@ def test_load_examples_from_configs_defaults(
         force_data=False,
     )
     mock_command.run.assert_called_once()
+
+
+def test_load_configs_from_directory_rejects_unsafe_yaml_metadata():
+    """metadata.yaml must be parsed with a safe YAML loader.
+
+    A bundle whose metadata.yaml carries a python/object/apply payload must be
+    rejected on parse instead of instantiating arbitrary Python objects.
+    """
+    from superset.examples.utils import load_configs_from_directory
+
+    with TemporaryDirectory() as tmpdir:
+        root = Path(tmpdir)
+        (root / "metadata.yaml").write_text("!!python/object/apply:os.getcwd []\n")
+
+        with patch("superset.examples.utils.ImportExamplesCommand") as mock_command_cls:
+            with pytest.raises(yaml.YAMLError):
+                load_configs_from_directory(root)
+
+        mock_command_cls.return_value.run.assert_not_called()