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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- `datacontract test` and `datacontract import sqlserver` sign in to SQL Server with an Entra ID access token read from a file (`DATACONTRACT_SQLSERVER_AUTHENTICATION=token`, `DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH`) (#1830 @SreeramaYeshwanthGowd)

### Fixed
- `datacontract test` checks the constraints and quality rules of nested properties (struct fields and array items) on Dremio servers
- `datacontract test` finds tables in Postgres schemas with upper case letters, such as `"Reporting"`
Expand Down
5 changes: 3 additions & 2 deletions datacontract/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,7 @@ class UnprocessableEntityResponse(BaseModel):
"DATACONTRACT_SNOWFLAKE_PRIVATE_KEY_PATH",
"DATACONTRACT_SNOWFLAKE_TOKEN_FILE_PATH",
"DATACONTRACT_SNOWFLAKE_WORKLOAD_IDENTITY_PROVIDER",
"DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH",
"DATACONTRACT_BIGQUERY_ACCOUNT_INFO_JSON_PATH",
"DATACONTRACT_DATABRICKS_PROFILE",
"DATACONTRACT_ORACLE_CLIENT_DIR",
Expand Down Expand Up @@ -531,8 +532,8 @@ def _parse_filters_query(filters: str | None) -> dict[str, str] | None:
"hive": ("host", "hive_host", ("hive_password",)),
"dremio": ("host", "dremio_host", ("dremio_password", "dremio_token")),
"redshift": ("host", "redshift_host", ("redshift_password",)),
"sqlserver": ("host", "sqlserver_host", ("sqlserver_password",)),
"mssql": ("host", "sqlserver_host", ("sqlserver_password",)),
"sqlserver": ("host", "sqlserver_host", ("sqlserver_password", "sqlserver_token_file_path")),
"mssql": ("host", "sqlserver_host", ("sqlserver_password", "sqlserver_token_file_path")),
"snowflake": (
"account",
"snowflake_account",
Expand Down
4 changes: 4 additions & 0 deletions datacontract/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ class Config(BaseSettings):
sqlserver_password: SecretStr | None = None
sqlserver_client_id: str | None = None
sqlserver_client_secret: SecretStr | None = None
sqlserver_token_file_path: str | None = None
sqlserver_driver: str | None = None
sqlserver_encrypted_connection: bool | None = None
sqlserver_trust_server_certificate: bool | None = None
Expand Down Expand Up @@ -1072,6 +1073,9 @@ def get_sqlserver_client_id(self, required: bool = False) -> str | None:
def get_sqlserver_client_secret(self, required: bool = False) -> str | None:
return self._str_option("sqlserver_client_secret", required)

def get_sqlserver_token_file_path(self, required: bool = False) -> str | None:
return self._str_option("sqlserver_token_file_path", required)

def get_sqlserver_driver(self, required: bool = False) -> str | None:
return self._str_option("sqlserver_driver", required)

Expand Down
29 changes: 25 additions & 4 deletions datacontract/engines/ibis/connections/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,12 +723,13 @@ def _sqlserver_connection_kwargs(server: Server, config: Config) -> dict:
- ``ActiveDirectoryServicePrincipal`` — Entra ID with ``CLIENT_ID`` / ``CLIENT_SECRET``
- ``ActiveDirectoryInteractive`` — Entra ID browser login (``USERNAME`` as a hint), Windows only
- ``cli`` — reuse an ``az login`` session (token passed as a pre-connect attribute)
- ``token`` — an Entra ID access token read from ``TOKEN_FILE_PATH`` (passed like ``cli``)

The legacy ``DATACONTRACT_SQLSERVER_TRUSTED_CONNECTION=true`` is equivalent to
``windows``, and applies only when ``DATACONTRACT_SQLSERVER_AUTHENTICATION`` is
unset — an explicitly chosen mode always wins. Extra keys (``Authentication``,
``Trusted_Connection``, ``Encrypt``, ``TrustServerCertificate``) become
connection-string attributes, so they use the ODBC spellings. ``cli`` sets
connection-string attributes, so they use the ODBC spellings. ``cli`` and ``token`` set
``attrs_before``, a pre-connect attribute rather than a connection-string keyword.
"""
driver = _get_custom_property(server, "driver") or config.get_sqlserver_driver()
Expand Down Expand Up @@ -773,7 +774,24 @@ def _sqlserver_connection_kwargs(server: Server, config: Config) -> dict:
elif authentication == "cli":
# The ODBC driver has no Azure-CLI mode: pass an `az login` token as a
# pre-connect attribute (must not be combined with UID/PWD/Trusted_Connection).
kwargs["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: _azure_cli_access_token()}
kwargs["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: _sqlserver_access_token(_azure_cli_access_token())}
elif authentication == "token":
# Read on every connection, so a token the caller rotates in the file keeps working.
token_file_path = config.get_sqlserver_token_file_path(required=True)
try:
with open(token_file_path) as f:
token = f.read().strip()
problem = None if token else "is empty"
except OSError as e:
problem = f"could not be read: {e.strerror}"
if problem:
raise DataContractException(
type="sqlserver-connection",
name="invalid_token_file",
reason=f"DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH points to {token_file_path}, which {problem}",
engine="datacontract-cli",
)
kwargs["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: _sqlserver_access_token(token)}
elif authentication == "activedirectoryserviceprincipal":
kwargs["Authentication"] = "ActiveDirectoryServicePrincipal"
kwargs["user"] = config.get_sqlserver_client_id(required=True)
Expand Down Expand Up @@ -806,7 +824,7 @@ def _sqlserver_connection_kwargs(server: Server, config: Config) -> dict:
return kwargs


def _azure_cli_access_token() -> bytes:
def _azure_cli_access_token() -> str:
try:
from azure.core.exceptions import ClientAuthenticationError
from azure.identity import AzureCliCredential
Expand All @@ -819,7 +837,7 @@ def _azure_cli_access_token() -> bytes:
original_exception=exc,
)
try:
token = AzureCliCredential().get_token("https://database.windows.net/.default").token
return AzureCliCredential().get_token("https://database.windows.net/.default").token
except ClientAuthenticationError as exc:
raise DataContractException(
type="sqlserver-connection",
Expand All @@ -828,6 +846,9 @@ def _azure_cli_access_token() -> bytes:
engine="datacontract-cli",
original_exception=exc,
)


def _sqlserver_access_token(token: str) -> bytes:
# The driver expects UTF-16LE bytes prefixed with their 4-byte little-endian length.
raw = token.encode("utf-16-le")
return struct.pack("<i", len(raw)) + raw
Expand Down
1 change: 1 addition & 0 deletions docs/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ Every option, by its environment variable name and the matching `Config` field.
| `DATACONTRACT_SQLSERVER_PASSWORD` | `sqlserver_password` | string (secret) | |
| `DATACONTRACT_SQLSERVER_CLIENT_ID` | `sqlserver_client_id` | string | |
| `DATACONTRACT_SQLSERVER_CLIENT_SECRET` | `sqlserver_client_secret` | string (secret) | |
| `DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH` | `sqlserver_token_file_path` | string | |
| `DATACONTRACT_SQLSERVER_DRIVER` | `sqlserver_driver` | string | |
| `DATACONTRACT_SQLSERVER_ENCRYPTED_CONNECTION` | `sqlserver_encrypted_connection` | boolean | |
| `DATACONTRACT_SQLSERVER_TRUST_SERVER_CERTIFICATE` | `sqlserver_trust_server_certificate` | boolean | |
Expand Down
5 changes: 3 additions & 2 deletions docs/docs/reference/sqlserver.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,17 @@ servers:

| Variable | Example | Description |
|---|---|---|
| `DATACONTRACT_SQLSERVER_AUTHENTICATION` | `sql` | `sql` (default), `cli` (uses `az login`), `windows`, `ActiveDirectoryPassword`, `ActiveDirectoryServicePrincipal`, `ActiveDirectoryInteractive` (Windows only) |
| `DATACONTRACT_SQLSERVER_AUTHENTICATION` | `sql` | `sql` (default), `cli` (uses `az login`), `token` (reads an access token from a file), `windows`, `ActiveDirectoryPassword`, `ActiveDirectoryServicePrincipal`, `ActiveDirectoryInteractive` (Windows only) |
| `DATACONTRACT_SQLSERVER_USERNAME` | `root` | Username (for `sql`, `ActiveDirectoryPassword`, `ActiveDirectoryInteractive`) |
| `DATACONTRACT_SQLSERVER_PASSWORD` | `toor` | Password (for `sql` and `ActiveDirectoryPassword`) |
| `DATACONTRACT_SQLSERVER_CLIENT_ID` | `a3cf5d29-...` | Client ID (for `ActiveDirectoryServicePrincipal`) |
| `DATACONTRACT_SQLSERVER_CLIENT_SECRET` | `kX9~Qr2Lm...` | Client secret (for `ActiveDirectoryServicePrincipal`) |
| `DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH` | `/var/run/secrets/tokens/sqlserver-token` | File holding an Entra ID access token for `https://database.windows.net/` (for `token`) |
| `DATACONTRACT_SQLSERVER_TRUST_SERVER_CERTIFICATE` | `True` | Trust self-signed certificate |
| `DATACONTRACT_SQLSERVER_ENCRYPTED_CONNECTION` | `True` | Use SSL |
| `DATACONTRACT_SQLSERVER_DRIVER` | `ODBC Driver 18 for SQL Server` | ODBC driver name |

The `cli` mode reuses an `az login` session: the CLI fetches an Entra ID access token and hands it to the ODBC driver, so it works on macOS and Linux too; it needs the `azure` extra (`datacontract-cli[sqlserver,azure]`). `ActiveDirectoryInteractive` is only offered by the Microsoft ODBC driver on Windows. `host`, `port`, `database`, `schema`, and `driver` come from the contract's `servers` block; `host`, `port`, and `database` can be overridden with `DATACONTRACT_SQLSERVER_HOST`, `DATACONTRACT_SQLSERVER_PORT`, and `DATACONTRACT_SQLSERVER_DATABASE`.
The `cli` mode reuses an `az login` session: the CLI fetches an Entra ID access token and hands it to the ODBC driver, so it works on macOS and Linux too; it needs the `azure` extra (`datacontract-cli[sqlserver,azure]`). The `token` mode hands over an access token you already hold, for example one a credential service writes: the file is read again on every connection, so a rotated token keeps working. `ActiveDirectoryInteractive` is only offered by the Microsoft ODBC driver on Windows. `host`, `port`, `database`, `schema`, and `driver` come from the contract's `servers` block; `host`, `port`, and `database` can be overridden with `DATACONTRACT_SQLSERVER_HOST`, `DATACONTRACT_SQLSERVER_PORT`, and `DATACONTRACT_SQLSERVER_DATABASE`.

### Deprecated variables

Expand Down
12 changes: 12 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,7 @@ def test_unknown_config_header_is_rejected():
"datacontract-duckdb-database",
"datacontract-snowflake-token-file-path",
"datacontract-snowflake-workload-identity-provider",
"datacontract-sqlserver-token-file-path",
],
)
def test_server_only_header_is_rejected(header):
Expand Down Expand Up @@ -907,6 +908,17 @@ def test_guard_blocks_env_trino_secrets(monkeypatch, secret):
assert secret in exc.value.detail


def test_guard_blocks_env_sqlserver_token_file_without_pinned_host(monkeypatch):
monkeypatch.setenv("DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH", "/var/run/secrets/tokens/sqlserver-token")
monkeypatch.delenv("DATACONTRACT_SQLSERVER_HOST", raising=False)

with pytest.raises(HTTPException) as exc:
_reject_environment_credentials_to_untrusted_host(
_POSTGRES_CONTRACT.replace("type: postgres", "type: sqlserver"), "production", None
)
assert "DATACONTRACT_SQLSERVER_HOST" in exc.value.detail


def test_test_endpoint_blocks_credential_exfiltration(monkeypatch):
"""End to end through the API: POST a contract naming the host while the
server holds a postgres password -> 422, no connection attempted."""
Expand Down
38 changes: 38 additions & 0 deletions tests/test_connect_sqlserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def _sqlserver_connection_kwargs(server):
"DATACONTRACT_SQLSERVER_PASSWORD",
"DATACONTRACT_SQLSERVER_CLIENT_ID",
"DATACONTRACT_SQLSERVER_CLIENT_SECRET",
"DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH",
"DATACONTRACT_SQLSERVER_TRUST_SERVER_CERTIFICATE",
"DATACONTRACT_SQLSERVER_ENCRYPTED_CONNECTION",
"DATACONTRACT_SQLSERVER_DRIVER",
Expand Down Expand Up @@ -210,6 +211,43 @@ def test_cli_auth_passes_az_login_token_as_pre_connect_attribute(env, monkeypatc
assert "Trusted_Connection" not in kwargs


def test_token_auth_passes_the_token_file_as_pre_connect_attribute(env, tmp_path):
token_file = tmp_path / "sqlserver-token"
token_file.write_text("tok\n")
env.setenv("DATACONTRACT_SQLSERVER_AUTHENTICATION", "token")
env.setenv("DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH", str(token_file))

kwargs = _sqlserver_connection_kwargs(_server())

# same packing as cli, without the trailing newline; no Authentication keyword or credentials
assert kwargs["attrs_before"] == {1256: b"\x06\x00\x00\x00t\x00o\x00k\x00"}
assert "Authentication" not in kwargs
assert kwargs["user"] is None
assert kwargs["password"] is None
assert "Trusted_Connection" not in kwargs


def test_token_auth_rereads_the_token_file_on_each_connection(env, tmp_path):
token_file = tmp_path / "sqlserver-token"
env.setenv("DATACONTRACT_SQLSERVER_AUTHENTICATION", "token")
env.setenv("DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH", str(token_file))

token_file.write_text("old")
first = _sqlserver_connection_kwargs(_server())
token_file.write_text("new")
second = _sqlserver_connection_kwargs(_server())

assert first["attrs_before"][1256].endswith("old".encode("utf-16-le"))
assert second["attrs_before"][1256].endswith("new".encode("utf-16-le"))


def test_token_auth_requires_token_file_path(env):
env.setenv("DATACONTRACT_SQLSERVER_AUTHENTICATION", "token")
with pytest.raises(DataContractException) as exc:
_sqlserver_connection_kwargs(_server())
assert "DATACONTRACT_SQLSERVER_TOKEN_FILE_PATH" in exc.value.reason


def test_ssl_options(env):
env.setenv("DATACONTRACT_SQLSERVER_USERNAME", "sa")
env.setenv("DATACONTRACT_SQLSERVER_PASSWORD", "secret")
Expand Down
Loading