From 4aec34fa4be08209183c565b30802445d8783d22 Mon Sep 17 00:00:00 2001 From: "bassem.benyahia" Date: Mon, 19 Oct 2026 12:49:12 +0100 Subject: [PATCH 1/3] Set the BigQuery query location and a Cloud KMS encryption key (#1728) Adds DATACONTRACT_BIGQUERY_LOCATION / DATACONTRACT_BIGQUERY_KMS_KEY_NAME and the server customProperties location / kmsKeyName, so datacontract test works on projects that enforce customer-managed encryption keys. --- CHANGELOG.md | 1 + datacontract/config/settings.py | 8 +++ .../engines/ibis/connections/connect.py | 16 ++++- docs/docs/configuration.md | 2 + docs/docs/reference/bigquery.md | 30 ++++++++++ tests/test_connect_bigquery.py | 58 ++++++++++++++++++- 6 files changed, 111 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f50855592..9c63e9476 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `datacontract edit --language` shows the editor in English, German, Swedish or French +- `datacontract test`: set the BigQuery query location and a Cloud KMS encryption key (CMEK) via `DATACONTRACT_BIGQUERY_LOCATION` / `DATACONTRACT_BIGQUERY_KMS_KEY_NAME` or the server `customProperties` `location` / `kmsKeyName` (#1728) ### Changed - The bundled Data Contract Editor (`datacontract edit`) is updated to 0.1.16 diff --git a/datacontract/config/settings.py b/datacontract/config/settings.py index 184a0e0bc..b05c6d48c 100644 --- a/datacontract/config/settings.py +++ b/datacontract/config/settings.py @@ -136,6 +136,8 @@ class Config(BaseSettings): bigquery_account_info_json_path: str | None = None bigquery_billing_project: str | None = None bigquery_impersonation_account: str | None = None + bigquery_location: str | None = None + bigquery_kms_key_name: str | None = None # overrides for the contract's servers block bigquery_project: str | None = None bigquery_dataset: str | None = None @@ -582,6 +584,12 @@ def get_bigquery_billing_project(self, required: bool = False) -> str | None: def get_bigquery_impersonation_account(self, required: bool = False) -> str | None: return self._str_option("bigquery_impersonation_account", required) + def get_bigquery_location(self, required: bool = False) -> str | None: + return self._str_option("bigquery_location", required) + + def get_bigquery_kms_key_name(self, required: bool = False) -> str | None: + return self._str_option("bigquery_kms_key_name", required) + def get_bigquery_project(self, required: bool = False) -> str | None: return self._str_option("bigquery_project", required) diff --git a/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 1019fd803..5f94d8eb3 100644 --- a/datacontract/engines/ibis/connections/connect.py +++ b/datacontract/engines/ibis/connections/connect.py @@ -375,7 +375,21 @@ def _connect_bigquery(ibis, server: Server, config: Config): ) if credentials: kwargs["credentials"] = credentials - return ibis.bigquery.connect(**kwargs) + location = config.get_bigquery_location() or _get_custom_property(server, "location") + if location: + kwargs["location"] = location + con = ibis.bigquery.connect(**kwargs) + + kms_key_name = config.get_bigquery_kms_key_name() or _get_custom_property(server, "kmsKeyName") + if kms_key_name: + from google.cloud import bigquery + + # Projects that enforce CMEK reject query jobs without a key. A dataset's default key does not + # cover the anonymous tables holding query results, so set it on the config every query uses. + con.client.default_query_job_config.destination_encryption_configuration = bigquery.EncryptionConfiguration( + kms_key_name=kms_key_name + ) + return con _BIGQUERY_SCOPES = ["https://www.googleapis.com/auth/bigquery"] diff --git a/docs/docs/configuration.md b/docs/docs/configuration.md index 6b15f1e3b..196140a60 100644 --- a/docs/docs/configuration.md +++ b/docs/docs/configuration.md @@ -175,6 +175,8 @@ Every option, by its environment variable name and the matching `Config` field. | `DATACONTRACT_BIGQUERY_ACCOUNT_INFO_JSON_PATH` | `bigquery_account_info_json_path` | string | | | `DATACONTRACT_BIGQUERY_BILLING_PROJECT` | `bigquery_billing_project` | string | | | `DATACONTRACT_BIGQUERY_IMPERSONATION_ACCOUNT` | `bigquery_impersonation_account` | string | | +| `DATACONTRACT_BIGQUERY_LOCATION` | `bigquery_location` | string | | +| `DATACONTRACT_BIGQUERY_KMS_KEY_NAME` | `bigquery_kms_key_name` | string | | | `DATACONTRACT_BIGQUERY_PROJECT` | `bigquery_project` | string | Overrides `project` from the contract's `servers` block | | `DATACONTRACT_BIGQUERY_DATASET` | `bigquery_dataset` | string | Overrides `dataset` from the contract's `servers` block | diff --git a/docs/docs/reference/bigquery.md b/docs/docs/reference/bigquery.md index 50ec5c1ab..c6669890a 100644 --- a/docs/docs/reference/bigquery.md +++ b/docs/docs/reference/bigquery.md @@ -29,6 +29,36 @@ Authentication uses a Service Account Key or Application Default Credentials (AD | `DATACONTRACT_BIGQUERY_BILLING_PROJECT` | `my-compute-project` | Optional. Project to bill query jobs to. Requires `bigquery.jobUser`, `bigquery.readSessionUser` on the billing project and `bigquery.dataViewer` on the data project. | | `DATACONTRACT_BIGQUERY_IMPERSONATION_ACCOUNT` | `runner@my-project.iam.gserviceaccount.com` | Optional. Service account to impersonate, using the key file above (or ADC) as the source principal. Requires `roles/iam.serviceAccountTokenCreator` on the target. | +### Query location and encryption key + +By default, query jobs run in the location BigQuery chooses (`US` when none can be inferred) and carry no encryption key. Projects that enforce the org policy `constraints/gcp.restrictNonCmekServices` reject such jobs: + +``` +Your administrator requires that you specify an encryption key for queries in project `my-project`. +``` + +Set the query location and a Cloud KMS key with these variables, or as `customProperties` on the server so each environment can declare its own: + +| Variable | Server `customProperties` | Example | Description | +|---|---|---|---| +| `DATACONTRACT_BIGQUERY_LOCATION` | `location` | `europe-west3` | Optional. Location in which query jobs run. Must match the location of the datasets. | +| `DATACONTRACT_BIGQUERY_KMS_KEY_NAME` | `kmsKeyName` | `projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key` | Optional. Cloud KMS key that encrypts the query results. The caller's service account needs `roles/cloudkms.cryptoKeyEncrypterDecrypter` on the key. | + +The variable wins over the custom property. + +```yaml +servers: + - server: bigquery + type: bigquery + project: my-project + dataset: my_dataset + customProperties: + - property: location + value: europe-west3 + - property: kmsKeyName + value: projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key +``` + `project` and `dataset` come from the contract's `servers` block, and can be overridden with `DATACONTRACT_BIGQUERY_PROJECT` and `DATACONTRACT_BIGQUERY_DATASET`. `datacontract import bigquery` always uses ADC — set `GOOGLE_APPLICATION_CREDENTIALS` to point it at a key file. ## Data types diff --git a/tests/test_connect_bigquery.py b/tests/test_connect_bigquery.py index 3c9c275c4..f7be0800f 100644 --- a/tests/test_connect_bigquery.py +++ b/tests/test_connect_bigquery.py @@ -17,11 +17,14 @@ "DATACONTRACT_BIGQUERY_ACCOUNT_INFO_JSON_PATH", "DATACONTRACT_BIGQUERY_BILLING_PROJECT", "DATACONTRACT_BIGQUERY_IMPERSONATION_ACCOUNT", + "DATACONTRACT_BIGQUERY_LOCATION", + "DATACONTRACT_BIGQUERY_KMS_KEY_NAME", "DATACONTRACT_BIGQUERY_PROJECT", "DATACONTRACT_BIGQUERY_DATASET", ] SERVICE_ACCOUNT = "runner@my-project.iam.gserviceaccount.com" +KMS_KEY = "projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key" @pytest.fixture @@ -42,14 +45,20 @@ def _connect(**overrides): return connect.call_args.kwargs -def _connect_ibis(): +def _connect_ibis(**overrides): """Connect through the real ibis BigQuery backend, stubbing out only the Google clients, so the assertions cover how ibis reads our arguments. - Returns the connection and the patched ``bigquery.Client``.""" + Returns the connection and the patched ``bigquery.Client``. + Without credentials, ibis would look up application default credentials.""" with patch("ibis.backends.bigquery.bq.Client") as client: client.return_value.default_query_job_config = None with patch("ibis.backends.bigquery.bqstorage.BigQueryReadClient"): - return connect_ibis(Run.create_run(), None, _server()), client + with patch("ibis.backends.bigquery.pydata_google_auth.default", return_value=(MagicMock(), None)): + return connect_ibis(Run.create_run(), None, _server(**overrides)), client + + +def _custom_properties(**values): + return [dict(property=name, value=value) for name, value in values.items()] def test_no_credentials_without_env_vars(env): @@ -146,3 +155,46 @@ def test_project_is_required_with_a_billing_project(env): _connect(project=None) assert e.value.name == "missing_project" + + +def test_no_location_or_kms_key_without_configuration(env): + con, client = _connect_ibis() + + assert client.call_args.kwargs["location"] is None + assert con.client.default_query_job_config.destination_encryption_configuration is None + + +def test_location_comes_from_env_variable(env): + env.setenv("DATACONTRACT_BIGQUERY_LOCATION", "europe-west3") + + assert _connect()["location"] == "europe-west3" + + +def test_location_comes_from_server_custom_property(env): + kwargs = _connect(customProperties=_custom_properties(location="europe-west3")) + + assert kwargs["location"] == "europe-west3" + + +def test_env_variable_wins_over_custom_property(env): + env.setenv("DATACONTRACT_BIGQUERY_LOCATION", "europe-west4") + + kwargs = _connect(customProperties=_custom_properties(location="europe-west3")) + + assert kwargs["location"] == "europe-west4" + + +def test_kms_key_is_set_on_the_default_query_job_config(env): + """Every query ibis runs merges the client's default query job config, so a key + set there also encrypts the anonymous tables that hold the query results.""" + env.setenv("DATACONTRACT_BIGQUERY_KMS_KEY_NAME", KMS_KEY) + + con, _ = _connect_ibis() + + assert con.client.default_query_job_config.destination_encryption_configuration.kms_key_name == KMS_KEY + + +def test_kms_key_comes_from_server_custom_property(env): + con, _ = _connect_ibis(customProperties=_custom_properties(kmsKeyName=KMS_KEY)) + + assert con.client.default_query_job_config.destination_encryption_configuration.kms_key_name == KMS_KEY From 04cdb330f2b7f9d2fbc943c36291973e90fb531b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Mon, 19 Oct 2026 17:28:31 +0200 Subject: [PATCH 2/3] Name the error a mismatched BigQuery location causes in the docs --- docs/docs/reference/bigquery.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/docs/reference/bigquery.md b/docs/docs/reference/bigquery.md index c6669890a..bf112f276 100644 --- a/docs/docs/reference/bigquery.md +++ b/docs/docs/reference/bigquery.md @@ -29,6 +29,8 @@ Authentication uses a Service Account Key or Application Default Credentials (AD | `DATACONTRACT_BIGQUERY_BILLING_PROJECT` | `my-compute-project` | Optional. Project to bill query jobs to. Requires `bigquery.jobUser`, `bigquery.readSessionUser` on the billing project and `bigquery.dataViewer` on the data project. | | `DATACONTRACT_BIGQUERY_IMPERSONATION_ACCOUNT` | `runner@my-project.iam.gserviceaccount.com` | Optional. Service account to impersonate, using the key file above (or ADC) as the source principal. Requires `roles/iam.serviceAccountTokenCreator` on the target. | +`project` and `dataset` come from the contract's `servers` block, and can be overridden with `DATACONTRACT_BIGQUERY_PROJECT` and `DATACONTRACT_BIGQUERY_DATASET`. `datacontract import bigquery` always uses ADC — set `GOOGLE_APPLICATION_CREDENTIALS` to point it at a key file. + ### Query location and encryption key By default, query jobs run in the location BigQuery chooses (`US` when none can be inferred) and carry no encryption key. Projects that enforce the org policy `constraints/gcp.restrictNonCmekServices` reject such jobs: @@ -45,6 +47,7 @@ Set the query location and a Cloud KMS key with these variables, or as `customPr | `DATACONTRACT_BIGQUERY_KMS_KEY_NAME` | `kmsKeyName` | `projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key` | Optional. Cloud KMS key that encrypts the query results. The caller's service account needs `roles/cloudkms.cryptoKeyEncrypterDecrypter` on the key. | The variable wins over the custom property. +A location that doesn't match the datasets' fails with `403 Access Denied: … User does not have permission to query table …, or perhaps it does not exist`. ```yaml servers: @@ -59,8 +62,6 @@ servers: value: projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key ``` -`project` and `dataset` come from the contract's `servers` block, and can be overridden with `DATACONTRACT_BIGQUERY_PROJECT` and `DATACONTRACT_BIGQUERY_DATASET`. `datacontract import bigquery` always uses ADC — set `GOOGLE_APPLICATION_CREDENTIALS` to point it at a key file. - ## Data types ### Importing From ba57dab02f48df8f9578158c1d246b436631467f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Mon, 19 Oct 2026 17:28:32 +0200 Subject: [PATCH 3/3] Drop a docstring line that restates the patch --- tests/test_connect_bigquery.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_connect_bigquery.py b/tests/test_connect_bigquery.py index f7be0800f..a89c3144e 100644 --- a/tests/test_connect_bigquery.py +++ b/tests/test_connect_bigquery.py @@ -48,8 +48,7 @@ def _connect(**overrides): def _connect_ibis(**overrides): """Connect through the real ibis BigQuery backend, stubbing out only the Google clients, so the assertions cover how ibis reads our arguments. - Returns the connection and the patched ``bigquery.Client``. - Without credentials, ibis would look up application default credentials.""" + Returns the connection and the patched ``bigquery.Client``.""" with patch("ibis.backends.bigquery.bq.Client") as client: client.return_value.default_query_job_config = None with patch("ibis.backends.bigquery.bqstorage.BigQueryReadClient"):