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
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Workflows run with a read-only token.** `ci.yml` and `release.yml` now set
`permissions: contents: read`; the publish and release jobs keep their own
narrower grants.
- **MySQL connections over TLS verify the server's certificate.** Whenever TLS
was on, which is always for IBM Cloud Databases hosts, certificate and host
name checks were turned off. Anyone between the toolkit and the server could
then present any certificate and read the MySQL credentials. TLS now always
checks that the certificate chains to a trusted CA and names the host, and
`sslMode=REQUIRED` and `VERIFY_CA` are treated as `VERIFY_IDENTITY`. For a
private CA, add `ssl_ca=/path/to/ca.pem` to the connection string. The
`sslMode` parameter was also dropped before it was read, so a
`sslMode=VERIFY_IDENTITY` string for any other host connected without TLS.
It now turns TLS on. Unknown `ssl*` options are refused rather than ignored,
and the two Beaver curation scripts, which had their own copies of the old
code, now share the library's.
- **TLS can no longer be stripped from a MySQL connection.** aiomysql and
PyMySQL treat TLS as a preference: when the server's handshake does not offer
it, they log in unencrypted. Anyone who could rewrite that handshake could
strip the offer and collect the login. With TLS on, the library and the schema
extractor now refuse to log in to a server that does not offer TLS.
- **`RemoteDatabaseConnector` verifies the API's certificate.** It sent
`SQL_API_KEY` as a bearer token with `verify=False`, so anyone between the
toolkit and the API could present any certificate and read the key. For a
private CA, set `REQUESTS_CA_BUNDLE`.
- **Connection strings are logged without their password.** MySQL execution
logged its connection string at DEBUG level. That is the toolkit's default
level, so every MySQL run printed the database password to the console and,
in a source checkout, to `data/results/bak/log.txt`. The new helper
`redact_url_password` now shows it as `***`. The Beaver curation runner gets
the same fix, and the BIRD Postgres schema converter no longer logs its
connection string at all. That converter also used to fail both with and
without `--pg_conn_str`, because an `else` was indented under the wrong `if`.

### Fixed

Expand Down
25 changes: 25 additions & 0 deletions docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,31 @@ Execution uses SQLAlchemy's asyncio engine, so a connection string must name an
in the string is translated where the toolkit can do so unambiguously, but
naming the async driver is clearer.

### MySQL over TLS

TLS is on when the connection string asks for it, with `sslMode=REQUIRED`,
`VERIFY_CA` or `VERIFY_IDENTITY`, with `ssl=true`, or by naming a CA or a client
certificate. It is always on for IBM Cloud Databases hosts. Whenever TLS is on,
the server's certificate must chain to a trusted CA and name the host in the
URL. `REQUIRED` and `VERIFY_CA` are treated as `VERIFY_IDENTITY`, and there is
no option to skip the check. If a private CA signs the server's certificate (IBM
Cloud Databases includes its CA with the service credentials), give that CA's
path with `ssl_ca`:

```bash
MYSQL_CONNECTION_STRING="mysql://user:password@host:port/db?sslMode=VERIFY_IDENTITY&ssl_ca=/path/to/ca.pem"
```

Connect by the host name the certificate names, not by its IP address. With TLS
on, a server that does not offer TLS is refused before the login is sent, rather
than reached unencrypted. `ssl_capath` names a folder of CAs instead of a single
file, and `ssl_cert` (with `ssl_key` if the key is a separate file) adds a
client certificate. `sslMode=DISABLED` or `ssl=false` turns TLS off.

`RemoteDatabaseConnector` sends `SQL_API_KEY` to its HTTP API as a bearer token
and always verifies the API's certificate. For a private CA, point
`REQUESTS_CA_BUNDLE` at that CA's certificate.

SQLite benchmarks read a local folder instead, given by `db_engine.db_folder`.

## Dashboard
Expand Down
4 changes: 3 additions & 1 deletion env.example
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ RITS_API_KEY=your_rits_api_key_here
# PostgreSQL (for PostgreSQL-based benchmarks)
POSTGRES_CONNECTION_STRING=postgresql://user:password@host:port/database

# MySQL (for benchmarks like beaver)
# MySQL (for benchmarks like beaver). For TLS add ?sslMode=VERIFY_IDENTITY, and
# &ssl_ca=/path/to/ca.pem if a private CA signs the server's certificate. The
# certificate is always verified; see docs/guide/configuration.md.
MYSQL_CONNECTION_STRING=mysql://user:password@host:port/database

# DB2 (for DB2-based benchmarks)
Expand Down
82 changes: 15 additions & 67 deletions scripts/curation/beaver_sql_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@
import importlib
import json
import logging
import re
import ssl
from pathlib import Path
from urllib.parse import urlparse, urlunparse

