What You'll Learn
- 1Choose between Google-managed, CMEK and CSEK encryption from the threat model
- 2Draw a VPC Service Controls perimeter and verify it in dry-run mode
- 3Replace service account keys with Workload Identity Federation
- 4Turn audit logs into alerts that identify a reader rather than a service
Start With the Threat, Not the Tool
Security work goes wrong when it begins as a shopping list. Begin instead with what would actually hurt: an attacker with a stolen credential reading a dataset it should not reach, an internal account exporting more rows than its role implies, a misconfigured bucket accepting anonymous reads, or a dependency in a pipeline quietly shipping data to an outside endpoint. Each of those has a different control as its first line, and buying the wrong one produces a compliance checkbox rather than a reduction in risk.
The controls group into three functions. Prevent: IAM bindings, organization policies, VPC Service Controls and private connectivity, which stop the action from being possible. Detect: audit logs, log-based metrics and policy intelligence, which turn an action into a signal within minutes. Contain: key revocation, perimeter denial and short-lived credentials, which limit how long a compromised identity keeps working. A design that only prevents assumes the perimeter never moves, so every serious architecture carries at least one control in each column.
| Threat | First control | Backup control | Evidence |
|---|---|---|---|
| Stolen credential used elsewhere | Workload Identity Federation, short lived tokens | VPC Service Controls perimeter | Policy denied log entries |
| Over-broad dataset read | IAM with condition, policy tags | Authorized views, masking | Data access audit log |
| Anonymous bucket exposure | Uniform bucket-level access, org policy | Public access prevention | Storage audit log |
| Insider exporting bulk rows | Least privilege, column tags | DLP job alerts, quota caps | Findings and export job history |
| Key compromise | CMEK revocation | Re-encryption with a new key | KMS key operation log |
Encryption: Three Levels of Control
Every object in GCP is encrypted at rest by default, so the real question is who holds the key and what happens when you want to destroy it. Google-managed keys are rotated automatically and cost nothing extra, which is correct for most data. A customer-managed encryption key stored in Cloud KMS puts rotation, key access policy and destruction under your control, and the resource cannot be read once the key version is destroyed, which is the property regulators ask about. Customer-supplied encryption keys go further: you provide the key material for each request, and Google never stores it, so a lost key means permanently unreadable data.
The trade is availability as much as control. A CMEK that has been disabled or destroyed renders the data unusable for everyone, including administrators who did not intend that outcome, so key permissions belong in break-glass procedures rather than in the ordinary IAM module. Most teams land on CMEK for the datasets a regulator names, Google-managed keys everywhere else, and a documented rotation period enforced by the key ring configuration.
â¨
Best Practice: Use CMEK for sensitive BigQuery and Cloud Storage data, enforce short key rotation, and put the ability to disable a key behind a two-person procedure. Layer VPC Service Controls so a stolen credential cannot reach the data from outside the perimeter, enable Data Access audit logs on sensitive projects only, and eliminate service account keys entirely with Workload Identity Federation.
CMEK with Cloud KMS
A key ring belongs to a region, so the key and the data it protects should live in the same place, and a key intended for BigQuery should be created with a purpose that BigQuery accepts. Rotation is a property of the key rather than of the data: once rotation_period is set, new versions are generated on schedule and the service transparently uses the current version, so re-encryption does not require rewriting the table.
from google.cloud import kms_v1
client = kms_v1.KeyManagementServiceClient()
key_ring = client.create_key_ring(
request={
"parent": "projects/my-project/locations/us-central1",
"key_ring_id": "data-engineering-keyring",
}
)
key = client.create_crypto_key(
request={
"parent": key_ring.name,
"crypto_key_id": "bigquery-encryption-key",
"purpose": "ENCRYPT_DECRYPT",
"version_template": {
"algorithm": "GOOGLE_SYMMETRIC_ENCRYPTION",
"protection_level": kms_v1.CryptoKeyVersion.ProtectionLevel.HSM
}
}
)
key.rotation_period = {"seconds": 7776000} # 90 days
client.update_crypto_key(request={"crypto_key": key})
Two operational facts matter more than the API calls. Destroying a version is irreversible and makes any data still encrypted with it unreadable, which is exactly what an erasure request sometimes needs and exactly what an accidental click must never do. And HSM protection moves the key material into hardware for a higher price, which is justified for a handful of master keys rather than for every key in the project.
VPC Service Controls: The Perimeter
IAM answers whether an identity may call a service; VPC Service Controls answers whether that service may be reached from outside a boundary. Together they cover the failure mode IAM cannot: a valid credential for a legitimate service being used from an unexpected network or account to read data out.
from google.cloud import accesscontextmanager_v1
client = accesscontextmanager_v1.AccessContextManagerClient()
policy = client.create_access_policy(
request={
"parent": "organizations/123456789",
"title": "Data Engineering Access Policy",
"scopes": ["projects/my-project"]
}
)
perimeter = client.create_service_perimeter(
request={
"parent": policy.name,
"service_perimeter_id": "data-engineering-perimeter",
"service_perimeter": {
"title": "Data Engineering Perimeter",
"status": {
"resources": ["projects/my-project"],
"restricted_services": [
"bigquery.googleapis.com",
"storage.googleapis.com",
"dataflow.googleapis.com"
],
"vpc_accessible_services": {
"enable_restriction": True,
"allowed_services": ["bigquery.googleapis.com"]
}
}
}
}
)
Deploy the perimeter in dry run mode first. In dry run the service writes policy denied log entries without enforcing them, which reveals every legitimate workflow that would break: an external scheduler, a partner's API client, a data transfer into another project. Each one is then either moved inside the perimeter, allowed through a bridge or access level, or removed. Enforcing on day one without that list produces an outage; enforcing without reviewing the denials afterwards produces a perimeter nobody can audit.
Identity Without Long-Lived Keys
Service account keys are the credential most likely to leak, because they are files that end up in laptops, repositories and build logs, and they do not expire. Workload Identity Federation removes them by letting an external identity, a GitHub Actions workflow, an AWS role or an Azure principal, exchange a short lived token for a Google token scoped to one service account.
gcloud iam workload-identity-pools create github-pool \
--project="my-project" --location="global" \
--display-name="GitHub OIDC pool"
gcloud iam workload-identity-pools providers create-oidc github-provider \
--project="my-project" --location="global" \
--workload-identity-pool="github-pool" \
--issuer-uri="https://token.actions.githubusercontent.com" \
--attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository"
gcloud iam service-accounts add-iam-policy-binding [email protected] \
--project="my-project" \
--role="roles/iam.workloadIdentityUser" \
--member="principalSet://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/github-pool/attribute.repository/my-org/repo"
The binding is deliberately narrow: only tokens asserting that one repository may assume that one service account. Add an attribute condition on the branch or environment and a pull request from a fork cannot reach production data at all, which is a property no key file can express.
Reading Audit Logs Like an Analyst
Four log types answer four different questions. Admin activity records who changed a resource and is always on and free. Data access records who read data and is off by default because it is voluminous and chargeable, which makes enabling it a deliberate decision for sensitive projects. System events record what the platform itself did, such as a host maintenance event. Policy denied records every request an organization policy or a perimeter blocked, and a sudden cluster of them is the signature of an attacker probing the boundary.
Route them with a log sink into a bucket in a separate project, then attach log-based metrics to the patterns that matter: a service account reading tables it has never touched, a bulk export job created by a human identity, a key disabled outside a change window, or any anonymous access attempt on a storage bucket. Metrics turn a search through terabytes of logs into an alert with a threshold, and the alert carries the principal so the responder starts with a person rather than with a service name.
Securing a Pipeline End to End
A data pipeline has a specific and forgiving attack surface, because every hop is an identity and a network path you control. Give each job its own service account with only the roles it needs, so a compromised Dataflow job cannot read the datasets it merely writes to. Run the workers in a VPC with private Google access or private service connect so traffic never crosses the public internet. Apply CMEK on the destination dataset and VPC Service Controls around the project that holds it, then mask or tokenize identifiers before they reach a non-production environment rather than trusting a network boundary to keep them apart.
The last control is the one teams skip: verify the chain. Run the pipeline under a deliberately over-privileged test account and confirm the audit log shows exactly the reads you expect and nothing else, then reduce the bindings until the log matches the design. A pipeline that has never been observed reading data is a pipeline nobody can certify.
Common Interview Questions
Q1: Google-managed keys or CMEK?
Answer: Google-managed keys rotate automatically and require no maintenance, which fits most data. CMEK gives you the rotation schedule, the key level IAM policy and the ability to destroy the key, which is what a regulator means by control of encryption, and it is required when policy names customer-managed keys explicitly.
Q2: What are VPC Service Controls?
Answer: A perimeter around projects and services that blocks calls to restricted services from outside it, regardless of the IAM binding on the caller. It is the control that stops an exfiltrated credential from reading BigQuery from an unexpected network or account, and it should be deployed in dry run first to enumerate what would break.
Q3: Which audit logs must be enabled?
Answer: Admin activity is always on. Data access logs record reads and must be enabled per service for the projects holding sensitive data, since they are chargeable. Policy denied logs come with the perimeter and organization policies. Export all of them to a project the workload cannot write to.
Q4: How do you secure a pipeline?
Answer: One narrow service account per job, no keys, Workload Identity Federation for external callers, private connectivity for the workers, CMEK on the destination, a perimeter around the project, and masking before any non-production copy. Then read the audit log to confirm the design matches reality.
Q5: What is Workload Identity Federation?
Answer: It exchanges an OIDC or SAML token from an external identity provider for a short lived Google token bound to a service account, with attribute conditions on repository, branch or environment. It removes long lived keys from CI entirely and makes the trust relationship auditable and revocable.
Interview Questions
Q1: Why deploy a VPC Service Controls perimeter in dry run first?
Dry run writes policy denied entries without enforcing them, so you can list every legitimate cross-boundary workflow and fix or allow it before enforcement turns those calls into an outage.
Q2: What happens when a CMEK version is destroyed?
Data encrypted with that version becomes permanently unreadable, including for administrators, which is why destruction belongs behind a two-person break-glass procedure separate from ordinary key administration.
Q3: How do audit logs detect an insider rather than an external attacker?
Data access logs carry the principal and the resource, so a normal account reading tables outside its usual pattern, or exporting volume far above its baseline, stands out as an anomaly on an otherwise valid identity.
Q4: Why prefer an attribute condition over a broader IAM role?
A condition narrows the same grant to a branch, environment or repository, so a compromised pull request from an untrusted fork cannot assume the production service account even though the role itself is unchanged.
Common Mistakes
Enforcing a service perimeter without a dry run period
Fix: Run dry run and review policy denied logs first, because every external scheduler and partner client has to be moved inside or explicitly allowed.
Distributing service account keys to build systems
Fix: Use Workload Identity Federation with attribute conditions, so credentials are short lived and bound to a repository or environment.
Leaving Data Access audit logs off because they cost money
Fix: Enable them only on the projects holding sensitive data and export them elsewhere, since a read nobody logged cannot be investigated.
Key Takeaways
- Start from the threat and place one control in each of prevent, detect and contain rather than buying controls by checklist
- Google-managed, CMEK and CSEK differ in who holds and destroys the key, and destroying a CMEK version makes the data permanently unreadable
- VPC Service Controls covers the case IAM cannot, a valid credential used from outside the boundary, and must be dry run before enforcement
- Workload Identity Federation removes long lived keys by exchanging external tokens for short lived Google tokens with attribute conditions