Skip to content

Commit c3060fa

Browse files
dmaresmajschoedl
andauthored
duckdb Azure add Credential Chain support (#1797)
* init * Don't use the Azure credential chain for contracts posted to the API A contract posted to `datacontract api` no longer reads Azure data with the API host's own identity (managed identity, `az login`, `AZURE_*` variables). Without a complete service principal, the test now fails with an error naming the missing `DATACONTRACT_AZURE_*` variable; callers can send the service principal as `datacontract-azure-*` request headers. `datacontract test` and `datacontract import` on the command line keep using the credential chain. * Remove the unreachable DuckDB version check for the Azure credential chain * Build the Azure DuckDB secret from an options dict, like the S3 one * Log why the Azure credential chain is used With --debug, `datacontract test` and `datacontract import` on Azure now log when they fall back to the Azure credential chain, naming the DATACONTRACT_AZURE_* service principal variables that are not set (if any are set at all). * Document that Delta tables need DATACONTRACT_AZURE_CREDENTIAL_CHAIN=cli after az login * Drop a test that only re-checks reading a config option from the environment * Shorten the Azure credential chain CHANGELOG entry --------- Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent 60ce181 commit c3060fa

7 files changed

Lines changed: 110 additions & 31 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2121
- `datacontract test`: test Excel sheets whose header is not in the first row, with an `xlsxRange` custom property per schema, and fail a sheet whose header row is empty (#1717 @nicolehazel)
2222
- Error messages link to the matching docs page: the server type's reference page when `datacontract test` fails, the format's guide when `import` or `export` fails, and the installation page when an optional dependency is missing
2323
- `datacontract lint` and `datacontract test` fail on duplicate schema, property, server and role names, and on duplicate `id`s within the same array; checks are skipped with a custom `--json-schema`
24+
- `datacontract test` and `datacontract import` authenticate to Azure through the Azure credential chain (e.g. `az login`) when no service principal is configured (@dmaresma)
2425

2526
## [1.2.9] - 2026-10-30
2627

‎datacontract/config/settings.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ class Config(BaseSettings):
132132
azure_tenant_id: str | None = None
133133
azure_client_id: str | None = None
134134
azure_client_secret: SecretStr | None = None
135+
azure_credential_chain: str | None = None
135136

136137
# bigquery
137138
bigquery_account_info_json_path: str | None = None
@@ -601,6 +602,9 @@ def get_azure_client_id(self, required: bool = False) -> str | None:
601602
def get_azure_client_secret(self, required: bool = False) -> str | None:
602603
return self._str_option("azure_client_secret", required)
603604

605+
def get_azure_credential_chain(self, required: bool = False) -> str | None:
606+
return self._str_option("azure_credential_chain", required)
607+
604608
# --- bigquery ---
605609
def get_bigquery_account_info_json_path(self, required: bool = False) -> str | None:
606610
return self._str_option("bigquery_account_info_json_path", required)

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

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def get_duckdb_connection(
5656
setup_gcs_connection(con, server, config)
5757
if server.type == "azure":
5858
path = server.location
59-
setup_azure_connection(con, server, config)
59+
setup_azure_connection(con, server, config, untrusted_contract)
6060

6161
if server.format == "delta":
6262
# Updating an extension reaches the network and the extension directory,
@@ -790,37 +790,49 @@ def setup_gcs_connection(con, server: Server, config: Config):
790790
""")
791791

792792

793-
def setup_azure_connection(con, server: Server, config: Config):
794-
tenant_id = config.get_azure_tenant_id(required=True)
795-
client_id = config.get_azure_client_id(required=True)
796-
client_secret = config.get_azure_client_secret(required=True)
793+
def setup_azure_connection(con, server: Server, config: Config, untrusted_contract: bool = False):
794+
tenant_id = config.get_azure_tenant_id()
795+
client_id = config.get_azure_client_id()
796+
client_secret = config.get_azure_client_secret()
797+
use_service_principal = bool(tenant_id and client_id and client_secret)
798+
799+
if not use_service_principal and untrusted_contract:
800+
# The credential chain would read with the host's own identity from any account an untrusted contract names
801+
tenant_id = config.get_azure_tenant_id(required=True)
802+
client_id = config.get_azure_client_id(required=True)
803+
client_secret = config.get_azure_client_secret(required=True)
804+
797805
storage_account = (
798806
to_azure_storage_account(server.location) if server.type == "azure" and "://" in server.location else None
799807
)
800808

801809
_load_extension(con, "azure", "azure")
802810

803-
if storage_account is not None:
804-
con.sql(f"""
805-
CREATE SECRET azure_spn (
806-
TYPE AZURE,
807-
PROVIDER SERVICE_PRINCIPAL,
808-
TENANT_ID '{_sql_literal(tenant_id)}',
809-
CLIENT_ID '{_sql_literal(client_id)}',
810-
CLIENT_SECRET '{_sql_literal(client_secret)}',
811-
ACCOUNT_NAME '{_sql_literal(storage_account)}'
812-
);
813-
""")
811+
if use_service_principal:
812+
provider = "SERVICE_PRINCIPAL"
813+
options = {"TENANT_ID": tenant_id, "CLIENT_ID": client_id, "CLIENT_SECRET": client_secret}
814814
else:
815-
con.sql(f"""
816-
CREATE SECRET azure_spn (
817-
TYPE AZURE,
818-
PROVIDER SERVICE_PRINCIPAL,
819-
TENANT_ID '{_sql_literal(tenant_id)}',
820-
CLIENT_ID '{_sql_literal(client_id)}',
821-
CLIENT_SECRET '{_sql_literal(client_secret)}'
822-
);
823-
""")
815+
# No service principal configured: resolve credentials through the Azure credential chain
816+
# (az cli, env, managed identity, workload identity, ...).
817+
missing = [
818+
name
819+
for name, value in [
820+
("DATACONTRACT_AZURE_TENANT_ID", tenant_id),
821+
("DATACONTRACT_AZURE_CLIENT_ID", client_id),
822+
("DATACONTRACT_AZURE_CLIENT_SECRET", client_secret),
823+
]
824+
if not value
825+
]
826+
if len(missing) == 3:
827+
logger.info("Using the Azure credential chain")
828+
else:
829+
logger.info("Using the Azure credential chain: %s not set", " and ".join(missing))
830+
provider = "CREDENTIAL_CHAIN"
831+
options = {"CHAIN": config.get_azure_credential_chain()}
832+
833+
options["ACCOUNT_NAME"] = storage_account
834+
clauses = [f"PROVIDER {provider}"] + [f"{name} '{_sql_literal(v)}'" for name, v in options.items() if v]
835+
con.sql(f"CREATE OR REPLACE SECRET azure_spn (TYPE AZURE, {', '.join(clauses)});")
824836

825837

826838
def to_azure_storage_account(location: str) -> str | None:

‎docs/docs/configuration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ Every option, by its environment variable name and the matching `Config` field.
167167
| `DATACONTRACT_AZURE_TENANT_ID` | `azure_tenant_id` | string | |
168168
| `DATACONTRACT_AZURE_CLIENT_ID` | `azure_client_id` | string | |
169169
| `DATACONTRACT_AZURE_CLIENT_SECRET` | `azure_client_secret` | string (secret) | |
170+
| `DATACONTRACT_AZURE_CREDENTIAL_CHAIN` | `azure_credential_chain` | string | |
170171

171172
### BigQuery
172173

‎docs/docs/reference/azure.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,19 @@ servers:
2121
2222
## Authentication
2323
24-
Authentication uses an Azure Service Principal (App Registration) with a secret:
24+
Two authentication methods are supported by the DuckDB engine (`datacontract test` on Azure files):
25+
26+
1. **Service Principal (App Registration) with a secret.** Used when all three of `DATACONTRACT_AZURE_TENANT_ID`, `DATACONTRACT_AZURE_CLIENT_ID` and `DATACONTRACT_AZURE_CLIENT_SECRET` are set.
27+
2. **Azure credential chain.** Used as soon as the service principal variables are not all set: Azure CLI (`az login`), environment, managed identity, workload identity, and so on. It uses the `CREDENTIAL_CHAIN` provider of the DuckDB `azure` extension. Contracts posted to `datacontract api` never use the chain, so the API server's own identity is not lent to its callers; send the service principal as `datacontract-azure-*` request headers instead.
2528

2629
| Variable | Example | Description |
2730
|---|---|---|
28-
| `DATACONTRACT_AZURE_TENANT_ID` | `79f5b80f-...` | The Azure Tenant ID |
29-
| `DATACONTRACT_AZURE_CLIENT_ID` | `3cf7ce49-...` | The Application/Client ID of the app registration |
30-
| `DATACONTRACT_AZURE_CLIENT_SECRET` | `yZK8Q~GWO1M...` | The client secret value |
31+
| `DATACONTRACT_AZURE_TENANT_ID` | `79f5b80f-...` | The Azure Tenant ID (service principal) |
32+
| `DATACONTRACT_AZURE_CLIENT_ID` | `3cf7ce49-...` | The Application/Client ID of the app registration (service principal) |
33+
| `DATACONTRACT_AZURE_CLIENT_SECRET` | `yZK8Q~GWO1M...` | The client secret value (service principal) |
34+
| `DATACONTRACT_AZURE_CREDENTIAL_CHAIN` | `cli;env;managed_identity` | Optional, credential chain only. `;`-separated providers, tried in order. Default: the DuckDB `azure` extension default chain. Delta tables need `cli` to use `az login` |
3135

32-
The service principal needs the **Storage Blob Data Reader** role. The [metadata-check path](../testing/azure.md#metadata-checks) alternatively accepts `DATACONTRACT_AZURE_CONNECTION_STRING` or `DATACONTRACT_AZURE_STORAGE_ACCOUNT_KEY`.
36+
The storage account is derived from the `location` of the server. The identity (service principal or the one found by the credential chain) needs the **Storage Blob Data Reader** role. The [metadata-check path](../testing/azure.md#metadata-checks) alternatively accepts `DATACONTRACT_AZURE_CONNECTION_STRING` or `DATACONTRACT_AZURE_STORAGE_ACCOUNT_KEY`.
3337

3438
Supported `location` URL formats (in the `servers` block):
3539

‎docs/docs/testing/azure.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ DATACONTRACT_AZURE_CLIENT_ID=3cf7ce49-e2e9-4cbc-a922-4328d4a58622
2727
DATACONTRACT_AZURE_CLIENT_SECRET=yZK8Q~GWO1MMXXXXXXXXXXXXX
2828
```
2929

30+
Without these three variables, the Azure credential chain is used instead (for example after `az login`, or with a managed identity). Set `DATACONTRACT_AZURE_CREDENTIAL_CHAIN` (e.g. `cli;env;managed_identity`) to choose the providers. Delta tables don't pick up `az login` from the default chain; set `DATACONTRACT_AZURE_CREDENTIAL_CHAIN=cli` for them.
31+
3032
## 3. Create a contract from your files
3133

3234
Import the schema straight from the container. This also generates a ready-to-test `servers` block:
@@ -80,7 +82,7 @@ Run `datacontract test datacontract.yaml` again: every violation is listed as an
8082

8183
## Reference
8284

83-
All authentication options (service principal, connection string, account key), supported location URL formats, and the data type handling per file format: **[Azure Reference](../reference/azure.md)**.
85+
All authentication options (service principal, credential chain, connection string, account key), supported location URL formats, and the data type handling per file format: **[Azure Reference](../reference/azure.md)**.
8486

8587
## Troubleshooting
8688

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from unittest.mock import MagicMock
2+
3+
import pytest
4+
from open_data_contract_standard.model import Server
5+
6+
from datacontract.config import Config
7+
from datacontract.engines.ibis.connections import duckdb_connection as dc
8+
from datacontract.model.exceptions import DataContractException
9+
10+
LOCATION = "azure://container@myaccount.blob.core.windows.net/path/*.parquet"
11+
SPN = {"azure_tenant_id": "tenant", "azure_client_id": "client", "azure_client_secret": "secret"}
12+
13+
14+
@pytest.fixture(autouse=True)
15+
def _clean_env(monkeypatch):
16+
for name in ["TENANT_ID", "CLIENT_ID", "CLIENT_SECRET", "CREDENTIAL_CHAIN"]:
17+
monkeypatch.delenv(f"DATACONTRACT_AZURE_{name}", raising=False)
18+
monkeypatch.setattr(dc, "_load_extension", lambda *a, **k: None)
19+
20+
21+
def _run(monkeypatch, untrusted_contract=False, **options):
22+
con = MagicMock()
23+
dc.setup_azure_connection(con, Server(type="azure", location=LOCATION), Config(**options), untrusted_contract)
24+
return con.sql.call_args[0][0]
25+
26+
27+
def test_service_principal_when_all_options_set(monkeypatch):
28+
sql = _run(monkeypatch, **SPN)
29+
assert "PROVIDER SERVICE_PRINCIPAL" in sql
30+
assert "ACCOUNT_NAME 'myaccount'" in sql
31+
32+
33+
def test_credential_chain_when_spn_missing(monkeypatch):
34+
sql = _run(monkeypatch)
35+
assert "PROVIDER CREDENTIAL_CHAIN" in sql
36+
assert "CHAIN '" not in sql
37+
assert "ACCOUNT_NAME 'myaccount'" in sql
38+
39+
40+
def test_credential_chain_when_spn_partially_set(monkeypatch):
41+
assert "PROVIDER CREDENTIAL_CHAIN" in _run(monkeypatch, azure_tenant_id="tenant")
42+
43+
44+
def test_credential_chain_custom_chain(monkeypatch):
45+
assert "CHAIN 'cli;env'" in _run(monkeypatch, azure_credential_chain="cli;env")
46+
47+
48+
def test_credential_chain_is_escaped(monkeypatch):
49+
sql = _run(monkeypatch, azure_credential_chain="cli'); DROP")
50+
assert "CHAIN 'cli''); DROP'" in sql
51+
52+
53+
def test_untrusted_contract_requires_spn_options(monkeypatch):
54+
with pytest.raises(DataContractException):
55+
_run(monkeypatch, untrusted_contract=True)

0 commit comments

Comments
 (0)