3: Ensuring data protection

    Inspecting and redacting personally identifiable information (PII) using Sensitive Data Protection

    A data protection program that begins at the encryption layer is already late.

    Plaintext personally identifiable information that lands in a Cloud Storage bucket, a BigQuery table, or a Pub/Sub topic without classification will be replicated into downstream caches, training corpora, audit exports, and developer notebooks within hours.

    Sensitive Data Protection (the renamed successor to Cloud Data Loss Prevention, exposed under the dlp.googleapis.com API and the gcloud dlp command set) is the discovery and transformation engine that classifies data, generates risk reports, and applies redactions before that downstream copy fans out.

    The service is the entry point to every other control in this chapter: without classification you cannot prove the right key control is applied, the right access restriction is in place, or the right retention rule has fired.

    How it works

    The inspection model rests on three building blocks: InfoTypes, Templates, and Findings.

    An InfoType is a named classifier such as EMAIL_ADDRESS, CREDIT_CARD_NUMBER, US_SOCIAL_SECURITY_NUMBER, IBAN_CODE, or PERSON_NAME.

    Built-in InfoTypes ship with detection rules tuned by Google; custom InfoTypes let an organization plug in regex patterns, dictionaries, or stored InfoTypes backed by a Cloud Storage object containing a phrase list (for example, an employee directory exported to a .txt file).

    A Template packages the detection configuration (InfoTypes, minimum likelihood, exclusion rules, custom infoTypes, max findings per item) into a reusable resource at organization, folder, or project scope so a security team can govern one template centrally and have all scanning jobs reference it.

    A Finding is the per-item, per-quote record that ties an InfoType match to its location in the source data along with a likelihood enumeration (VERY_UNLIKELY through VERY_LIKELY).

    Two execution surfaces matter for the exam.

    • Inspection jobs (DlpJob resources) operate over a bounded data source: a BigQuery table, a Cloud Storage prefix, or a Datastore kind.
    • Storage scanners (the "Sensitive Data Protection discovery" surface) operate continuously across an organization and emit profiles into Security Command Center.
    • They remove the need for a security team to hand-write one scan job per dataset and instead auto-discover sensitive data at the granularity of column-and-table for BigQuery, file-and-bucket for Cloud Storage, and column-and-database for Cloud SQL.

    Discovery results are surfaced as Data Profile findings inside Security Command Center, where the same finding can pivot a security analyst into VPC Service Controls posture, IAM bindings, and audit log history.

    Designing inspection at organization scope

    A well-formed inspection design at organization scope follows four rules.

    • First, place every reusable InfoType, deidentify, and inspect template at the organization or folder level so individual projects cannot override the classification baseline.
    • Second, attach a Pub/Sub completion topic to every job so downstream automation (Cloud Functions, Workflows, Cloud Run jobs) can fire on the JOB_DONE notification.
    • Third, write findings to a dedicated BigQuery dataset in a separate project under tight IAM control because findings include quoted plaintext snippets and are themselves sensitive.
    • Fourth, attach the discovery service agent to a security-owned project and let it scan across the organization through a workload identity that has only the predefined roles/dlp.user and roles/dlp.jobsEditor plus the appropriate roles/bigquery.dataViewer or roles/storage.objectViewer on each scanned dataset.
    # Create an organization-scoped inspect template that catches PII across all
    # projects in the acme.example org. The template lives in a security-owned
    # project but is referenced from per-project jobs.
    
    gcloud dlp inspect-templates create \
     --location=us \
     --display-name="acme-baseline-pii" \
     --inspect-template-from-file=baseline-pii.json \
     --project=acme-sec-control
    
    # baseline-pii.json (excerpt)
    # {
    # "inspectConfig": {
    # "infoTypes": [
    # {"name": "EMAIL_ADDRESS"},
    # {"name": "CREDIT_CARD_NUMBER"},
    # {"name": "US_SOCIAL_SECURITY_NUMBER"},
    # {"name": "IBAN_CODE"},
    # {"name": "PERSON_NAME"}
    # ],
    # "minLikelihood": "LIKELY",
    # "includeQuote": false,
    # "limits": {"maxFindingsPerItem": 100}
    # }
    # }
    

    Setting includeQuote to false is the design lever that prevents the findings store from itself becoming a PII reservoir.

    A finding record then carries the offset, the InfoType, and the likelihood, but not the matched substring.

    Security teams that need quotes to triage false positives can flip the field on a per-template basis and route those quote-bearing findings into a higher-IAM-scoped audit project.

    Running inspection jobs over BigQuery, Cloud Storage, and Pub/Sub

    Inspection jobs over BigQuery scan a table and write findings either back into BigQuery, into a Pub/Sub topic, or into Security Command Center. The job can sample rows (rowsLimit, rowsLimitPercent) and restrict to identified fields (identifyingFields) so that the findings table can be joined back to the source by a stable key.

    Inspection jobs over Cloud Storage walk a prefix, optionally restrict by file type (fileTypes: [TEXT_FILE, IMAGE]), and can sample by bytesLimitPerFile.

    Streaming inspection is handled through the content.inspect and content.deidentify RPCs called from a Dataflow streaming pipeline or a Cloud Run inline service that consumes a Pub/Sub topic.

    # Inline inspection of a Pub/Sub payload before writing to BigQuery.
    # The pipeline runs in Dataflow with the worker service account holding
    # roles/dlp.user, roles/pubsub.subscriber, and roles/bigquery.dataEditor.
    
    from google.cloud import dlp_v2
    
    dlp = dlp_v2.DlpServiceClient()
    PARENT = "projects/acme-data-prod/locations/us"
    TEMPLATE = "organizations/123456789/inspectTemplates/acme-baseline-pii"
    
    def inspect_record(payload: str) -> dict:
     response = dlp.inspect_content(
     request={
     "parent": PARENT,
     "inspect_template_name": TEMPLATE,
     "item": {"value": payload},
     }
     )
     return {
     "has_pii": bool(response.result.findings),
     "info_types": sorted({f.info_type.name for f in response.result.findings}),
     "max_likelihood": max(
     (f.likelihood for f in response.result.findings),
     default=dlp_v2.Likelihood.LIKELIHOOD_UNSPECIFIED,
     ).name,
     }
    

    💡 Exam Trap: A scenario describes a security team that wants to "continuously discover sensitive data across every BigQuery project in the organization without authoring per-project jobs." The correct answer is the Sensitive Data Protection discovery configuration at the organization parent, not a DlpJob per project. DlpJob is bounded to one resource; discovery is continuous and organization-scoped.

    📊 Limit: A single InspectContent request is capped at 0.5 MB of text per call. Larger payloads must be split, written to Cloud Storage and scanned as an inspection job, or chunked client-side before the call.

    Creating and managing encryption keys for CMEK and EKM

    Inspection produces a classification label, but the label is only useful if the encryption layer can react to it.

    Customer-managed encryption keys (CMEK) and Cloud External Key Manager (EKM) keys give a security team the ability to revoke access to the plaintext form of a classified table or bucket by destroying or disabling the key version, even when IAM bindings are intact. Both surfaces share the same primitives.

    A KeyRing is a regional or multi-regional container; a CryptoKey lives inside a key ring; each CryptoKey carries one or more CryptoKeyVersion resources. The primary version is the one used for new encryption operations; older versions remain available for decryption until they are destroyed.

    Rotation is configured per key by setting rotationPeriod (minimum one day, no maximum) and nextRotationTime. When rotation fires, Cloud KMS creates a new version and marks it primary; older versions remain enabled until explicitly disabled or destroyed. Disabling a version stops both encryption and decryption immediately; destroying a version moves it to DESTROY_SCHEDULED state for 24 hours by default before the key material is irreversibly removed. The 24-hour delay is configurable per key (destroyScheduledDuration) between 24 hours and 120 days.

    Importing existing key material into Cloud KMS is supported through an import job. The flow is:

    • create a KeyRing
    • create an ImportJob with a wrapping algorithm (RSA_OAEP_3072_SHA256_AES_256 or stronger)
    • download the import job's public key
    • wrap the customer's key material on the customer side
    • submit the wrapped material to the import job

    The import job and the wrapping operation never expose the key material to Google's control plane in plaintext.

    # Create a CMEK key ring, key, and rotation schedule for the acme-data-prod
    # project. The key encrypts BigQuery tables in us-central1 and rotates every
    # 30 days.
    
    gcloud kms keyrings create acme-prod-ring \
     --location=us-central1 \
     --project=acme-data-prod
    
    gcloud kms keys create bq-pii-key \
     --keyring=acme-prod-ring \
     --location=us-central1 \
     --purpose=encryption \
     --rotation-period=30d \
     --next-rotation-time=$(date -u -d "now + 30 days" +"%Y-%m-%dT%H:%M:%SZ") \
     --project=acme-data-prod
    
    # Grant the BigQuery service account the encrypter/decrypter role so it can
    # use the key to encrypt new tables in the project.
    
    PROJECT_NUMBER=$(gcloud projects describe acme-data-prod --format="value(projectNumber)")
    gcloud kms keys add-iam-policy-binding bq-pii-key \
     --keyring=acme-prod-ring \
     --location=us-central1 \
     --member="serviceAccount:bq-${PROJECT_NUMBER}@bigquery-encryption.iam.gserviceaccount.com" \
     --role=roles/cloudkms.cryptoKeyEncrypterDecrypter \
     --project=acme-data-prod
    

    Cloud EKM extends the model so that the key material lives outside Google Cloud in a customer-controlled external key manager (Thales CipherTrust Manager, Fortanix DSM, Futurex KMES, Equinix SmartKey, and similar partners). The Google Cloud-resident object is a stub CryptoKeyVersion of protection level EXTERNAL (over the internet) or EXTERNAL_VPC (over an interconnect into the partner's VPC).

    Each encrypt and decrypt call is brokered through the external key manager: the customer can revoke at the external system and lose access to the data even if their Google Cloud IAM bindings are intact. This is the only Cloud KMS option where the key material is not stored in a Google-managed boundary.

    ⚠️ Anti-Pattern: Deleting a key ring or key to "rotate" the key. Key rings cannot be deleted; keys can be set to destroy individual versions but the key itself remains in the metadata catalog. Operators who script a gcloud kms keyrings delete will discover the command does not exist; the only correct rotation surface is gcloud kms keys versions create or automatic rotation.

    🎯 Scenario: A regulator demands that the customer prove they can break-glass revoke access to a dataset without Google's cooperation. The acceptable answer is Cloud EKM with key revocation on the external KMS, because CMEK keys reside in Google-managed Cloud KMS even though the customer controls the IAM and lifecycle.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the GCP - Professional Cloud Security Engineer learning hub.