Skip to content

Commit ebaf7e4

Browse files
ezno12bassem.benyahiajschoedl
authored
Set the BigQuery query location and a Cloud KMS encryption key (#1728) (#1757)
* 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. * Name the error a mismatched BigQuery location causes in the docs * Drop a docstring line that restates the patch --------- Co-authored-by: bassem.benyahia <bassem.benyahia@aureskonnect.com> Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent 5c1a111 commit ebaf7e4

6 files changed

Lines changed: 110 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Added
1111
- `datacontract test` loads the custom quality checks a contract uses from Entropy Data when an Entropy Data API key is set, unless the local folder has them
1212
- `datacontract export sql`: export a schema with `physicalType: view` as a view (#1031)
13+
- `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)
1314

1415
### Changed
1516
- `datacontract test` matches custom quality check IDs regardless of case

‎datacontract/config/settings.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,8 @@ class Config(BaseSettings):
136136
bigquery_account_info_json_path: str | None = None
137137
bigquery_billing_project: str | None = None
138138
bigquery_impersonation_account: str | None = None
139+
bigquery_location: str | None = None
140+
bigquery_kms_key_name: str | None = None
139141
# overrides for the contract's servers block
140142
bigquery_project: str | None = None
141143
bigquery_dataset: str | None = None
@@ -582,6 +584,12 @@ def get_bigquery_billing_project(self, required: bool = False) -> str | None:
582584
def get_bigquery_impersonation_account(self, required: bool = False) -> str | None:
583585
return self._str_option("bigquery_impersonation_account", required)
584586

587+
def get_bigquery_location(self, required: bool = False) -> str | None:
588+
return self._str_option("bigquery_location", required)
589+
590+
def get_bigquery_kms_key_name(self, required: bool = False) -> str | None:
591+
return self._str_option("bigquery_kms_key_name", required)
592+
585593
def get_bigquery_project(self, required: bool = False) -> str | None:
586594
return self._str_option("bigquery_project", required)
587595

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,21 @@ def _connect_bigquery(ibis, server: Server, config: Config):
375375
)
376376
if credentials:
377377
kwargs["credentials"] = credentials
378-
return ibis.bigquery.connect(**kwargs)
378+
location = config.get_bigquery_location() or _get_custom_property(server, "location")
379+
if location:
380+
kwargs["location"] = location
381+
con = ibis.bigquery.connect(**kwargs)
382+
383+
kms_key_name = config.get_bigquery_kms_key_name() or _get_custom_property(server, "kmsKeyName")
384+
if kms_key_name:
385+
from google.cloud import bigquery
386+
387+
# Projects that enforce CMEK reject query jobs without a key. A dataset's default key does not
388+
# cover the anonymous tables holding query results, so set it on the config every query uses.
389+
con.client.default_query_job_config.destination_encryption_configuration = bigquery.EncryptionConfiguration(
390+
kms_key_name=kms_key_name
391+
)
392+
return con
379393

380394

381395
_BIGQUERY_SCOPES = ["https://www.googleapis.com/auth/bigquery"]

‎docs/docs/configuration.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,8 @@ Every option, by its environment variable name and the matching `Config` field.
175175
| `DATACONTRACT_BIGQUERY_ACCOUNT_INFO_JSON_PATH` | `bigquery_account_info_json_path` | string | |
176176
| `DATACONTRACT_BIGQUERY_BILLING_PROJECT` | `bigquery_billing_project` | string | |
177177
| `DATACONTRACT_BIGQUERY_IMPERSONATION_ACCOUNT` | `bigquery_impersonation_account` | string | |
178+
| `DATACONTRACT_BIGQUERY_LOCATION` | `bigquery_location` | string | |
179+
| `DATACONTRACT_BIGQUERY_KMS_KEY_NAME` | `bigquery_kms_key_name` | string | |
178180
| `DATACONTRACT_BIGQUERY_PROJECT` | `bigquery_project` | string | Overrides `project` from the contract's `servers` block |
179181
| `DATACONTRACT_BIGQUERY_DATASET` | `bigquery_dataset` | string | Overrides `dataset` from the contract's `servers` block |
180182

‎docs/docs/reference/bigquery.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,37 @@ Authentication uses a Service Account Key or Application Default Credentials (AD
3131

3232
`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.
3333

34+
### Query location and encryption key
35+
36+
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:
37+
38+
```
39+
Your administrator requires that you specify an encryption key for queries in project `my-project`.
40+
```
41+
42+
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:
43+
44+
| Variable | Server `customProperties` | Example | Description |
45+
|---|---|---|---|
46+
| `DATACONTRACT_BIGQUERY_LOCATION` | `location` | `europe-west3` | Optional. Location in which query jobs run. Must match the location of the datasets. |
47+
| `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. |
48+
49+
The variable wins over the custom property.
50+
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`.
51+
52+
```yaml
53+
servers:
54+
- server: bigquery
55+
type: bigquery
56+
project: my-project
57+
dataset: my_dataset
58+
customProperties:
59+
- property: location
60+
value: europe-west3
61+
- property: kmsKeyName
62+
value: projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key
63+
```
64+
3465
## Data types
3566
3667
### Importing

‎tests/test_connect_bigquery.py‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@
1717
"DATACONTRACT_BIGQUERY_ACCOUNT_INFO_JSON_PATH",
1818
"DATACONTRACT_BIGQUERY_BILLING_PROJECT",
1919
"DATACONTRACT_BIGQUERY_IMPERSONATION_ACCOUNT",
20+
"DATACONTRACT_BIGQUERY_LOCATION",
21+
"DATACONTRACT_BIGQUERY_KMS_KEY_NAME",
2022
"DATACONTRACT_BIGQUERY_PROJECT",
2123
"DATACONTRACT_BIGQUERY_DATASET",
2224
]
2325

2426
SERVICE_ACCOUNT = "runner@my-project.iam.gserviceaccount.com"
27+
KMS_KEY = "projects/my-kms-project/locations/europe-west3/keyRings/my-ring/cryptoKeys/my-key"
2528

2629

2730
@pytest.fixture
@@ -42,14 +45,19 @@ def _connect(**overrides):
4245
return connect.call_args.kwargs
4346

4447

45-
def _connect_ibis():
48+
def _connect_ibis(**overrides):
4649
"""Connect through the real ibis BigQuery backend, stubbing out only the
4750
Google clients, so the assertions cover how ibis reads our arguments.
4851
Returns the connection and the patched ``bigquery.Client``."""
4952
with patch("ibis.backends.bigquery.bq.Client") as client:
5053
client.return_value.default_query_job_config = None
5154
with patch("ibis.backends.bigquery.bqstorage.BigQueryReadClient"):
52-
return connect_ibis(Run.create_run(), None, _server()), client
55+
with patch("ibis.backends.bigquery.pydata_google_auth.default", return_value=(MagicMock(), None)):
56+
return connect_ibis(Run.create_run(), None, _server(**overrides)), client
57+
58+
59+
def _custom_properties(**values):
60+
return [dict(property=name, value=value) for name, value in values.items()]
5361

5462

5563
def test_no_credentials_without_env_vars(env):
@@ -146,3 +154,46 @@ def test_project_is_required_with_a_billing_project(env):
146154
_connect(project=None)
147155

148156
assert e.value.name == "missing_project"
157+
158+
159+
def test_no_location_or_kms_key_without_configuration(env):
160+
con, client = _connect_ibis()
161+
162+
assert client.call_args.kwargs["location"] is None
163+
assert con.client.default_query_job_config.destination_encryption_configuration is None
164+
165+
166+
def test_location_comes_from_env_variable(env):
167+
env.setenv("DATACONTRACT_BIGQUERY_LOCATION", "europe-west3")
168+
169+
assert _connect()["location"] == "europe-west3"
170+
171+
172+
def test_location_comes_from_server_custom_property(env):
173+
kwargs = _connect(customProperties=_custom_properties(location="europe-west3"))
174+
175+
assert kwargs["location"] == "europe-west3"
176+
177+
178+
def test_env_variable_wins_over_custom_property(env):
179+
env.setenv("DATACONTRACT_BIGQUERY_LOCATION", "europe-west4")
180+
181+
kwargs = _connect(customProperties=_custom_properties(location="europe-west3"))
182+
183+
assert kwargs["location"] == "europe-west4"
184+
185+
186+
def test_kms_key_is_set_on_the_default_query_job_config(env):
187+
"""Every query ibis runs merges the client's default query job config, so a key
188+
set there also encrypts the anonymous tables that hold the query results."""
189+
env.setenv("DATACONTRACT_BIGQUERY_KMS_KEY_NAME", KMS_KEY)
190+
191+
con, _ = _connect_ibis()
192+
193+
assert con.client.default_query_job_config.destination_encryption_configuration.kms_key_name == KMS_KEY
194+
195+
196+
def test_kms_key_comes_from_server_custom_property(env):
197+
con, _ = _connect_ibis(customProperties=_custom_properties(kmsKeyName=KMS_KEY))
198+
199+
assert con.client.default_query_job_config.destination_encryption_configuration.kms_key_name == KMS_KEY

0 commit comments

Comments
 (0)