import pandas as pd
from sqlglot import exp, parse_one
from tqdm.asyncio import tqdm as tqdm_asyncio

from text2sql_eval_toolkit.execution.execution_tools import (
normalize_mysql_connection_string,
redact_url_password,
)

_sqlalchemy_mod = None
_aiomysql_mod = None

Expand Down Expand Up @@ -55,63 +57,6 @@ def _require_mysql_deps():
) from e


def normalize_mysql_connection_string(
connection_string: str, db_id: str = None
) -> tuple[str, dict]:
"""
Normalize MySQL connection string and return connect_args.
Based on your working normalize_connection_string function.
"""
connect_args = {}

# Handle mysql:// with SSL parameters like your example
if connection_string.startswith("mysql://"):
# For async, we'll try aiomysql first, then fall back to asyncio-mysql
# But follow your SSL handling pattern
connection_string = connection_string.replace(
"mysql://", "mysql+aiomysql://", 1
)

# Parse the URL to modify the database part only if db_id is provided
if db_id:
parsed = urlparse(connection_string)
# Replace the database part (path) with the db_id
# Remove leading slash and any existing database name
new_path = f"/{db_id}"
# Rebuild the URL with the new database name
connection_string = urlunparse(
(
parsed.scheme,
parsed.netloc,
new_path,
parsed.params,
parsed.query,
parsed.fragment,
)
)

# Handle SSL mode parameter conversion - remove problematic SSL params
if "sslMode=" in connection_string:
# Remove the sslMode parameter entirely and let driver handle SSL automatically
connection_string = re.sub(r"[&?]sslMode=[^&]*", "", connection_string)

# Determine if this is an IBM Cloud or other SSL-required connection
ssl_required = any(
domain in connection_string
for domain in ["databases.appdomain.cloud", "ssl=true", "sslMode="]
)

if ssl_required:
# For aiomysql, let's try a simpler SSL approach
# Just enable SSL without complex verification for IBM Cloud
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
connect_args = {"ssl": ssl_context}

return connection_string, connect_args


def quote_mysql_identifiers(sql: str) -> str:
"""
Quote MySQL identifiers using backticks instead of double quotes.
Expand Down Expand Up @@ -170,13 +115,13 @@ async def run_sql_and_get_dataframe_mysql_async(
"""Execute SQL query on MySQL using SQLAlchemy async engine."""
sqlalchemy_async, text = _require_mysql_deps()

# If db_id is provided, create a new connection string for that specific database
# Only the database changes per record: the TLS context is already in
# connect_args, and the URL no longer carries the options it came from.
final_conn_str = normalized_conn_str
if db_id:
final_conn_str, final_connect_args = normalize_mysql_connection_string(
normalized_conn_str.replace("mysql+aiomysql://", "mysql://"), db_id
final_conn_str, _ = normalize_mysql_connection_string(
normalized_conn_str, db_id
)
else:
final_conn_str, final_connect_args = normalized_conn_str, connect_args

engine = sqlalchemy_async.create_async_engine(
final_conn_str,
Expand All @@ -185,7 +130,7 @@ async def run_sql_and_get_dataframe_mysql_async(
pool_pre_ping=True,
pool_recycle=3600,
echo=False,
connect_args=final_connect_args,
connect_args=connect_args,
)

try:
Expand Down Expand Up @@ -234,7 +179,10 @@ async def run_sql_queries(
normalized_conn_str, connect_args = normalize_mysql_connection_string(
connection_string
)
logger.debug(f"Normalized MySQL connection string: {normalized_conn_str}")
logger.debug(
"Normalized MySQL connection string: "
f"{redact_url_password(normalized_conn_str)}"
)

# Create a test engine to verify base connection
sqlalchemy_async, text = _require_mysql_deps()
Expand Down
11 changes: 6 additions & 5 deletions scripts/curation/bird_schema_converter_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,16 +231,17 @@ def get_bird_pg_schema_dict(dev_tables_json, pg_conn_str=None):
with open(args.dev_tables_filepath, "r") as f:
dev_tables_json = json.load(f)

# The string itself is never logged: it carries the database password.
if args.pg_conn_str is None:
pg_conn_str = os.getenv("POSTGRES_CONNECTION_STRING")
if not pg_conn_str:
logger.error("POSTGRES_CONNECTION_STRING is not set")
raise RuntimeError("Missing POSTGRES_CONNECTION_STRING")
else:
pg_conn_str = args.pg_conn_str
logger.info(
f"Using Postgres connection string from environment variable: {pg_conn_str}"
)
logger.info(
"Using the Postgres connection string in POSTGRES_CONNECTION_STRING"
)
else:
pg_conn_str = args.pg_conn_str

schema = get_bird_pg_schema_dict(dev_tables_json, pg_conn_str)

Expand Down
Loading
Loading