Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions datacontract/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)
Expand Down
12 changes: 6 additions & 6 deletions datacontract/engines/ibis/connections/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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_:
Expand Down
13 changes: 13 additions & 0 deletions datacontract/engines/ibis/connections/duckdb_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 2 additions & 3 deletions datacontract/imports/mysql_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
19 changes: 15 additions & 4 deletions tests/test_connect_mysql.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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())
Expand Down Expand Up @@ -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))
30 changes: 30 additions & 0 deletions tests/test_import_mysql.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading