From 5fda388eca33ca96a9b5cdf5541eb3a2c9bfeeef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Tue, 6 Oct 2026 17:52:25 +0200 Subject: [PATCH 1/5] Redact secrets in the MySQL connection string of error messages --- CHANGELOG.md | 3 +++ .../engines/ibis/connections/connect.py | 18 +++++++++++++----- datacontract/imports/mysql_importer.py | 4 ++-- tests/test_connect_mysql.py | 19 ++++++++++++++++--- tests/test_import_mysql.py | 13 +++++++++++++ 5 files changed, 47 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 679e3b61f..0fc9b4e0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `datacontract test`: check that foreign keys declared under `relationships` have no values missing from the referenced schema (#1691) +### Fixed +- Redact secrets in the MySQL connection string of error messages (#1706) + ## [1.2.3] - 2026-10-05 ### Added diff --git a/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 6f20b6aa2..1a0d39fea 100644 --- a/datacontract/engines/ibis/connections/connect.py +++ b/datacontract/engines/ibis/connections/connect.py @@ -612,12 +612,8 @@ def _connect_mysql_via_duckdb( con = duckdb.connect() _load_extension(con, "mysql", "mysql") - parts = [f"host={host}", f"port={port}", f"user={user}", f"password={password}"] - if database: - parts.append(f"database={database}") - conn_str = " ".join(parts).replace("'", "''") run.log_info(f"Attaching MySQL {host}:{port} via the duckdb mysql extension") - con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql)") + _attach_mysql(con, host, port, user, password, database) if data_contract.schema_: for schema_obj in data_contract.schema_: @@ -634,6 +630,18 @@ def _connect_mysql_via_duckdb( return ibis.duckdb.from_connection(con) +def _attach_mysql(con, host: str, port: int, user: str, password: str, database: str | None) -> None: + """ATTACH MySQL as ``mysqldb``, masking the password DuckDB spells out in its connection errors.""" + parts = [f"host={host}", f"port={port}", f"user={user}", f"password={password}"] + if database: + parts.append(f"database={database}") + conn_str = " ".join(parts).replace("'", "''") + try: + con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql)") + except Exception as e: + raise type(e)(str(e).replace(f"password={password}", "password=***")) from None + + def _materialize_attached_table(con, catalog: str, database: str | None, model: str): """Copy an attached-catalog table into a local DuckDB table named ``model``. diff --git a/datacontract/imports/mysql_importer.py b/datacontract/imports/mysql_importer.py index 165fc7e76..d7c7761f2 100644 --- a/datacontract/imports/mysql_importer.py +++ b/datacontract/imports/mysql_importer.py @@ -121,6 +121,7 @@ def _attach(host: str, port: int, database: str, config: Optional[Config] = None original_exception=e, ) + from datacontract.engines.ibis.connections.connect import _attach_mysql from datacontract.engines.ibis.connections.duckdb_connection import _load_extension user = config.get_mysql_username(required=True) @@ -128,9 +129,8 @@ def _attach(host: str, port: int, database: str, config: Optional[Config] = None con = duckdb.connect() _load_extension(con, "mysql", "mysql") - connection_string = _escape(f"host={host} port={port} user={user} password={password} database={database}") try: - con.execute(f"ATTACH '{connection_string}' AS mysqldb (TYPE mysql)") + _attach_mysql(con, host, port, user, password, database) except Exception as e: con.close() raise DataContractException( diff --git a/tests/test_connect_mysql.py b/tests/test_connect_mysql.py index 71638c042..1b39b9a96 100644 --- a/tests/test_connect_mysql.py +++ b/tests/test_connect_mysql.py @@ -1,11 +1,11 @@ """Unit tests for how connect_ibis attaches MySQL through DuckDB. -These do not hit MySQL: ``duckdb.connect``, the extension loader, and the ibis -wrapper are patched, and we only assert the ATTACH connection string built for -a given set of env vars. +These do not hit MySQL: most patch ``duckdb.connect`` and assert the ATTACH +connection string; the failed-attach test points the real extension at a closed port. """ import os +import traceback import duckdb import ibis @@ -76,3 +76,16 @@ def test_env_variables_override_the_contract_server_details(env, captured_statem assert "host=env-host" in attach assert "port=3308" in attach assert "database=env_db" in attach + + +def test_a_failed_attach_does_not_show_the_password(env): + env.setenv("DATACONTRACT_MYSQL_PASSWORD", "s3cret-pw") + env.setenv("DATACONTRACT_MYSQL_HOST", "127.0.0.1") + env.setenv("DATACONTRACT_MYSQL_PORT", "1") + + with pytest.raises(duckdb.Error) as exc_info: + _connect() + + output = "".join(traceback.format_exception(exc_info.value)) + assert "password=***" in output + assert "s3cret-pw" not in output diff --git a/tests/test_import_mysql.py b/tests/test_import_mysql.py index 90ef8a7e8..026ed595c 100644 --- a/tests/test_import_mysql.py +++ b/tests/test_import_mysql.py @@ -1,5 +1,7 @@ """Tests for the MySQL importer, run against a real MySQL container.""" +import traceback + import pytest import yaml from testcontainers.mysql import MySqlContainer @@ -152,6 +154,17 @@ def test_import_mysql_fails_on_an_unknown_table(): assert "No tables found" in exc_info.value.reason +def test_a_failed_connection_does_not_show_the_password(monkeypatch): + monkeypatch.setenv("DATACONTRACT_MYSQL_PASSWORD", "s3cret-pw") + + with pytest.raises(DataContractException) as exc_info: + _import(port=1) + + assert "password=***" in exc_info.value.reason + assert "s3cret-pw" not in exc_info.value.reason + assert "s3cret-pw" not in "".join(traceback.format_exception(exc_info.value.original_exception)) + + def test_import_mysql_requires_a_database(): with pytest.raises(DataContractException) as exc_info: DataContract.import_from_source("mysql", "127.0.0.1", database=None) From 6e1c4000c3ec71051947bbb36a91b3c2ffdc0a8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Tue, 6 Oct 2026 18:11:37 +0200 Subject: [PATCH 2/5] Pass the MySQL password in a DuckDB secret, keeping it out of every connection error --- .../engines/ibis/connections/connect.py | 18 +++++------------- .../ibis/connections/duckdb_connection.py | 13 +++++++++++++ datacontract/imports/mysql_importer.py | 3 +-- tests/test_connect_mysql.py | 6 ++---- tests/test_import_mysql.py | 1 - 5 files changed, 21 insertions(+), 20 deletions(-) diff --git a/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 1a0d39fea..bc39edce0 100644 --- a/datacontract/engines/ibis/connections/connect.py +++ b/datacontract/engines/ibis/connections/connect.py @@ -601,7 +601,11 @@ def _connect_mysql_via_duckdb( """ import duckdb - from datacontract.engines.ibis.connections.duckdb_connection import _load_extension, restrict_to_paths + from datacontract.engines.ibis.connections.duckdb_connection import ( + _attach_mysql, + _load_extension, + restrict_to_paths, + ) user = config.get_mysql_username(required=True) password = config.get_mysql_password(required=True) @@ -630,18 +634,6 @@ def _connect_mysql_via_duckdb( return ibis.duckdb.from_connection(con) -def _attach_mysql(con, host: str, port: int, user: str, password: str, database: str | None) -> None: - """ATTACH MySQL as ``mysqldb``, masking the password DuckDB spells out in its connection errors.""" - parts = [f"host={host}", f"port={port}", f"user={user}", f"password={password}"] - if database: - parts.append(f"database={database}") - conn_str = " ".join(parts).replace("'", "''") - try: - con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql)") - except Exception as e: - raise type(e)(str(e).replace(f"password={password}", "password=***")) from None - - def _materialize_attached_table(con, catalog: str, database: str | None, model: str): """Copy an attached-catalog table into a local DuckDB table named ``model``. diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index da8a5909c..dc788fc78 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -507,6 +507,19 @@ def _load_extension(con, name: str, extra: str) -> None: ) from e +def _attach_mysql(con, host: str, port: int, user: str, password: str, database: str | None) -> None: + """ATTACH MySQL as ``mysqldb``; the password goes in a secret, as DuckDB echoes the ATTACH string in its errors.""" + parts = [f"host={host}", f"port={port}", f"user={user}"] + if database: + parts.append(f"database={database}") + conn_str = " ".join(parts).replace("'", "''") + con.execute("CREATE SECRET mysqldb_password (TYPE mysql, PASSWORD ?)", [password]) + try: + con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql, SECRET mysqldb_password)") + finally: + con.execute("DROP SECRET mysqldb_password") + + def _sql_literal(value) -> str: """Escape a value for a single-quoted duckdb string literal. diff --git a/datacontract/imports/mysql_importer.py b/datacontract/imports/mysql_importer.py index d7c7761f2..69cec3fca 100644 --- a/datacontract/imports/mysql_importer.py +++ b/datacontract/imports/mysql_importer.py @@ -121,8 +121,7 @@ def _attach(host: str, port: int, database: str, config: Optional[Config] = None original_exception=e, ) - from datacontract.engines.ibis.connections.connect import _attach_mysql - from datacontract.engines.ibis.connections.duckdb_connection import _load_extension + from datacontract.engines.ibis.connections.duckdb_connection import _attach_mysql, _load_extension user = config.get_mysql_username(required=True) password = config.get_mysql_password(required=True) diff --git a/tests/test_connect_mysql.py b/tests/test_connect_mysql.py index 1b39b9a96..62affa77d 100644 --- a/tests/test_connect_mysql.py +++ b/tests/test_connect_mysql.py @@ -32,7 +32,7 @@ def captured_statements(monkeypatch): statements = [] class FakeConnection: - def execute(self, sql): + def execute(self, sql, parameters=None): statements.append(sql) monkeypatch.setattr(duckdb, "connect", lambda: FakeConnection()) @@ -86,6 +86,4 @@ def test_a_failed_attach_does_not_show_the_password(env): with pytest.raises(duckdb.Error) as exc_info: _connect() - output = "".join(traceback.format_exception(exc_info.value)) - assert "password=***" in output - assert "s3cret-pw" not in output + assert "s3cret-pw" not in "".join(traceback.format_exception(exc_info.value)) diff --git a/tests/test_import_mysql.py b/tests/test_import_mysql.py index 026ed595c..e3ea3b440 100644 --- a/tests/test_import_mysql.py +++ b/tests/test_import_mysql.py @@ -160,7 +160,6 @@ def test_a_failed_connection_does_not_show_the_password(monkeypatch): with pytest.raises(DataContractException) as exc_info: _import(port=1) - assert "password=***" in exc_info.value.reason assert "s3cret-pw" not in exc_info.value.reason assert "s3cret-pw" not in "".join(traceback.format_exception(exc_info.value.original_exception)) From e507248e6e352fd01fc40b37c002eee5c46417fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Tue, 6 Oct 2026 18:11:38 +0200 Subject: [PATCH 3/5] Hide local variables in --debug tracebacks, which could hold credentials --- CHANGELOG.md | 1 + datacontract/cli.py | 2 ++ tests/test_import_mysql.py | 20 ++++++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fc9b4e0a..be1d75104 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Redact secrets in the MySQL connection string of error messages (#1706) +- `--debug` tracebacks no longer print local variables, which could hold credentials ## [1.2.3] - 2026-10-05 diff --git a/datacontract/cli.py b/datacontract/cli.py index 93f3aaf81..0b700b52b 100644 --- a/datacontract/cli.py +++ b/datacontract/cli.py @@ -130,6 +130,8 @@ def parse_args(self, ctx: Context, args): cls=OrderedCommandsWithMigrationHints, no_args_is_help=True, add_completion=False, + # the locals of a --debug traceback can hold credentials + pretty_exceptions_show_locals=False, help="CLI to manage data contracts. Documentation: https://docs.datacontract.com", epilog="Read the full documentation at https://docs.datacontract.com", ) diff --git a/tests/test_import_mysql.py b/tests/test_import_mysql.py index e3ea3b440..adfe6e575 100644 --- a/tests/test_import_mysql.py +++ b/tests/test_import_mysql.py @@ -1,5 +1,7 @@ """Tests for the MySQL importer, run against a real MySQL container.""" +import subprocess +import sys import traceback import pytest @@ -164,6 +166,24 @@ def test_a_failed_connection_does_not_show_the_password(monkeypatch): assert "s3cret-pw" not in "".join(traceback.format_exception(exc_info.value.original_exception)) +def test_the_debug_traceback_of_a_failed_connection_does_not_show_the_password(monkeypatch): + monkeypatch.setenv("DATACONTRACT_MYSQL_PASSWORD", "s3cret-pw") + + result = subprocess.run( + [ + sys.executable, + "-m", + "datacontract.cli", + *"import mysql --source 127.0.0.1 --port 1 --database db --debug".split(), + ], + capture_output=True, + text=True, + ) + + assert "Could not connect to MySQL" in result.stderr + assert "s3cret-pw" not in result.stdout + result.stderr + + def test_import_mysql_requires_a_database(): with pytest.raises(DataContractException) as exc_info: DataContract.import_from_source("mysql", "127.0.0.1", database=None) From be8f3e793ad99ab9b7f4aabc0fa97eae00d494b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Tue, 6 Oct 2026 18:24:50 +0200 Subject: [PATCH 4/5] Keep a saved DuckDB secret named mysqldb_password from breaking the MySQL connection --- datacontract/engines/ibis/connections/duckdb_connection.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index dc788fc78..1767d5dbe 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -513,11 +513,11 @@ def _attach_mysql(con, host: str, port: int, user: str, password: str, database: if database: parts.append(f"database={database}") conn_str = " ".join(parts).replace("'", "''") - con.execute("CREATE SECRET mysqldb_password (TYPE mysql, PASSWORD ?)", [password]) + con.execute("CREATE TEMPORARY SECRET mysqldb_password (TYPE mysql, PASSWORD ?)", [password]) try: con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql, SECRET mysqldb_password)") finally: - con.execute("DROP SECRET mysqldb_password") + con.execute("DROP TEMPORARY SECRET mysqldb_password") def _sql_literal(value) -> str: From ca67b9ae7b406627fda80f4496922fa6650b92bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Tue, 6 Oct 2026 18:24:50 +0200 Subject: [PATCH 5/5] Drop the import test's traceback assertion, covered by the connect and --debug tests --- tests/test_import_mysql.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/test_import_mysql.py b/tests/test_import_mysql.py index adfe6e575..3bde4132e 100644 --- a/tests/test_import_mysql.py +++ b/tests/test_import_mysql.py @@ -2,7 +2,6 @@ import subprocess import sys -import traceback import pytest import yaml @@ -163,7 +162,6 @@ def test_a_failed_connection_does_not_show_the_password(monkeypatch): _import(port=1) assert "s3cret-pw" not in exc_info.value.reason - assert "s3cret-pw" not in "".join(traceback.format_exception(exc_info.value.original_exception)) def test_the_debug_traceback_of_a_failed_connection_does_not_show_the_password(monkeypatch):