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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `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
- `datacontract export sql`: export a schema with `physicalType: view` as a view (#1031)
- `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
- `datacontract test` matches custom quality check IDs regardless of case
Expand Down
8 changes: 8 additions & 0 deletions datacontract/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
16 changes: 15 additions & 1 deletion datacontract/engines/ibis/connections/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
31 changes: 31 additions & 0 deletions docs/docs/reference/bigquery.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,37 @@ Authentication uses a Service Account Key or Application Default Credentials (AD

`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:

```
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.
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:
- 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
```

## Data types

### Importing
Expand Down
55 changes: 53 additions & 2 deletions tests/test_connect_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -42,14 +45,19 @@ 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``."""
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):
Expand Down Expand Up @@ -146,3 +154,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
Loading