Skip to content

Commit 337c9b2

Browse files
authored
Redact secrets in the MySQL connection string of error messages (#1708)
* Redact secrets in the MySQL connection string of error messages * Pass the MySQL password in a DuckDB secret, keeping it out of every connection error * Hide local variables in --debug tracebacks, which could hold credentials * Keep a saved DuckDB secret named mysqldb_password from breaking the MySQL connection * Drop the import test's traceback assertion, covered by the connect and --debug tests
1 parent 8e1ee96 commit 337c9b2

7 files changed

Lines changed: 72 additions & 13 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Added
1111
- `datacontract test`: check that foreign keys declared under `relationships` have no values missing from the referenced schema (#1691)
1212

13+
### Fixed
14+
- Redact secrets in the MySQL connection string of error messages (#1706)
15+
- `--debug` tracebacks no longer print local variables, which could hold credentials
16+
1317
## [1.2.3] - 2026-10-05
1418

1519
### Added

‎datacontract/cli.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ def parse_args(self, ctx: Context, args):
130130
cls=OrderedCommandsWithMigrationHints,
131131
no_args_is_help=True,
132132
add_completion=False,
133+
# the locals of a --debug traceback can hold credentials
134+
pretty_exceptions_show_locals=False,
133135
help="CLI to manage data contracts. Documentation: https://docs.datacontract.com",
134136
epilog="Read the full documentation at https://docs.datacontract.com",
135137
)

‎datacontract/engines/ibis/connections/connect.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -601,7 +601,11 @@ def _connect_mysql_via_duckdb(
601601
"""
602602
import duckdb
603603

604-
from datacontract.engines.ibis.connections.duckdb_connection import _load_extension, restrict_to_paths
604+
from datacontract.engines.ibis.connections.duckdb_connection import (
605+
_attach_mysql,
606+
_load_extension,
607+
restrict_to_paths,
608+
)
605609

606610
user = config.get_mysql_username(required=True)
607611
password = config.get_mysql_password(required=True)
@@ -612,12 +616,8 @@ def _connect_mysql_via_duckdb(
612616
con = duckdb.connect()
613617
_load_extension(con, "mysql", "mysql")
614618

615-
parts = [f"host={host}", f"port={port}", f"user={user}", f"password={password}"]
616-
if database:
617-
parts.append(f"database={database}")
618-
conn_str = " ".join(parts).replace("'", "''")
619619
run.log_info(f"Attaching MySQL {host}:{port} via the duckdb mysql extension")
620-
con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql)")
620+
_attach_mysql(con, host, port, user, password, database)
621621

622622
if data_contract.schema_:
623623
for schema_obj in data_contract.schema_:

‎datacontract/engines/ibis/connections/duckdb_connection.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,19 @@ def _load_extension(con, name: str, extra: str) -> None:
507507
) from e
508508

509509

510+
def _attach_mysql(con, host: str, port: int, user: str, password: str, database: str | None) -> None:
511+
"""ATTACH MySQL as ``mysqldb``; the password goes in a secret, as DuckDB echoes the ATTACH string in its errors."""
512+
parts = [f"host={host}", f"port={port}", f"user={user}"]
513+
if database:
514+
parts.append(f"database={database}")
515+
conn_str = " ".join(parts).replace("'", "''")
516+
con.execute("CREATE TEMPORARY SECRET mysqldb_password (TYPE mysql, PASSWORD ?)", [password])
517+
try:
518+
con.execute(f"ATTACH '{conn_str}' AS mysqldb (TYPE mysql, SECRET mysqldb_password)")
519+
finally:
520+
con.execute("DROP TEMPORARY SECRET mysqldb_password")
521+
522+
510523
def _sql_literal(value) -> str:
511524
"""Escape a value for a single-quoted duckdb string literal.
512525

‎datacontract/imports/mysql_importer.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,16 +121,15 @@ def _attach(host: str, port: int, database: str, config: Optional[Config] = None
121121
original_exception=e,
122122
)
123123

124-
from datacontract.engines.ibis.connections.duckdb_connection import _load_extension
124+
from datacontract.engines.ibis.connections.duckdb_connection import _attach_mysql, _load_extension
125125

126126
user = config.get_mysql_username(required=True)
127127
password = config.get_mysql_password(required=True)
128128

129129
con = duckdb.connect()
130130
_load_extension(con, "mysql", "mysql")
131-
connection_string = _escape(f"host={host} port={port} user={user} password={password} database={database}")
132131
try:
133-
con.execute(f"ATTACH '{connection_string}' AS mysqldb (TYPE mysql)")
132+
_attach_mysql(con, host, port, user, password, database)
134133
except Exception as e:
135134
con.close()
136135
raise DataContractException(

‎tests/test_connect_mysql.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"""Unit tests for how connect_ibis attaches MySQL through DuckDB.
22
3-
These do not hit MySQL: ``duckdb.connect``, the extension loader, and the ibis
4-
wrapper are patched, and we only assert the ATTACH connection string built for
5-
a given set of env vars.
3+
These do not hit MySQL: most patch ``duckdb.connect`` and assert the ATTACH
4+
connection string; the failed-attach test points the real extension at a closed port.
65
"""
76

87
import os
8+
import traceback
99

1010
import duckdb
1111
import ibis
@@ -32,7 +32,7 @@ def captured_statements(monkeypatch):
3232
statements = []
3333

3434
class FakeConnection:
35-
def execute(self, sql):
35+
def execute(self, sql, parameters=None):
3636
statements.append(sql)
3737

3838
monkeypatch.setattr(duckdb, "connect", lambda: FakeConnection())
@@ -76,3 +76,14 @@ def test_env_variables_override_the_contract_server_details(env, captured_statem
7676
assert "host=env-host" in attach
7777
assert "port=3308" in attach
7878
assert "database=env_db" in attach
79+
80+
81+
def test_a_failed_attach_does_not_show_the_password(env):
82+
env.setenv("DATACONTRACT_MYSQL_PASSWORD", "s3cret-pw")
83+
env.setenv("DATACONTRACT_MYSQL_HOST", "127.0.0.1")
84+
env.setenv("DATACONTRACT_MYSQL_PORT", "1")
85+
86+
with pytest.raises(duckdb.Error) as exc_info:
87+
_connect()
88+
89+
assert "s3cret-pw" not in "".join(traceback.format_exception(exc_info.value))

‎tests/test_import_mysql.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""Tests for the MySQL importer, run against a real MySQL container."""
22

3+
import subprocess
4+
import sys
5+
36
import pytest
47
import yaml
58
from testcontainers.mysql import MySqlContainer
@@ -152,6 +155,33 @@ def test_import_mysql_fails_on_an_unknown_table():
152155
assert "No tables found" in exc_info.value.reason
153156

154157

158+
def test_a_failed_connection_does_not_show_the_password(monkeypatch):
159+
monkeypatch.setenv("DATACONTRACT_MYSQL_PASSWORD", "s3cret-pw")
160+
161+
with pytest.raises(DataContractException) as exc_info:
162+
_import(port=1)
163+
164+
assert "s3cret-pw" not in exc_info.value.reason
165+
166+
167+
def test_the_debug_traceback_of_a_failed_connection_does_not_show_the_password(monkeypatch):
168+
monkeypatch.setenv("DATACONTRACT_MYSQL_PASSWORD", "s3cret-pw")
169+
170+
result = subprocess.run(
171+
[
172+
sys.executable,
173+
"-m",
174+
"datacontract.cli",
175+
*"import mysql --source 127.0.0.1 --port 1 --database db --debug".split(),
176+
],
177+
capture_output=True,
178+
text=True,
179+
)
180+
181+
assert "Could not connect to MySQL" in result.stderr
182+
assert "s3cret-pw" not in result.stdout + result.stderr
183+
184+
155185
def test_import_mysql_requires_a_database():
156186
with pytest.raises(DataContractException) as exc_info:
157187
DataContract.import_from_source("mysql", "127.0.0.1", database=None)

0 commit comments

Comments
 (0)