This is an automated email from the ASF dual-hosted git repository.
msyavuz 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 b139d19a410 fix(embedded): refuse an import that would wipe the
embedded guest private key (#45870)
b139d19a410 is described below
commit b139d19a410882b29cff841eecd4e7e56f466143
Author: Hugh A. Miles II <[email protected]>
AuthorDate: Fri Nov 13 13:20:27 2026 -0500
fix(embedded): refuse an import that would wipe the embedded guest private
key (#45870)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
---
UPDATING.md | 5 +-
docs/sip/embedded-fallback-credential.md | 6 +-
superset/commands/database/importers/v1/utils.py | 78 ++++++--
superset/commands/importers/v1/assets.py | 10 +-
superset/databases/utils.py | 28 +++
.../databases/commands/importers/v1/import_test.py | 205 +++++++++++++++++++++
tests/unit_tests/databases/schema_tests.py | 5 +-
tests/unit_tests/importexport/api_test.py | 142 ++++++++++++++
8 files changed, 457 insertions(+), 22 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index 8811f4d2914..cfc7dd329b6 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -88,8 +88,9 @@ assists people when migrating to a new version.
DATA-cache entry (or, under `GLOBAL_ASYNC_QUERIES`, a deduplicated chart
task) with a logged-in user's
per-user result; existing cached entries for such charts are effectively
invalidated
for guests. A malformed or incomplete `embedded_credentials` is rejected by
- `POST`/`PUT /api/v1/database/` and by `validate_parameters` rather than
stored and
- ignored while both embedding flags are enabled. Import refuses a credential
on a
+ `POST`/`PUT /api/v1/database/`, by `validate_parameters`, and by database
and asset
+ import (HTTP 400, naming the missing fields) rather than stored and ignored
while
+ both embedding flags are enabled. Import also refuses a credential on a
connection whose file turns **Impersonate logged in user** off and, with
either
flag off, a new or changed credential, as the API does. Validation
uses the engine's credential rules and edited credentials rather than stale
stored
diff --git a/docs/sip/embedded-fallback-credential.md
b/docs/sip/embedded-fallback-credential.md
index 56b93c2a137..2f86e99f3ac 100644
--- a/docs/sip/embedded-fallback-credential.md
+++ b/docs/sip/embedded-fallback-credential.md
@@ -243,8 +243,10 @@ does not let a token holder choose an identity.
`EMBEDDED_CREDENTIAL_FALLBACK` and `EMBEDDED_SUPERSET` are on and the
connection uses
OAuth2.
- **New validation** rejecting malformed or incomplete `embedded_credentials`
on
- `POST`/`PUT /api/v1/database/` and on `validate_parameters` while both
embedding flags
- are enabled. Import is deliberately not tightened, so existing exports still
load.
+ `POST`/`PUT /api/v1/database/`, on `validate_parameters`, and on database
and asset
+ import (HTTP 400) while both embedding flags are enabled. With either flag
off,
+ import refuses only a new or changed credential, so an export that leaves the
+ stored credential unchanged still loads.
No database migration: the credential lives in the existing `encrypted_extra`
column.
diff --git a/superset/commands/database/importers/v1/utils.py
b/superset/commands/database/importers/v1/utils.py
index b38ce50a726..67190d5c621 100644
--- a/superset/commands/database/importers/v1/utils.py
+++ b/superset/commands/database/importers/v1/utils.py
@@ -19,7 +19,6 @@ import logging
from typing import Any
from flask import current_app as app
-from sqlalchemy.engine.url import URL
from superset import db, is_feature_enabled, security_manager
from superset.commands.database.exceptions import DatabaseInvalidError
@@ -32,8 +31,12 @@ from superset.commands.exceptions import ImportFailedError,
ImportRefusedError
from superset.constants import EMBEDDED_CREDENTIALS_KEY, PASSWORD_MASK
from superset.databases.schemas import embedded_credentials_stranded
from superset.databases.ssh_tunnel.models import SSHTunnel
-from superset.databases.utils import embedded_credentials_present,
make_url_safe
-from superset.db_engine_specs import get_engine_spec
+from superset.databases.utils import (
+ embedded_credentials_incomplete,
+ embedded_credentials_missing_fields,
+ embedded_credentials_present,
+ make_url_safe,
+)
from superset.db_engine_specs.base import BaseEngineSpec
from superset.db_engine_specs.exceptions import SupersetDBAPIError
from superset.exceptions import (
@@ -82,14 +85,14 @@ def _refuse_stored_secret_reuse(existing: Database, config:
dict[str, Any]) -> N
)
-def _import_engine_spec(
- config: dict[str, Any], existing: Database | None
-) -> type[BaseEngineSpec]:
- """The engine spec of the connection as the import leaves it."""
- if existing:
- return existing.db_engine_spec
- url: URL = make_url_safe(config["sqlalchemy_uri"])
- return get_engine_spec(url.get_backend_name(),
driver=url.get_driver_name())
+def _import_engine_spec(config: dict[str, Any]) -> type[BaseEngineSpec]:
+ """
+ The engine spec of the connection as the import leaves it.
+
+ The incoming URI decides the engine: an overwrite can change it, and the
+ stored engine's rules would miss the new engine's secrets and fields.
+ """
+ return Database.get_db_engine_spec(make_url_safe(config["sqlalchemy_uri"]))
def _refuse_unusable_embedded_credentials(
@@ -132,7 +135,7 @@ def _refuse_unusable_embedded_credentials(
)
return
- engine_spec = engine_spec or _import_engine_spec(config, existing)
+ engine_spec = engine_spec or _import_engine_spec(config)
impersonate_user = config.get(
"impersonate_user", existing.impersonate_user if existing else False
)
@@ -173,6 +176,48 @@ def _refuse_embedded_credentials_while_disabled(
)
+def _refuse_incomplete_embedded_credentials(
+ database_name: str,
+ encrypted_extra: dict[str, Any],
+ engine_spec: type[BaseEngineSpec],
+) -> None:
+ """
+ Refuse a half-filled embedded guest credential, as the dialog and API do.
+
+ Only the secrets that arrive masked are revealed from the stored
credential,
+ so one the file leaves out entirely (e.g. a key-pair credential without its
+ private key) would replace the stored credential with one no embedded
+ viewer can log in with.
+ """
+ if not (
+ is_feature_enabled("EMBEDDED_CREDENTIAL_FALLBACK")
+ and is_feature_enabled("EMBEDDED_SUPERSET")
+ ):
+ return
+
+ credentials = encrypted_extra.get(EMBEDDED_CREDENTIALS_KEY)
+ if not embedded_credentials_incomplete(
+ credentials,
+ engine_spec.validate_embedded_credentials,
+ accept_json_string=False,
+ ):
+ return
+
+ sensitive_fields = engine_spec.encrypted_extra_sensitive_fields
+ labels = sensitive_fields if isinstance(sensitive_fields, dict) else {}
+ missing = [
+ field + (f" ({labels[field]})" if field in labels else "")
+ for field in embedded_credentials_missing_fields(credentials)
+ ]
+ raise ImportRefusedError(
+ f"Embedded guest credentials of database '{database_name}' are invalid
"
+ "or incomplete."
+ + (f" Missing: {', '.join(missing)}." if missing else "")
+ + " Provide all required fields or clear them to leave embedded
viewers "
+ "unconfigured."
+ )
+
+
def _sync_permissions_best_effort(database: Database) -> None:
"""
Sync catalog/schema permissions for ``database``, tolerating a transient
@@ -277,15 +322,20 @@ def import_database( # noqa: C901
# already storing a mask exports that way, since masking it changes
nothing.
engine_spec: type[BaseEngineSpec] | None = None
if config.get("encrypted_extra"):
- engine_spec = _import_engine_spec(config, existing)
+ engine_spec = _import_engine_spec(config)
+ payload = json.loads(config["encrypted_extra"])
if still_masked := json.get_masked_fields(
- json.loads(config["encrypted_extra"]),
+ payload,
engine_spec.encrypted_extra_sensitive_field_paths(),
):
raise ImportFailedError(
"Must provide value for masked_encrypted_extra field: "
+ ", ".join(still_masked)
)
+ if isinstance(payload, dict):
+ _refuse_incomplete_embedded_credentials(
+ config["database_name"], payload, engine_spec
+ )
_refuse_unusable_embedded_credentials(config, existing, engine_spec)
diff --git a/superset/commands/importers/v1/assets.py
b/superset/commands/importers/v1/assets.py
index 128236c23e0..14b786aeca4 100644
--- a/superset/commands/importers/v1/assets.py
+++ b/superset/commands/importers/v1/assets.py
@@ -66,8 +66,14 @@ from superset.utils.decorators import on_error, transaction
def _on_import_error(ex: Exception) -> None:
- """Keep dependency validation actionable after the transaction rolls
back."""
- if isinstance(ex, SemanticReferenceError):
+ """
+ Keep dependency validation and deliberate import refusals actionable after
+ the transaction rolls back.
+
+ An ``ImportFailedError`` names what the bundle must change, e.g. a secret
it
+ must provide; re-raising it bare would leave only "unknown reason".
+ """
+ if isinstance(ex, (SemanticReferenceError, ImportFailedError)):
raise ex
on_error(ex, catches=(Exception,), reraise=ImportFailedError)
diff --git a/superset/databases/utils.py b/superset/databases/utils.py
index 7dd6abb8084..5fb88cd9477 100644
--- a/superset/databases/utils.py
+++ b/superset/databases/utils.py
@@ -24,6 +24,7 @@ from sqlalchemy.engine.url import make_url, URL
from sqlalchemy.exc import NoSuchTableError
from superset.commands.database.exceptions import DatabaseInvalidError
+from superset.constants import EMBEDDED_CREDENTIALS_KEY
from superset.sql.parse import Table
from superset.utils import json
@@ -270,3 +271,30 @@ def embedded_credentials_incomplete(
return True
return validate_credentials(value) is None
+
+
+def embedded_credentials_missing_fields(credentials: Any) -> list[str]:
+ """
+ Name the fields of the canonical credential shape that ``credentials``
lacks.
+
+ Paths are JSONPath into Secure Extra (``$.embedded_credentials.<field>``),
the
+ form the import already uses to name a secret it needs. Returns an empty
list
+ when nothing canonical is missing, e.g. an unknown ``auth_method`` or a
shape
+ only an engine-specific validator rejects.
+ """
+ if not isinstance(credentials, dict):
+ return []
+
+ missing: list[str] = []
+ if not _is_present(credentials.get("username")):
+ missing.append("username")
+
+ auth_method = credentials.get("auth_method", "password")
+ if auth_method == "keypair":
+ if not _is_present(credentials.get("privatekey_body")):
+ missing.append("privatekey_body")
+ elif auth_method == "password":
+ if not _is_present(credentials.get("password")):
+ missing.append("password")
+
+ return [f"$.{EMBEDDED_CREDENTIALS_KEY}.{field}" for field in missing]
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 9510aed8ab5..b66ba063555 100644
--- a/tests/unit_tests/databases/commands/importers/v1/import_test.py
+++ b/tests/unit_tests/databases/commands/importers/v1/import_test.py
@@ -1237,3 +1237,208 @@ def
test_an_unparseable_stored_secure_extra_is_refused_not_a_server_error() -> N
_refuse_embedded_credentials_while_disabled(
"imported", {"username": "svc", "password": "pw"}, existing
)
+
+
+EMBEDDED_KEYPAIR = {
+ "username": "EMBED_SVC",
+ "auth_method": "keypair",
+ "privatekey_body": "-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE
KEY-----\n",
+ "privatekey_pass": "passphrase",
+}
+
+
+def _import_snowflake_with_stored_keypair(mocker: MockerFixture) -> "Database":
+ from superset import security_manager
+ from superset.commands.database.importers.v1.utils import import_database
+ from superset.models.core import Database
+
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+ Database.metadata.create_all(db.session.get_bind()) # pylint:
disable=no-member
+
+ existing = import_database(_snowflake_config(EMBEDDED_KEYPAIR))
+ db.session.flush()
+ return existing
+
+
+@with_feature_flags(EMBEDDED_SUPERSET=True, EMBEDDED_CREDENTIAL_FALLBACK=True)
+def test_import_database_refuses_embedded_credential_missing_private_key(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """
+ An overwrite whose embedded key-pair credential leaves out the private key
+ is refused, naming the key, and the stored key stays (sc-127530).
+
+ The dialog and the API refuse the same half-filled credential; without this
+ the import replaced the stored credential with one no viewer can log in
with.
+ """
+ from superset.commands.database.importers.v1.utils import import_database
+
+ existing = _import_snowflake_with_stored_keypair(mocker)
+
+ half_filled = {
+ "username": "EMBED_SVC",
+ "auth_method": "keypair",
+ "privatekey_pass": PASSWORD_MASK,
+ }
+ with pytest.raises(
+ ImportFailedError, match=r"\$\.embedded_credentials\.privatekey_body"
+ ):
+ import_database(_snowflake_config(half_filled), overwrite=True)
+
+ stored = json.loads(existing.encrypted_extra)["embedded_credentials"]
+ assert stored == EMBEDDED_KEYPAIR
+
+
+@with_feature_flags(EMBEDDED_SUPERSET=True, EMBEDDED_CREDENTIAL_FALLBACK=True)
[email protected](
+ "secure_extra_key", ["masked_encrypted_extra", "encrypted_extra"]
+)
+def test_import_database_refuses_embedded_credential_as_a_json_string(
+ mocker: MockerFixture, session: Session, secure_extra_key: str
+) -> None:
+ """
+ The value is stored as sent and a string is refused at query time, so
however
+ complete the JSON inside it, an overwrite would lose a working credential.
+ """
+ from superset.commands.database.importers.v1.utils import import_database
+
+ existing = _import_snowflake_with_stored_keypair(mocker)
+
+ config = _snowflake_config(EMBEDDED_KEYPAIR)
+ del config["masked_encrypted_extra"]
+ config[secure_extra_key] = json.dumps(
+ {
+ "oauth2_client_info": {"id": "client", "secret": "client-secret"},
+ "embedded_credentials": json.dumps({"username": "svc", "password":
"pw"}),
+ }
+ )
+ with pytest.raises(ImportFailedError, match="invalid or incomplete"):
+ import_database(config, overwrite=True)
+
+ stored = json.loads(existing.encrypted_extra)["embedded_credentials"]
+ assert stored == EMBEDDED_KEYPAIR
+
+
+@with_feature_flags(EMBEDDED_SUPERSET=True, EMBEDDED_CREDENTIAL_FALLBACK=True)
+def test_import_database_refuses_new_db_with_incomplete_embedded_credential(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """A new connection can't be created with a half-filled credential
either."""
+ from superset import security_manager
+ from superset.commands.database.importers.v1.utils import import_database
+ from superset.models.core import Database
+
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+ Database.metadata.create_all(db.session.get_bind()) # pylint:
disable=no-member
+
+ with pytest.raises(ImportFailedError,
match=r"\$\.embedded_credentials\.password"):
+ import_database(_snowflake_config({"username": "EMBED_SVC"}))
+
+ assert db.session.query(Database).count() == 0
+
+
+@with_feature_flags(EMBEDDED_SUPERSET=True, EMBEDDED_CREDENTIAL_FALLBACK=True)
+def test_import_database_keeps_complete_embedded_credential_on_overwrite(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """A complete credential, its secrets masked, overwrites and reveals as
before."""
+ from superset.commands.database.importers.v1.utils import import_database
+
+ _import_snowflake_with_stored_keypair(mocker)
+
+ masked = {
+ **EMBEDDED_KEYPAIR,
+ "privatekey_body": PASSWORD_MASK,
+ "privatekey_pass": PASSWORD_MASK,
+ }
+ database = import_database(_snowflake_config(masked), overwrite=True)
+
+ stored = json.loads(database.encrypted_extra)["embedded_credentials"]
+ assert stored == EMBEDDED_KEYPAIR
+
+
+def test_import_database_checks_masks_with_the_incoming_engine(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """
+ An overwrite moving to another engine is checked against that engine's
paths.
+
+ The stored engine's paths would not list the new engine's secret, so its
mask
+ would be stored as the credential.
+ """
+ from superset import security_manager
+ from superset.commands.database.importers.v1.utils import import_database
+ from superset.models.core import Database
+
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+ Database.metadata.create_all(db.session.get_bind()) # pylint:
disable=no-member
+
+ config = {
+ "database_name": "moved_connection",
+ "sqlalchemy_uri": "postgresql://user@host/db",
+ "uuid": "7d2c1ee7-1d83-4f57-9a8e-1a2b3c4d5e6f",
+ "version": "1.0.0",
+ "extra": {},
+ }
+ existing = import_database(copy.deepcopy(config))
+ db.session.flush()
+
+ moved = {
+ **copy.deepcopy(config),
+ "sqlalchemy_uri": "snowflake://user:new-pw@account/db",
+ # Only the incoming engine lists this secret. Every engine lists the
+ # embedded credential's paths, so those would not tell the engines
apart.
+ "masked_encrypted_extra": json.dumps(
+ {"auth_params": {"privatekey_body": PASSWORD_MASK}}
+ ),
+ }
+ with pytest.raises(ImportFailedError,
match=r"\$\.auth_params\.privatekey_body"):
+ import_database(moved, overwrite=True)
+
+ assert existing.encrypted_extra is None
+
+
+@with_feature_flags(EMBEDDED_SUPERSET=True, EMBEDDED_CREDENTIAL_FALLBACK=True)
+def
test_import_database_refuses_incomplete_credential_in_plain_encrypted_extra(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """The completeness check also covers a file with only
``encrypted_extra``."""
+ from superset.commands.database.importers.v1.utils import import_database
+
+ existing = _import_snowflake_with_stored_keypair(mocker)
+
+ config = _snowflake_config(EMBEDDED_KEYPAIR)
+ del config["masked_encrypted_extra"]
+ config["encrypted_extra"] = json.dumps({"embedded_credentials":
{"username": "u"}})
+ with pytest.raises(ImportFailedError,
match=r"\$\.embedded_credentials\.password"):
+ import_database(config, overwrite=True)
+
+ stored = json.loads(existing.encrypted_extra)["embedded_credentials"]
+ assert stored == EMBEDDED_KEYPAIR
+
+
+@with_feature_flags(EMBEDDED_SUPERSET=True, EMBEDDED_CREDENTIAL_FALLBACK=True)
+def test_import_database_does_not_count_a_mask_as_an_embedded_password(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """The completeness check would take the mask for a present password."""
+ from superset.commands.database.importers.v1.utils import import_database
+
+ existing = _import_snowflake_with_stored_keypair(mocker)
+
+ config = _snowflake_config(EMBEDDED_KEYPAIR)
+ del config["masked_encrypted_extra"]
+ config["encrypted_extra"] = json.dumps(
+ {
+ "oauth2_client_info": {"id": "client", "secret": "client-secret"},
+ "embedded_credentials": {"username": "svc", "password":
PASSWORD_MASK},
+ }
+ )
+ with pytest.raises(ImportFailedError,
match=r"\$\.embedded_credentials\.password"):
+ import_database(config, overwrite=True)
+
+ stored = json.loads(existing.encrypted_extra)["embedded_credentials"]
+ assert stored == EMBEDDED_KEYPAIR
diff --git a/tests/unit_tests/databases/schema_tests.py
b/tests/unit_tests/databases/schema_tests.py
index ee045f9ebd7..1b3c1beee9a 100644
--- a/tests/unit_tests/databases/schema_tests.py
+++ b/tests/unit_tests/databases/schema_tests.py
@@ -721,11 +721,12 @@ def
test_masked_encrypted_extra_accepts_complete_or_absent_credentials(
def test_import_accepts_a_half_filled_embedded_credential() -> None:
"""
- Test that import is deliberately not tightened.
+ Test that the import schema is deliberately not tightened.
The check lives on `DatabaseParametersSchemaMixin` rather than on
`encrypted_extra_validator`, which also backs the import schemas: rejecting
- this on import would refuse existing exports.
+ this in the schema would refuse existing exports whatever the feature
flags.
+ `import_database` refuses it only while the embedded fallback is on.
"""
from superset.databases.schemas import ImportV1DatabaseSchema
diff --git a/tests/unit_tests/importexport/api_test.py
b/tests/unit_tests/importexport/api_test.py
index a131827e5da..6afebfc13dd 100644
--- a/tests/unit_tests/importexport/api_test.py
+++ b/tests/unit_tests/importexport/api_test.py
@@ -20,10 +20,12 @@
from io import BytesIO
from pathlib import Path
from typing import Any
+from uuid import UUID
from zipfile import is_zipfile, ZIP_DEFLATED, ZipFile
import pytest
from pytest_mock import MockerFixture
+from sqlalchemy.orm.session import Session
from superset import security_manager
from superset.utils import json
@@ -554,6 +556,146 @@ def test_bundle_imports_pass_encrypted_extra_secrets(
assert import_command.call_args.kwargs["encrypted_extra_secrets"] ==
secrets
+EMBEDDED_KEYPAIR = {
+ "username": "EMBED_SVC",
+ "auth_method": "keypair",
+ "privatekey_body": "-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE
KEY-----\n",
+ "privatekey_pass": "passphrase",
+}
+
+
[email protected](
+ "fallback_enabled,incoming,status,error",
+ [
+ pytest.param(
+ True,
+ {"username": "EMBED_SVC", "auth_method": "keypair",
"privatekey_pass": "X"},
+ 400,
+ "$.embedded_credentials.privatekey_body",
+ id="private-key-missing",
+ ),
+ pytest.param(
+ True,
+ {**EMBEDDED_KEYPAIR, "privatekey_body": "X", "privatekey_pass":
"X"},
+ 200,
+ None,
+ id="complete",
+ ),
+ pytest.param(
+ False,
+ {"username": "EMBED_SVC", "auth_method": "keypair",
"privatekey_pass": "X"},
+ 400,
+ "fallback is turned off",
+ id="fallback-off",
+ ),
+ ],
+)
+def test_import_assets_overwrite_embedded_credential(
+ mocker: MockerFixture,
+ session: Session,
+ client: Any,
+ full_api_access: None,
+ fallback_enabled: bool,
+ incoming: dict[str, str],
+ status: int,
+ error: str | None,
+) -> None:
+ """
+ An overwrite import whose embedded guest credential leaves out a required
+ value is refused with a message naming it, and the stored credential stays
+ (sc-127530). A complete credential imports as before; with the fallback
off,
+ a changed credential is refused too (sc-130270).
+
+ ``"X"`` in ``incoming`` stands for the export mask, which the import
reveals
+ from the stored credential.
+ """
+ import yaml
+
+ from superset import db
+ from superset.constants import PASSWORD_MASK
+ from superset.extensions import feature_flag_manager
+ from superset.models.core import Database
+
+ flags = {
+ "EMBEDDED_SUPERSET": True,
+ "EMBEDDED_CREDENTIAL_FALLBACK": fallback_enabled,
+ }
+ mocker.patch.object(
+ feature_flag_manager,
+ "get_feature_flags",
+ return_value={**(feature_flag_manager._feature_flags or {}), **flags},
+ )
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
mocker.patch("superset.commands.database.importers.v1.utils.add_permissions")
+ mocker.patch(
+
"superset.commands.importers.v1.assets.get_default_viewers_for_current_user",
+ return_value=[],
+ )
+
+ def mask(credentials: dict[str, str]) -> dict[str, str]:
+ return {k: PASSWORD_MASK if v == "X" else v for k, v in
credentials.items()}
+
+ db_uuid = "6c1c5ee7-1d83-4f57-9a8e-1a2b3c4d5e6f"
+ Database.metadata.create_all(db.session.get_bind()) # pylint:
disable=no-member
+ db.session.add(
+ Database(
+ database_name="snowflake_embedded",
+ sqlalchemy_uri="snowflake://base_user@account/db",
+ uuid=UUID(db_uuid),
+ impersonate_user=True,
+ encrypted_extra=json.dumps(
+ {
+ "oauth2_client_info": {"id": "client", "secret":
"client-secret"},
+ "embedded_credentials": EMBEDDED_KEYPAIR,
+ }
+ ),
+ )
+ )
+ db.session.commit()
+
+ contents = {
+ "metadata.yaml": yaml.safe_dump(
+ {"version": "1.0.0", "type": "assets", "timestamp":
"2026-10-29T00:00:00"}
+ ),
+ "databases/snowflake_embedded.yaml": yaml.safe_dump(
+ {
+ "database_name": "snowflake_embedded",
+ "sqlalchemy_uri": "snowflake://base_user@account/db",
+ "uuid": db_uuid,
+ "version": "1.0.0",
+ "impersonate_user": True,
+ "extra": {},
+ "masked_encrypted_extra": json.dumps(
+ {
+ "oauth2_client_info": {"id": "client", "secret":
PASSWORD_MASK},
+ "embedded_credentials": mask(incoming),
+ }
+ ),
+ }
+ ),
+ }
+ buf = BytesIO()
+ with ZipFile(buf, "w") as bundle:
+ for path, body in contents.items():
+ with bundle.open(f"assets_export/{path}", "w") as fp:
+ fp.write(body.encode())
+ buf.seek(0)
+
+ response = client.post(
+ "/api/v1/assets/import/",
+ data={"bundle": (buf, "assets_export.zip")},
+ content_type="multipart/form-data",
+ )
+
+ assert response.status_code == status, response.json
+ if error is not None:
+ assert error in response.json["errors"][0]["message"]
+ db.session.expire_all()
+ database = db.session.query(Database).filter_by(uuid=UUID(db_uuid)).one()
+ stored = json.loads(database.encrypted_extra)["embedded_credentials"]
+ assert stored == EMBEDDED_KEYPAIR
+
+
@pytest.mark.parametrize(
"resource,module,command",
[