diff --git a/CHANGELOG.md b/CHANGELOG.md index 679e3b61f..be1d75104 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ 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) +- `--debug` tracebacks no longer print local variables, which could hold credentials + ## [1.2.3] - 2026-10-05 ### Added 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/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 6f20b6aa2..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) @@ -612,12 +616,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_: diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index da8a5909c..1767d5dbe 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 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 TEMPORARY 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 165fc7e76..69cec3fca 100644 --- a/datacontract/imports/mysql_importer.py +++ b/datacontract/imports/mysql_importer.py @@ -121,16 +121,15 @@ def _attach(host: str, port: int, database: str, config: Optional[Config] = None original_exception=e, ) - 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) 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..62affa77d 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 @@ -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()) @@ -76,3 +76,14 @@ 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() + + 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 90ef8a7e8..3bde4132e 100644 --- a/tests/test_import_mysql.py +++ b/tests/test_import_mysql.py @@ -1,5 +1,8 @@ """Tests for the MySQL importer, run against a real MySQL container.""" +import subprocess +import sys + import pytest import yaml from testcontainers.mysql import MySqlContainer @@ -152,6 +155,33 @@ 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 "s3cret-pw" not in exc_info.value.reason + + +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)