Invia i risultati del job di ispezione di Sensitive Data Protection a Security Command Center

Questa guida illustra l'ispezione dei dati in Cloud Storage, Firestore in modalità Datastore (Datastore) o BigQuery e l'invio dei risultati dell'ispezione a Security Command Center.

Per i dati BigQuery, puoi eseguire anche la profilazione, che è diversa da un'operazione di ispezione. Puoi anche inviare profili di dati a Security Command Center. Per ulteriori informazioni, vedi Pubblicare profili di dati in Security Command Center.

Panoramica

Security Command Center consente di raccogliere dati sulle minacce alla sicurezza, nonché identificare e intervenire prima che possano causare danni o perdite all'azienda. Con Security Command Center puoi eseguire diverse azioni relative alla sicurezza da un'unica dashboard centralizzata.

La protezione dei dati sensibili è integrata con Security Command Center. Quando utilizzi un'azione di Sensitive Data Protection per ispezionare i repository di Google Cloud Storage alla ricerca di dati sensibili, i risultati possono essere inviati direttamente alla dashboard di Security Command Center. Vengono visualizzate accanto ad altre metriche di sicurezza.

Completando la procedura descritta in questa guida, procedi nel seguente modo:

  • Abilita Security Command Center e Sensitive Data Protection.
  • Configura Sensitive Data Protection per ispezionare un repository Google Cloud Storage, un bucket Cloud Storage, una tabella BigQuery o un tipo di datastore.
  • Configura una scansione di Sensitive Data Protection per inviare i risultati del job di ispezione a Security Command Center.

Per ulteriori informazioni su Security Command Center, consulta la documentazione di Security Command Center.

Se vuoi inviare a Security Command Center i risultati delle analisi di rilevamento, non i job di ispezione, consulta la documentazione per la profilazione di un'organizzazione, una cartella o un progetto.

Costi

In questo documento vengono utilizzati i seguenti componenti fatturabili di Google Cloud:

  • Sensitive Data Protection
  • Cloud Storage
  • BigQuery
  • Datastore

Per generare una stima dei costi in base all'utilizzo previsto, utilizza il Calcolatore prezzi. I nuovi utenti di Google Cloud possono essere idonei a una prova senza costi aggiuntivi.

Prima di iniziare

Prima di poter inviare i risultati dell'analisi di Sensitive Data Protection a Security Command Center, devi eseguire ciascuna delle seguenti operazioni:

  • Passaggio 1: imposta i repository di Google Cloud Storage.
  • Passaggio 2: imposta i ruoli IAM (Identity and Access Management).
  • Passaggio 3: attiva Security Command Center.
  • Passaggio 4: attiva Sensitive Data Protection.
  • Passaggio 5: attiva Sensitive Data Protection come origine di sicurezza per Security Command Center.

La procedura per configurare questi componenti è descritta nelle sezioni seguenti.

Passaggio 1: imposta i repository di Google Cloud Storage

Scegli se eseguire la scansione del tuo repository Google Cloud Storage o di un repository di esempio. Questo argomento fornisce istruzioni per entrambi gli scenari.

Scansiona i tuoi dati

Se vuoi scansionare il tuo bucket Cloud Storage, la tabella BigQuery o il tipo di Datastore esistente, apri prima il progetto in cui si trova il repository. Nei passaggi successivi, abiliterai sia Security Command Center che Sensitive Data Protection per questo progetto e la relativa organizzazione.

Dopo aver aperto il progetto che vuoi utilizzare, vai al Passaggio 2 per configurare alcuni ruoli IAM.

Analizza i dati di esempio

Se vuoi eseguire la scansione di un set di dati di test, assicurati di aver configurato un account di fatturazione, quindi crea un nuovo progetto. Per completare questo passaggio, devi disporre del ruolo IAM Autore progetto. Scopri di più sui ruoli IAM.

  1. Se non hai ancora configurato la fatturazione, configura un account di fatturazione.

    Scopri come attivare la fatturazione

  2. Vai alla pagina Nuovo progetto nella console Google Cloud.

    Vai al nuovo progetto

  3. Nell'elenco a discesa Account di fatturazione, seleziona l'account di fatturazione a cui deve essere fatturato il progetto.
  4. Nell'elenco a discesa Organizzazione, seleziona l'organizzazione in cui vuoi creare il progetto.
  5. Nell'elenco a discesa Posizione, seleziona l'organizzazione o la cartella in cui vuoi creare il progetto.

Quindi, scarica e memorizza i dati di esempio:

  1. Vai al repository dei tutorial di Cloud Functions su GitHub.
  2. Fai clic su Clona o scarica, quindi su Scarica ZIP.
  3. Estrai il file ZIP che hai scaricato.
  4. Vai alla pagina Browser Storage nella console Google Cloud.

    Vai a Cloud Storage

  5. Fai clic su Crea bucket.
  6. Nella pagina Crea un bucket, assegna al bucket un nome univoco, quindi fai clic su Crea.
  7. Nella pagina Dettagli bucket, fai clic su Carica cartella.
  8. Vai alla cartella dlp-cloud-functions-tutorials-master che hai estratto, aprila e seleziona la cartella sample_data. Fai clic su Carica per caricare i contenuti della cartella in Cloud Storage.

Prendi nota del nome che hai assegnato al bucket Cloud Storage per un secondo momento. Al termine del caricamento del file, puoi continuare.

Passaggio 2: imposta i ruoli IAM

Per utilizzare Sensitive Data Protection per inviare i risultati della scansione a Security Command Center, devi disporre dei ruoli IAM Amministratore Centro sicurezza ed Editor job di protezione dei dati sensibili. Questa sezione descrive come aggiungere i ruoli. Per completare questa sezione, devi disporre del ruolo IAM Amministratore organizzazione.

  1. Vai alla pagina IAM.

    Vai a IAM

  2. Nella scheda Visualizza per entità, trova il tuo Account Google e fai clic su Modifica entità.
  3. Aggiungi i ruoli Amministratore Centro sicurezza ed Editor job di protezione dei dati sensibili:

    1. Nel riquadro Modifica accesso, fai clic su Aggiungi un altro ruolo.
    2. Nell'elenco Seleziona un ruolo, cerca Amministratore Centro sicurezza e selezionalo.
    3. Fai clic su Aggiungi un altro ruolo.
    4. Nell'elenco Seleziona un ruolo, cerca Editor job DLP e selezionalo.
    5. Fai clic su Salva.

Ora disponi dei ruoli Editor job di protezione dei dati sensibili e Amministratore Centro sicurezza per la tua organizzazione. Questi ruoli consentono di completare le attività rimanenti di questo argomento.

Passaggio 3: attiva Security Command Center

  1. Vai alla pagina Security Command Center nella console Google Cloud.

    Vai a Security Command Center

  2. Nell'elenco a discesa Organizzazione, seleziona l'organizzazione per la quale vuoi attivare Sensitive Data Protection, quindi fai clic su Seleziona.

  3. Nella pagina Abilita rilevamento asset visualizzata, seleziona Tutti i progetti attuali e futuri e fai clic su Abilita. Dovrebbe essere visualizzato un messaggio che informa che Sensitive Data Protection sta iniziando il rilevamento degli asset.

Una volta completato il rilevamento degli asset, Sensitive Data Protection mostrerà gli asset Google Cloud supportati. Il rilevamento degli asset potrebbe richiedere alcuni minuti e potrebbe essere necessario aggiornare la pagina per visualizzare gli asset.

Per ulteriori informazioni sull'abilitazione di Security Command Center, consulta la documentazione di Security Command Center.

Passaggio 4: attiva Sensitive Data Protection

Abilita Sensitive Data Protection per il progetto da scansionare. Il progetto deve trovarsi all'interno della stessa organizzazione per la quale hai abilitato Security Command Center. Per abilitare la protezione dei dati sensibili utilizzando la console Google Cloud:

  1. Nella console Google Cloud, vai alla pagina Abilita l'accesso all'API.

    Abilitare l'API

  2. Nella barra degli strumenti, seleziona il progetto dal Passaggio 1 di questa guida. Il progetto deve contenere il bucket Cloud Storage, la tabella BigQuery o il tipo di Datastore da scansionare.
  3. Tocca Avanti.
  4. Fai clic su Abilita.

La protezione dei dati sensibili è ora abilitata per il tuo progetto.

Passaggio 5: attiva Sensitive Data Protection come servizio integrato per Security Command Center

Per visualizzare i risultati dell'analisi di Sensitive Data Protection in Security Command Center, abilita Sensitive Data Protection come servizio integrato. Per ulteriori informazioni, vedi Aggiungere un servizio integrato di Google Cloud nella documentazione di Security Command Center.

I risultati relativi a Sensitive Data Protection vengono visualizzati nella pagina Risultati di Security Command Center.

Configura ed esegui una scansione di ispezione di Sensitive Data Protection

In questa sezione configurerai ed esegui un job di ispezione di Sensitive Data Protection.

Il job di ispezione che configuri qui indica a Sensitive Data Protection di eseguire la scansione dei dati di esempio archiviati in Cloud Storage o dei tuoi dati archiviati in Cloud Storage, Datastore o BigQuery. Nella configurazione del job specificata puoi anche chiedere a Sensitive Data Protection di salvare i risultati della scansione in Security Command Center.

Passaggio 1: prendi nota dell'identificatore del progetto

  1. Vai alla console Google Cloud.

    Vai alla console Google Cloud

  2. Fai clic su Seleziona.
  3. Nell'elenco a discesa Seleziona da, seleziona l'organizzazione per la quale hai abilitato Security Command Center.
  4. In ID, copia l'ID progetto per il progetto contenente i dati da scansionare.
  5. In Nome, fai clic sul progetto per selezionarlo.

Passaggio 2: apri Explorer API e configura il job

  1. Vai a Explorer API nella pagina di riferimento per il metodo dlpJobs.create facendo clic sul seguente pulsante:

    Apri Explorer API

  2. Nella casella parent, inserisci quanto segue, dove PROJECT_ID è l'ID progetto che hai annotato nel passaggio 1:
    projects/PROJECT_ID

Sostituisci i contenuti del campo Request body (Corpo della richiesta) con il seguente JSON per il tipo di dati che vuoi utilizzare: dati di esempio in un bucket Cloud Storage o i tuoi dati archiviati in Cloud Storage, Datastore o BigQuery.

Dati di esempio

Se hai creato un bucket Cloud Storage per archiviare i dati di esempio, copia il seguente JSON e incollalo nel campo Corpo della richiesta. Sostituisci BUCKET_NAME con il nome che hai assegnato al tuo bucket Cloud Storage:

{
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://BUCKET_NAME/**"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"EMAIL_ADDRESS"
        },
        {
          "name":"PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "includeQuote":true,
      "minLikelihood":"UNLIKELY",
      "limits":{
        "maxFindingsPerRequest":100
      }
    },
    "actions":[
      {
        "publishSummaryToCscc":{

        }
      }
    ]
  }
}

Dati di Cloud Storage

Per eseguire la scansione del tuo bucket Cloud Storage, copia il seguente JSON e incollalo nel campo Corpo della richiesta.

Sostituisci PATH_NAME con il percorso della località da scansionare. Per eseguire una scansione ricorsiva, termina il percorso con due asterischi, ad esempio gs://path_to_files/**. Per eseguire la scansione di una directory specifica e non oltre, termina il percorso con un asterisco, ad esempio gs://path_to_files/*.

{
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://PATH_NAME"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"EMAIL_ADDRESS"
        },
        {
          "name":"PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "includeQuote":true,
      "minLikelihood":"UNLIKELY",
      "limits":{
        "maxFindingsPerRequest":100
      }
    },
    "actions":[
      {
        "publishSummaryToCscc":{

        }
      }
    ]
  }
}

Per scoprire di più sulle opzioni di scansione disponibili, consulta Ispezione dello spazio di archiviazione e dei database per l'individuazione di dati sensibili.

Dati Datastore

Per analizzare i tuoi dati conservati in Datastore, copia il seguente JSON e incollalo nel campo Request body (Corpo della richiesta).

Sostituisci DATASTORE_KIND con il nome del tipo di datastore. Puoi anche sostituire NAMESPACE_ID e PROJECT_ID con gli identificatori dello spazio dei nomi e del progetto, in alternativa, puoi rimuovere "partitionID" completamente se vuoi.

{
  "inspectJob":{
    "storageConfig":{
      "datastoreOptions":{
        "kind":{
          "name":"DATASTORE_KIND"
        },
        "partitionId":{
          "namespaceId":"NAMESPACE_ID",
          "projectId":"PROJECT_ID"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"EMAIL_ADDRESS"
        },
        {
          "name":"PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "includeQuote":true,
      "minLikelihood":"UNLIKELY",
      "limits":{
        "maxFindingsPerRequest":100
      }
    },
    "actions":[
      {
        "publishSummaryToCscc":{

        }
      }
    ]
  }
}

Per scoprire di più sulle opzioni di scansione disponibili, consulta Ispezione dello spazio di archiviazione e dei database per l'individuazione di dati sensibili.

Dati BigQuery

Per analizzare la tua tabella BigQuery, copia il seguente JSON e incollalo nel campo Corpo della richiesta.

Sostituisci PROJECT_ID, BIGQUERY_DATASET_NAME e BIGQUERY_TABLE_NAME con l'ID progetto e i nomi delle tabelle e del set di dati BigQuery.

{
  "inspectJob":
  {
    "storageConfig":
    {
      "bigQueryOptions":
      {
        "tableReference":
        {
          "projectId": "PROJECT_ID",
          "datasetId": "BIGQUERY_DATASET_NAME",
          "tableId": "BIGQUERY_TABLE_NAME"
        }
      }
    },
    "inspectConfig":
    {
      "infoTypes":
      [
        {
          "name": "EMAIL_ADDRESS"
        },
        {
          "name": "PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name": "PHONE_NUMBER"
        }
      ],
      "includeQuote": true,
      "minLikelihood": "UNLIKELY",
      "limits":
      {
        "maxFindingsPerRequest": 100
      }
    },
    "actions":
    [
      {
        "publishSummaryToCscc":
        {
        }
      }
    ]
  }
}

Per scoprire di più sulle opzioni di scansione disponibili, consulta Ispezione dello spazio di archiviazione e dei database per l'individuazione di dati sensibili.

Passaggio 3: esegui la richiesta per avviare il job di ispezione

Dopo aver configurato il job seguendo i passaggi precedenti, fai clic su Esegui per inviare la richiesta. Se la richiesta ha esito positivo, sotto la richiesta viene visualizzata una risposta con un codice di operazione riuscita e un oggetto JSON che indica lo stato del job di Sensitive Data Protection che hai creato.

Controlla lo stato dell'analisi di ispezione di Sensitive Data Protection

La risposta alla richiesta di scansione include l'ID job del job di scansione di ispezione come chiave "name" e lo stato attuale del job di ispezione come chiave "state". Subito dopo aver inviato la richiesta, lo stato del job è "PENDING".

Dopo l'invio della richiesta, la scansione dei contenuti inizia immediatamente.

Per controllare lo stato del job di ispezione:

  1. Vai a Explorer API nella pagina di riferimento per il metodo dlpJobs.get facendo clic sul seguente pulsante:

    Apri Explorer API

  2. Nella casella nome, digita il nome del job dalla risposta JSON alla richiesta di scansione nel seguente formato:
    projects/PROJECT_ID/dlpJobs/JOB_ID
    L'ID job è nel formato i-1234567890123456789.
  3. Per inviare la richiesta, fai clic su Esegui.

Se la chiave "state" dell'oggetto JSON di risposta indica che il job è "DONE", il job di ispezione è stato completato.

Per visualizzare il resto del codice JSON della risposta, scorri la pagina verso il basso. In "result" > "infoTypeStats", ogni tipo di informazione elencato deve avere un valore "count" corrispondente. In caso contrario, assicurati di aver inserito correttamente il JSON e che il percorso o la posizione dei dati sia corretta.

Al termine del job di ispezione, puoi passare alla sezione successiva di questa guida per visualizzare i risultati della scansione in Security Command Center.

Esempi di codice: ispezione di un bucket Cloud Storage

Questo esempio mostra come utilizzare l'API DLP per creare un job di ispezione che ispeziona un bucket Cloud Storage e invia i risultati a Security Command Center.

C#

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using System.Collections.Generic;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;

public class InspectStorageWithSCCIntegration
{
    public static DlpJob SendGcsData(
        string projectId,
        string gcsPath,
        Likelihood minLikelihood = Likelihood.Unlikely,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Specify the GCS file to be inspected.
        var storageConfig = new StorageConfig
        {
            CloudStorageOptions = new CloudStorageOptions
            {
                FileSet = new CloudStorageOptions.Types.FileSet
                {
                    Url = gcsPath
                }
            }
        };

        // Specify the type of info to be inspected and construct the inspect config.
        var inspectConfig = new InspectConfig
        {
            InfoTypes =
            {
                infoTypes ?? new InfoType[]
                {
                    new InfoType { Name = "EMAIL_ADDRESS" },
                    new InfoType { Name = "PERSON_NAME" },
                    new InfoType { Name = "LOCATION" },
                    new InfoType { Name = "PHONE_NUMBER" }
                }
            },
            IncludeQuote = true,
            MinLikelihood = minLikelihood,
            Limits = new FindingLimits
            {
                MaxFindingsPerRequest = 100
            }
        };

        // Construct the SCC action which will be performed after inspecting the storage.
        var actions = new Action[]
        {
            new Action
            {
                PublishSummaryToCscc = new Action.Types.PublishSummaryToCscc()
            }
        };

        // Construct the inspect job config using storage config, inspect config and action.
        var inspectJob = new InspectJobConfig
        {
            StorageConfig = storageConfig,
            InspectConfig = inspectConfig,
            Actions = { actions }
        };

        // Construct the request.
        var request = new CreateDlpJobRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectJob = inspectJob
        };

        // Call the API.
        DlpJob response = dlp.CreateDlpJob(request);

        return response;
    }
}

Go

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectGCSFileSendToScc inspects sensitive data in a Google Cloud Storage (GCS) file
// and sends the inspection results to Google Cloud Security Command Center (SCC) for further analysis.
func inspectGCSFileSendToScc(w io.Writer, projectID, gcsPath string) error {
	// projectID := "my-project-id"
	// gcsPath := "gs://" + "your-bucket-name" + "path/to/file.txt"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the GCS file to be inspected.
	cloudStorageOptions := &dlppb.CloudStorageOptions{
		FileSet: &dlppb.CloudStorageOptions_FileSet{
			Url: gcsPath,
		},
	}

	// storageCfg represents the configuration for data inspection in various storage types.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_CloudStorageOptions{
			CloudStorageOptions: cloudStorageOptions,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	infoTypes := []*dlppb.InfoType{
		{Name: "EMAIL_ADDRESS"},
		{Name: "PERSON_NAME"},
		{Name: "LOCATION"},
		{Name: "PHONE_NUMBER"},
	}

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_UNLIKELY

	// The maximum number of findings to report (0 = server maximum).
	findingLimits := &dlppb.InspectConfig_FindingLimits{
		MaxFindingsPerItem: 100,
	}

	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:     infoTypes,
		MinLikelihood: minLikelihood,
		Limits:        findingLimits,
		IncludeQuote:  true,
	}

	// Specify the action that is triggered when the job completes.
	action := &dlppb.Action{
		Action: &dlppb.Action_PublishSummaryToCscc_{
			PublishSummaryToCscc: &dlppb.Action_PublishSummaryToCscc{},
		},
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		StorageConfig: storageConfig,
		InspectConfig: inspectConfig,
		Actions: []*dlppb.Action{
			action,
		},
	}

	// Create the request for the job configured above.
	req := &dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// Send the request.
	resp, err := client.CreateDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "Job created successfully: %v", resp.Name)
	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.CloudStorageOptions;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeStats;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectDataSourceDetails;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StorageConfig;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InspectGcsFileSendToScc {

  private static final int TIMEOUT_MINUTES = 15;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The name of the file in the Google Cloud Storage bucket.
    String gcsPath = "gs://" + "your-bucket-name" + "path/to/file.txt";
    createJobSendToScc(projectId, gcsPath);
  }

  // Creates a DLP Job to scan the sample data stored in a Cloud Storage and save its scan results
  // to Security Command Center.
  public static void createJobSendToScc(String projectId, String gcsPath)
      throws IOException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the GCS file to be inspected.
      CloudStorageOptions cloudStorageOptions =
          CloudStorageOptions.newBuilder()
              .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
              .build();

      StorageConfig storageConfig =
          StorageConfig.newBuilder()
              .setCloudStorageOptions(cloudStorageOptions)
              .build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      // The minimum likelihood required before returning a match.
      // See: https://cloud.google.com/dlp/docs/likelihood
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob response = dlpServiceClient.createDlpJob(createDlpJobRequest);
      // Get the current time.
      long startTime = System.currentTimeMillis();

      // Check if the job state is DONE.
      while (response.getState() != DlpJob.JobState.DONE) {
        // Sleep for 30 second.
        Thread.sleep(30000);

        // Get the updated job status.
        response = dlpServiceClient.getDlpJob(response.getName());

        // Check if the timeout duration has exceeded.
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= TIMEOUT_MINUTES) {
          System.out.printf("Job did not complete within %d minutes.%n", TIMEOUT_MINUTES);
          break;
        }
      }
      // Print the results.
      System.out.println("Job status: " + response.getState());
      System.out.println("Job name: " + response.getName());
      InspectDataSourceDetails.Result result = response.getInspectDetails().getResult();
      System.out.println("Findings: ");
      for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
        System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
        System.out.println("\tCount: " + infoTypeStat.getCount());
      }
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlpClient = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'your-project-id';

// The name of the file in the bucket
// const gcsPath = 'gcs-file-path';

async function inspectGCSSendToScc() {
  // Specify the storage configuration object with GCS URL.
  const storageConfig = {
    cloudStorageOptions: {
      fileSet: {
        url: gcsPath,
      },
    },
  };

  // Construct the info types to look for in the GCS file.
  const infoTypes = [
    {name: 'EMAIL_ADDRESS'},
    {name: 'PERSON_NAME'},
    {name: 'LOCATION'},
    {name: 'PHONE_NUMBER'},
  ];

  // Construct the inspection configuration.
  const inspectConfig = {
    infoTypes,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.UNLIKELY,
    limits: {
      maxFindingsPerItem: 100,
    },
  };

  // Specify the action that is triggered when the job completes.
  const action = {
    publishSummaryToCscc: {},
  };

  // Configure the inspection job we want the service to perform.
  const jobConfig = {
    inspectConfig,
    storageConfig,
    actions: [action],
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: jobConfig,
  };

  // Send the job creation request and process the response.
  const [jobsResponse] = await dlpClient.createDlpJob(request);
  const jobName = jobsResponse.name;

  // Waiting for a maximum of 15 minutes for the job to get complete.
  let job;
  let numOfAttempts = 30;
  while (numOfAttempts > 0) {
    // Fetch DLP Job status
    [job] = await dlpClient.getDlpJob({name: jobName});

    // Check if the job has completed.
    if (job.state === 'DONE') {
      break;
    }
    if (job.state === 'FAILED') {
      console.log('Job Failed, Please check the configuration.');
      return;
    }
    // Sleep for a short duration before checking the job status again.
    await new Promise(resolve => {
      setTimeout(() => resolve(), 30000);
    });
    numOfAttempts -= 1;
  }

  // Print out the results.
  const infoTypeStats = job.inspectDetails.result.infoTypeStats;
  if (infoTypeStats.length > 0) {
    infoTypeStats.forEach(infoTypeStat => {
      console.log(
        `Found ${infoTypeStat.count} instance(s) of infoType ${infoTypeStat.infoType.name}.`
      );
    });
  } else {
    console.log('No findings.');
  }
}
await inspectGCSSendToScc();

PHP

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\DlpJob\JobState;

/**
 * (GCS) Send Cloud DLP scan results to Security Command Center.
 * Using Cloud Data Loss Prevention to scan specific Google Cloud resources and send data to Security Command Center.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $gcsUri            GCS file to be inspected.
 */
function inspect_gcs_send_to_scc(
    // TODO(developer): Replace sample parameters before running the code.
    string $callingProjectId,
    string $gcsUri = 'gs://GOOGLE_STORAGE_BUCKET_NAME/dlp_sample.csv'
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Construct the items to be inspected.
    $cloudStorageOptions = (new CloudStorageOptions())
        ->setFileSet((new FileSet())
            ->setUrl($gcsUri));

    $storageConfig = (new StorageConfig())
        ->setCloudStorageOptions(($cloudStorageOptions));

    // Specify the type of info the inspection will look for.
    $infoTypes = [
        (new InfoType())->setName('EMAIL_ADDRESS'),
        (new InfoType())->setName('PERSON_NAME'),
        (new InfoType())->setName('LOCATION'),
        (new InfoType())->setName('PHONE_NUMBER')
    ];

    // Specify how the content should be inspected.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood(likelihood::UNLIKELY)
        ->setLimits((new FindingLimits())
            ->setMaxFindingsPerRequest(100))
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote(true);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Construct inspect job config to run.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $job = $dlp->createDlpJob($parent, [
        'inspectJob' => $inspectJobConfig
    ]);

    $numOfAttempts = 10;
    do {
        printf('Waiting for job to complete' . PHP_EOL);
        sleep(10);
        $job = $dlp->getDlpJob($job->getName());
        if ($job->getState() == JobState::DONE) {
            break;
        }
        $numOfAttempts--;
    } while ($numOfAttempts > 0);

    // Print finding counts.
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
    switch ($job->getState()) {
        case JobState::DONE:
            $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
            if (count($infoTypeStats) === 0) {
                printf('No findings.' . PHP_EOL);
            } else {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of infoType %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            }
            break;
        case JobState::FAILED:
            printf('Job %s had errors:' . PHP_EOL, $job->getName());
            $errors = $job->getErrors();
            foreach ($errors as $error) {
                var_dump($error->getDetails());
            }
            break;
        case JobState::PENDING:
            printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
            break;
        default:
            printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
    }
}

Python

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import time
from typing import List

import google.cloud.dlp

def inspect_gcs_send_to_scc(
    project: str,
    bucket: str,
    info_types: List[str],
    max_findings: int = 100,
) -> None:
    """
    Uses the Data Loss Prevention API to inspect Google Cloud Storage
    data and send the results to Google Security Command Center.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        bucket: The name of the GCS bucket containing the file, as a string.
        info_types: A list of strings representing infoTypes to inspect for.
            A full list of infoType categories can be fetched from the API.
        max_findings: The maximum number of findings to report; 0 = no maximum.
    """
    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a cloud_storage_options dictionary with the bucket's URL.
    url = f"gs://{bucket}"
    storage_config = {"cloud_storage_options": {"file_set": {"url": url}}}

    # Tell the API where to send a notification when the job is complete.
    actions = [{"publish_summary_to_cscc": {}}]

    # Construct the job definition.
    job = {
        "inspect_config": inspect_config,
        "storage_config": storage_config,
        "actions": actions,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.create_dlp_job(
        request={
            "parent": parent,
            "inspect_job": job,
        }
    )
    print(f"Inspection Job started : {response.name}")

    job_name = response.name

    # Waiting for maximum 15 minutes for the job to get complete.
    no_of_attempts = 30
    while no_of_attempts > 0:
        # Get the DLP job status.
        job = dlp.get_dlp_job(request={"name": job_name})
        # Check if the job has completed.
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.DONE:
            break
        elif job.state == google.cloud.dlp_v2.DlpJob.JobState.FAILED:
            print("Job Failed, Please check the configuration.")
            return

        # Sleep for a short duration before checking the job status again.
        time.sleep(30)
        no_of_attempts -= 1

    # Print out the results.
    print(f"Job name: {job.name}")
    result = job.inspect_details.result
    print("Processed Bytes: ", result.processed_bytes)
    if result.info_type_stats:
        for stats in result.info_type_stats:
            print(f"Info type: {stats.info_type.name}")
            print(f"Count: {stats.count}")
    else:
        print("No findings.")

Esempi di codice: ispeziona una tabella BigQuery

Questo esempio mostra come utilizzare l'API DLP per creare un job di ispezione che ispeziona una tabella BigQuery e invia i risultati a Security Command Center.

C#

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using System.Collections.Generic;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;

public class InspectBigQueryWithSCCIntegration
{
    public static DlpJob SendBigQueryData(
        string projectId,
        Likelihood minLikelihood = Likelihood.Unlikely,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Construct the storage config by providing the table to be inspected.
        var storageConfig = new StorageConfig
        {
            BigQueryOptions = new BigQueryOptions
            {
                TableReference = new BigQueryTable
                {
                    ProjectId = "bigquery-public-data",
                    DatasetId = "usa_names",
                    TableId = "usa_1910_current",
                }
            }
        };

        // Construct the inspect config by specifying the type of info to be inspected.
        var inspectConfig = new InspectConfig
        {
            InfoTypes =
            {
                infoTypes ?? new InfoType[]
                {
                    new InfoType { Name = "EMAIL_ADDRESS" },
                    new InfoType { Name = "PERSON_NAME" }
                }
            },
            IncludeQuote = true,
            MinLikelihood = minLikelihood,
            Limits = new FindingLimits
            {
                MaxFindingsPerRequest = 100
            }
        };

        // Construct the SCC action which will be performed after inspecting the source.
        var actions = new Action[]
        {
            new Action
            {
                PublishSummaryToCscc = new Action.Types.PublishSummaryToCscc()
            }
        };

        // Construct the inspect job config using storage config, inspect config and action.
        var inspectJob = new InspectJobConfig
        {
            StorageConfig = storageConfig,
            InspectConfig = inspectConfig,
            Actions = { actions }
        };

        // Construct the request.
        var request = new CreateDlpJobRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectJob = inspectJob
        };

        // Call the API.
        DlpJob response = dlp.CreateDlpJob(request);

        System.Console.WriteLine($"Job created successfully. Job name: {response.Name}");

        return response;
    }
}

Go

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectBigQuerySendToScc configures the inspection job that instructs Cloud DLP to scan data stored in BigQuery,
// and also instructs Cloud DLP to save its scan results to Security Command Center.
func inspectBigQuerySendToScc(w io.Writer, projectID, bigQueryDatasetId, bigQueryTableId string) error {
	// projectID := "my-project-id"
	// bigQueryDatasetId := "your-project-bigquery-dataset"
	// bigQueryTableId := "your-project-bigquery_table"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the BigQuery table to be inspected.
	tableReference := &dlppb.BigQueryTable{
		ProjectId: projectID,
		DatasetId: bigQueryDatasetId,
		TableId:   bigQueryTableId,
	}

	bigQueryOptions := &dlppb.BigQueryOptions{
		TableReference: tableReference,
	}

	// Specify the type of storage that you have configured.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_BigQueryOptions{
			BigQueryOptions: bigQueryOptions,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types.
	infoTypes := []*dlppb.InfoType{
		{Name: "EMAIL_ADDRESS"},
		{Name: "PERSON_NAME"},
		{Name: "LOCATION"},
		{Name: "PHONE_NUMBER"},
	}

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_UNLIKELY

	// The maximum number of findings to report (0 = server maximum).
	findingLimits := &dlppb.InspectConfig_FindingLimits{
		MaxFindingsPerItem: 100,
	}

	// Specify how the content should be inspected.
	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:     infoTypes,
		MinLikelihood: minLikelihood,
		Limits:        findingLimits,
		IncludeQuote:  true,
	}

	// Specify the action that is triggered when the job completes.
	action := &dlppb.Action{
		Action: &dlppb.Action_PublishSummaryToCscc_{
			PublishSummaryToCscc: &dlppb.Action_PublishSummaryToCscc{},
		},
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		StorageConfig: storageConfig,
		InspectConfig: inspectConfig,
		Actions: []*dlppb.Action{
			action,
		},
	}

	// Create the request for the job configured above.
	req := &dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// Send the request.
	resp, err := client.CreateDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the result
	fmt.Fprintf(w, "Job created successfully: %v", resp.Name)
	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.BigQueryOptions;
import com.google.privacy.dlp.v2.BigQueryTable;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeStats;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectDataSourceDetails;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StorageConfig;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InspectBigQuerySendToScc {

  private static final int TIMEOUT_MINUTES = 15;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The BigQuery dataset id to be used and the reference table name to be inspected.
    String bigQueryDatasetId = "your-project-bigquery-dataset";
    String bigQueryTableId = "your-project-bigquery_table";
    inspectBigQuerySendToScc(projectId, bigQueryDatasetId, bigQueryTableId);
  }

  // Inspects a BigQuery Table to send data to Security Command Center.
  public static void inspectBigQuerySendToScc(
      String projectId, String bigQueryDatasetId, String bigQueryTableId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the BigQuery table to be inspected.
      BigQueryTable tableReference =
          BigQueryTable.newBuilder()
              .setProjectId(projectId)
              .setDatasetId(bigQueryDatasetId)
              .setTableId(bigQueryTableId)
              .build();

      BigQueryOptions bigQueryOptions =
          BigQueryOptions.newBuilder().setTableReference(tableReference).build();

      StorageConfig storageConfig =
          StorageConfig.newBuilder().setBigQueryOptions(bigQueryOptions).build();

      // Specify the type of info the inspection will look for.
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      // The minimum likelihood required before returning a match.
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      // Specify how the content should be inspected.
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob response = dlpServiceClient.createDlpJob(createDlpJobRequest);

      // Get the current time.
      long startTime = System.currentTimeMillis();

      // Check if the job state is DONE.
      while (response.getState() != DlpJob.JobState.DONE) {
        // Sleep for 30 second.
        Thread.sleep(30000);

        // Get the updated job status.
        response = dlpServiceClient.getDlpJob(response.getName());

        // Check if the timeout duration has exceeded.
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= TIMEOUT_MINUTES) {
          System.out.printf("Job did not complete within %d minutes.%n", TIMEOUT_MINUTES);
          break;
        }
      }
      // Print the results.
      System.out.println("Job status: " + response.getState());
      System.out.println("Job name: " + response.getName());
      InspectDataSourceDetails.Result result = response.getInspectDetails().getResult();
      System.out.println("Findings: ");
      for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
        System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
        System.out.println("\tCount: " + infoTypeStat.getCount());
      }
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = "your-project-id";

// The project ID the table is stored under
// This may or (for public datasets) may not equal the calling project ID
// const dataProjectId = 'my-project';

// The ID of the dataset to inspect, e.g. 'my_dataset'
// const datasetId = 'my_dataset';

// The ID of the table to inspect, e.g. 'my_table'
// const tableId = 'my_table';

async function inspectBigQuerySendToScc() {
  // Specify the storage configuration object with big query table.
  const storageItem = {
    bigQueryOptions: {
      tableReference: {
        projectId: dataProjectId,
        datasetId: datasetId,
        tableId: tableId,
      },
    },
  };

  // Specify the type of info the inspection will look for.
  const infoTypes = [
    {name: 'EMAIL_ADDRESS'},
    {name: 'PERSON_NAME'},
    {name: 'LOCATION'},
    {name: 'PHONE_NUMBER'},
  ];

  // Construct inspect configuration.
  const inspectConfig = {
    infoTypes: infoTypes,
    includeQuote: true,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.UNLIKELY,
    limits: {
      maxFindingsPerItem: 100,
    },
  };

  // Specify the action that is triggered when the job completes.
  const action = {
    publishSummaryToCscc: {
      enable: true,
    },
  };

  // Configure the inspection job we want the service to perform.
  const inspectJobConfig = {
    inspectConfig: inspectConfig,
    storageConfig: storageItem,
    actions: [action],
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: inspectJobConfig,
  };

  // Send the job creation request and process the response.
  const [jobsResponse] = await dlp.createDlpJob(request);
  const jobName = jobsResponse.name;

  // Waiting for a maximum of 15 minutes for the job to get complete.
  let job;
  let numOfAttempts = 30;
  while (numOfAttempts > 0) {
    // Fetch DLP Job status
    [job] = await dlp.getDlpJob({name: jobName});

    // Check if the job has completed.
    if (job.state === 'DONE') {
      break;
    }
    if (job.state === 'FAILED') {
      console.log('Job Failed, Please check the configuration.');
      return;
    }
    // Sleep for a short duration before checking the job status again.
    await new Promise(resolve => {
      setTimeout(() => resolve(), 30000);
    });
    numOfAttempts -= 1;
  }

  // Print out the results.
  const infoTypeStats = job.inspectDetails.result.infoTypeStats;
  if (infoTypeStats.length > 0) {
    infoTypeStats.forEach(infoTypeStat => {
      console.log(
        `  Found ${infoTypeStat.count} instance(s) of infoType ${infoTypeStat.infoType.name}.`
      );
    });
  } else {
    console.log('No findings.');
  }
}
await inspectBigQuerySendToScc();

PHP

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\BigQueryOptions;
use Google\Cloud\Dlp\V2\BigQueryTable;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\DlpJob\JobState;

/**
 * (BIGQUERY) Send Cloud DLP scan results to Security Command Center.
 * Using Cloud Data Loss Prevention to scan specific Google Cloud resources and send data to Security Command Center.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $projectId         The ID of the Project.
 * @param string $datasetId         The ID of the BigQuery Dataset.
 * @param string $tableId           The ID of the BigQuery Table to be inspected.
 */
function inspect_bigquery_send_to_scc(
    // TODO(developer): Replace sample parameters before running the code.
    string $callingProjectId,
    string $projectId,
    string $datasetId,
    string $tableId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Construct the items to be inspected.
    $bigqueryTable = (new BigQueryTable())
        ->setProjectId($projectId)
        ->setDatasetId($datasetId)
        ->setTableId($tableId);
    $bigQueryOptions = (new BigQueryOptions())
        ->setTableReference($bigqueryTable);

    $storageConfig = (new StorageConfig())
        ->setBigQueryOptions(($bigQueryOptions));

    // Specify the type of info the inspection will look for.
    $infoTypes = [
        (new InfoType())->setName('EMAIL_ADDRESS'),
        (new InfoType())->setName('PERSON_NAME'),
        (new InfoType())->setName('LOCATION'),
        (new InfoType())->setName('PHONE_NUMBER')
    ];

    // Specify how the content should be inspected.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood(likelihood::UNLIKELY)
        ->setLimits((new FindingLimits())
            ->setMaxFindingsPerRequest(100))
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote(true);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Configure the inspection job we want the service to perform.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $job = $dlp->createDlpJob($parent, [
        'inspectJob' => $inspectJobConfig
    ]);

    $numOfAttempts = 10;
    do {
        printf('Waiting for job to complete' . PHP_EOL);
        sleep(10);
        $job = $dlp->getDlpJob($job->getName());
        if ($job->getState() == JobState::DONE) {
            break;
        }
        $numOfAttempts--;
    } while ($numOfAttempts > 0);

    // Print finding counts.
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
    switch ($job->getState()) {
        case JobState::DONE:
            $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
            if (count($infoTypeStats) === 0) {
                printf('No findings.' . PHP_EOL);
            } else {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of infoType %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            }
            break;
        case JobState::FAILED:
            printf('Job %s had errors:' . PHP_EOL, $job->getName());
            $errors = $job->getErrors();
            foreach ($errors as $error) {
                var_dump($error->getDetails());
            }
            break;
        case JobState::PENDING:
            printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
            break;
        default:
            printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
    }
}

Python

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import time
from typing import List

import google.cloud.dlp

def inspect_bigquery_send_to_scc(
    project: str,
    info_types: List[str],
    max_findings: int = 100,
) -> None:
    """
    Uses the Data Loss Prevention API to inspect public bigquery dataset
    and send the results to Google Security Command Center.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        info_types: A list of strings representing infoTypes to inspect for.
            A full list of infoType categories can be fetched from the API.
        max_findings: The maximum number of findings to report; 0 = no maximum
    """
    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a Cloud Storage Options dictionary with the big query options.
    storage_config = {
        "big_query_options": {
            "table_reference": {
                "project_id": "bigquery-public-data",
                "dataset_id": "usa_names",
                "table_id": "usa_1910_current",
            }
        }
    }

    # Tell the API where to send a notification when the job is complete.
    actions = [{"publish_summary_to_cscc": {}}]

    # Construct the job definition.
    job = {
        "inspect_config": inspect_config,
        "storage_config": storage_config,
        "actions": actions,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.create_dlp_job(
        request={
            "parent": parent,
            "inspect_job": job,
        }
    )
    print(f"Inspection Job started : {response.name}")

    job_name = response.name

    # Waiting for a maximum of 15 minutes for the job to get complete.
    no_of_attempts = 30
    while no_of_attempts > 0:
        # Get the DLP job status.
        job = dlp.get_dlp_job(request={"name": job_name})
        # Check if the job has completed.
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.DONE:
            break
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.FAILED:
            print("Job Failed, Please check the configuration.")
            return

        # Sleep for a short duration before checking the job status again.
        time.sleep(30)
        no_of_attempts -= 1

    # Print out the results.
    print(f"Job name: {job.name}")
    result = job.inspect_details.result
    if result.info_type_stats:
        for stats in result.info_type_stats:
            print(f"Info type: {stats.info_type.name}")
            print(f"Count: {stats.count}")
    else:
        print("No findings.")

Esempi di codice: ispezione di un tipo di Datastore

Questo esempio mostra come utilizzare l'API DLP per creare un job di ispezione che ispeziona un tipo di Datastore e invia i risultati a Security Command Center.

C#

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using System.Collections.Generic;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;

public class InspectDataStoreJobWithSCCIntegration
{
    public static DlpJob SendInspectDatastoreToSCC(
        string projectId,
        string kindName,
        string namespaceId,
        Likelihood minLikelihood = Likelihood.Unlikely,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Specify the Datastore entity to be inspected and construct the storage
        // config. The NamespaceId is to be used for partition entity and the datastore kind defining
        // a data set.
        var storageConfig = new StorageConfig
        {
            DatastoreOptions = new DatastoreOptions
            {
                Kind = new KindExpression { Name = kindName },
                PartitionId = new PartitionId
                {
                    NamespaceId = namespaceId,
                    ProjectId = projectId
                }
            }
        };

        // Specify the type of info to be inspected and construct the inspect config.
        var inspectConfig = new InspectConfig
        {
            InfoTypes =
            {
                infoTypes ?? new InfoType[]
                {
                    new InfoType { Name = "EMAIL_ADDRESS" },
                    new InfoType { Name = "PERSON_NAME" },
                    new InfoType { Name = "LOCATION" },
                    new InfoType { Name = "PHONE_NUMBER" }
                }
            },
            IncludeQuote = true,
            MinLikelihood = minLikelihood,
            Limits = new FindingLimits
            {
                MaxFindingsPerRequest = 100
            }
        };

        // Construct the SCC action which will be performed after inspecting the datastore.
        var actions = new Action[]
        {
            new Action
            {
                PublishSummaryToCscc = new Action.Types.PublishSummaryToCscc()
            }
        };

        // Construct the inspect job config using storage config, inspect config and action.
        var inspectJob = new InspectJobConfig
        {
            StorageConfig = storageConfig,
            InspectConfig = inspectConfig,
            Actions = { actions }
        };

        // Construct the request.
        var request = new CreateDlpJobRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectJob = inspectJob
        };

        // Call the API.
        DlpJob response = dlp.CreateDlpJob(request);

        return response;
    }
}

Go

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectDataStoreSendToScc inspects sensitive data in a Datastore
// and sends the results to Google Cloud Security Command Center (SCC).
func inspectDataStoreSendToScc(w io.Writer, projectID, datastoreNamespace, datastoreKind string) error {
	// projectID := "my-project-id"
	// datastoreNamespace := "your-datastore-namespace"
	// datastoreKind := "your-datastore-kind"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the Datastore entity to be inspected.
	partitionId := &dlppb.PartitionId{
		ProjectId:   projectID,
		NamespaceId: datastoreNamespace,
	}

	// kindExpr represents an expression specifying a kind or range of kinds for data inspection in DLP.
	kindExpression := &dlppb.KindExpression{
		Name: datastoreKind,
	}

	// Specify datastoreOptions so that It holds the configuration options for inspecting data in
	// Google Cloud Datastore.
	datastoreOptions := &dlppb.DatastoreOptions{
		PartitionId: partitionId,
		Kind:        kindExpression,
	}

	// Specify the storageConfig to represents the configuration settings for inspecting data
	// in different storage types, such as BigQuery and Cloud Storage.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_DatastoreOptions{
			DatastoreOptions: datastoreOptions,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	infoTypes := []*dlppb.InfoType{
		{Name: "EMAIL_ADDRESS"},
		{Name: "PERSON_NAME"},
		{Name: "LOCATION"},
		{Name: "PHONE_NUMBER"},
	}

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_UNLIKELY

	// The maximum number of findings to report (0 = server maximum).
	findingLimits := &dlppb.InspectConfig_FindingLimits{
		MaxFindingsPerItem: 100,
	}

	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:     infoTypes,
		MinLikelihood: minLikelihood,
		Limits:        findingLimits,
		IncludeQuote:  true,
	}

	// Specify the action that is triggered when the job completes.
	action := &dlppb.Action{
		Action: &dlppb.Action_PublishSummaryToCscc_{
			PublishSummaryToCscc: &dlppb.Action_PublishSummaryToCscc{},
		},
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		StorageConfig: storageConfig,
		InspectConfig: inspectConfig,
		Actions: []*dlppb.Action{
			action,
		},
	}

	// Create the request for the job configured above.
	req := &dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// Send the request.
	resp, err := client.CreateDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the result
	fmt.Fprintf(w, "Job created successfully: %v", resp.Name)
	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DatastoreOptions;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeStats;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectDataSourceDetails;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.KindExpression;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.PartitionId;
import com.google.privacy.dlp.v2.StorageConfig;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InspectDatastoreSendToScc {

  private static final int TIMEOUT_MINUTES = 15;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The namespace specifier to be used for the partition entity.
    String datastoreNamespace = "your-datastore-namespace";
    // The datastore kind defining a data set.
    String datastoreKind = "your-datastore-kind";
    inspectDatastoreSendToScc(projectId, datastoreNamespace, datastoreKind);
  }

  // Creates a DLP Job to scan the sample data stored in a DataStore table and save its scan results
  // to Security Command Center.
  public static void inspectDatastoreSendToScc(
      String projectId, String datastoreNamespace, String datastoreKind)
      throws IOException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the Datastore entity to be inspected.
      PartitionId partitionId =
          PartitionId.newBuilder()
              .setProjectId(projectId)
              .setNamespaceId(datastoreNamespace)
              .build();

      KindExpression kindExpression = KindExpression.newBuilder().setName(datastoreKind).build();

      DatastoreOptions datastoreOptions =
          DatastoreOptions.newBuilder().setKind(kindExpression).setPartitionId(partitionId).build();

      StorageConfig storageConfig =
          StorageConfig.newBuilder().setDatastoreOptions(datastoreOptions).build();

      // Specify the type of info the inspection will look for.
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      // The minimum likelihood required before returning a match.
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      // Specify how the content should be inspected.
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob response = dlpServiceClient.createDlpJob(createDlpJobRequest);
      // Get the current time.
      long startTime = System.currentTimeMillis();

      // Check if the job state is DONE.
      while (response.getState() != DlpJob.JobState.DONE) {
        // Sleep for 30 second.
        Thread.sleep(30000);

        // Get the updated job status.
        response = dlpServiceClient.getDlpJob(response.getName());

        // Check if the timeout duration has exceeded.
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= TIMEOUT_MINUTES) {
          System.out.printf("Job did not complete within %d minutes.%n", TIMEOUT_MINUTES);
          break;
        }
      }
      // Print the results.
      System.out.println("Job status: " + response.getState());
      System.out.println("Job name: " + response.getName());
      InspectDataSourceDetails.Result result = response.getInspectDetails().getResult();
      System.out.println("Findings: ");
      for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
        System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
        System.out.println("\tCount: " + infoTypeStat.getCount());
      }
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = "your-project-id";

// Datastore namespace
// const datastoreNamespace = 'datastore-namespace';

// Datastore kind
// const datastoreKind = 'datastore-kind';

async function inspectDatastoreSendToScc() {
  // Specify the storage configuration object with datastore.
  const storageConfig = {
    datastoreOptions: {
      kind: {
        name: datastoreKind,
      },
      partitionId: {
        projectId: projectId,
        namespaceId: datastoreNamespace,
      },
    },
  };

  // Construct the info types to look for in the datastore.
  const infoTypes = [
    {name: 'EMAIL_ADDRESS'},
    {name: 'PERSON_NAME'},
    {name: 'LOCATION'},
    {name: 'PHONE_NUMBER'},
  ];

  // Construct the inspection configuration.
  const inspectConfig = {
    infoTypes: infoTypes,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.UNLIKELY,
    limits: {
      maxFindingsPerItem: 100,
    },
    includeQuote: true,
  };

  // Specify the action that is triggered when the job completes
  const action = {
    publishSummaryToCscc: {enable: true},
  };

  // Configure the inspection job we want the service to perform.
  const inspectJobConfig = {
    inspectConfig: inspectConfig,
    storageConfig: storageConfig,
    actions: [action],
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: inspectJobConfig,
  };

  // Send the job creation request and process the response.
  const [jobsResponse] = await dlp.createDlpJob(request);
  const jobName = jobsResponse.name;

  // Waiting for a maximum of 15 minutes for the job to get complete.
  let job;
  let numOfAttempts = 30;
  while (numOfAttempts > 0) {
    // Fetch DLP Job status
    [job] = await dlp.getDlpJob({name: jobName});

    // Check if the job has completed.
    if (job.state === 'DONE') {
      break;
    }
    if (job.state === 'FAILED') {
      console.log('Job Failed, Please check the configuration.');
      return;
    }
    // Sleep for a short duration before checking the job status again.
    await new Promise(resolve => {
      setTimeout(() => resolve(), 30000);
    });
    numOfAttempts -= 1;
  }

  // Print out the results.
  const infoTypeStats = job.inspectDetails.result.infoTypeStats;
  if (infoTypeStats.length > 0) {
    infoTypeStats.forEach(infoTypeStat => {
      console.log(
        `Found ${infoTypeStat.count} instance(s) of infoType ${infoTypeStat.infoType.name}.`
      );
    });
  } else {
    console.log('No findings.');
  }
}
await inspectDatastoreSendToScc();

PHP

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\DatastoreOptions;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\KindExpression;
use Google\Cloud\Dlp\V2\PartitionId;
use Google\Cloud\Dlp\V2\DlpJob\JobState;

/**
 * (DATASTORE) Send Cloud DLP scan results to Security Command Center.
 * Using Cloud Data Loss Prevention to scan specific Google Cloud resources and send data to Security Command Center.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $kindName          Datastore kind name to be inspected.
 * @param string $namespaceId       Namespace Id to be inspected.
 */
function inspect_datastore_send_to_scc(
    string $callingProjectId,
    string $kindName,
    string $namespaceId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Construct the items to be inspected.
    $datastoreOptions = (new DatastoreOptions())
        ->setKind((new KindExpression())
            ->setName($kindName))
        ->setPartitionId((new PartitionId())
            ->setNamespaceId($namespaceId)
            ->setProjectId($callingProjectId));

    $storageConfig = (new StorageConfig())
        ->setDatastoreOptions(($datastoreOptions));

    // Specify the type of info the inspection will look for.
    $infoTypes = [
        (new InfoType())->setName('EMAIL_ADDRESS'),
        (new InfoType())->setName('PERSON_NAME'),
        (new InfoType())->setName('LOCATION'),
        (new InfoType())->setName('PHONE_NUMBER')
    ];

    // Specify how the content should be inspected.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood(likelihood::UNLIKELY)
        ->setLimits((new FindingLimits())
            ->setMaxFindingsPerRequest(100))
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote(true);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Construct inspect job config to run.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $job = $dlp->createDlpJob($parent, [
        'inspectJob' => $inspectJobConfig
    ]);

    $numOfAttempts = 10;
    do {
        printf('Waiting for job to complete' . PHP_EOL);
        sleep(10);
        $job = $dlp->getDlpJob($job->getName());
        if ($job->getState() == JobState::DONE) {
            break;
        }
        $numOfAttempts--;
    } while ($numOfAttempts > 0);

    // Print finding counts.
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
    switch ($job->getState()) {
        case JobState::DONE:
            $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
            if (count($infoTypeStats) === 0) {
                printf('No findings.' . PHP_EOL);
            } else {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of infoType %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            }
            break;
        case JobState::FAILED:
            printf('Job %s had errors:' . PHP_EOL, $job->getName());
            $errors = $job->getErrors();
            foreach ($errors as $error) {
                var_dump($error->getDetails());
            }
            break;
        case JobState::PENDING:
            printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
            break;
        default:
            printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
    }
}

Python

Per scoprire come installare e utilizzare la libreria client per Sensitive Data Protection, consulta Librerie client di Sensitive Data Protection.

Per eseguire l'autenticazione in Sensitive Data Protection, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import time
from typing import List

import google.cloud.dlp

def inspect_datastore_send_to_scc(
    project: str,
    datastore_project: str,
    kind: str,
    info_types: List[str],
    namespace_id: str = None,
    max_findings: int = 100,
) -> None:
    """
    Uses the Data Loss Prevention API to inspect Datastore data and
    send the results to Google Security Command Center.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        datastore_project: The Google Cloud project id of the target Datastore.
        kind: The kind of the Datastore entity to inspect, e.g. 'Person'.
        info_types: A list of strings representing infoTypes to inspect for.
            A full list of infoType categories can be fetched from the API.
        namespace_id: The namespace of the Datastore document, if applicable.
        max_findings: The maximum number of findings to report; 0 = no maximum

    """
    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a cloud_storage_options dictionary with datastore options.
    storage_config = {
        "datastore_options": {
            "partition_id": {
                "project_id": datastore_project,
                "namespace_id": namespace_id,
            },
            "kind": {"name": kind},
        }
    }

    # Tell the API where to send a notification when the job is complete.
    actions = [{"publish_summary_to_cscc": {}}]

    # Construct the job definition.
    job = {
        "inspect_config": inspect_config,
        "storage_config": storage_config,
        "actions": actions,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API
    response = dlp.create_dlp_job(
        request={
            "parent": parent,
            "inspect_job": job,
        }
    )
    print(f"Inspection Job started : {response.name}")

    job_name = response.name

    # Waiting for a maximum of 15 minutes for the job to get complete.
    no_of_attempts = 30
    while no_of_attempts > 0:
        # Get the DLP job status.
        job = dlp.get_dlp_job(request={"name": job_name})
        # Check if the job has completed.
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.DONE:
            break
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.FAILED:
            print("Job Failed, Please check the configuration.")
            return

        # Sleep for a short duration before checking the job status again.
        time.sleep(30)
        no_of_attempts -= 1

    # Print out the results.
    print(f"Job name: {job.name}")
    result = job.inspect_details.result
    if result.info_type_stats:
        for stats in result.info_type_stats:
            print(f"Info type: {stats.info_type.name}")
            print(f"Count: {stats.count}")
    else:
        print("No findings.")

Visualizza i risultati dell'analisi di Sensitive Data Protection in Security Command Center

Poiché hai chiesto a Sensitive Data Protection di inviare i risultati del job di ispezione a Security Command Center, ora puoi visualizzare i risultati del job di ispezione in Security Command Center:

  1. Nella console Google Cloud, vai alla pagina Risultati di Security Command Center.

    Vai a Risultati

  2. Seleziona l'organizzazione per la quale hai abilitato Security Command Center.
  3. Nel campo Editor query, inserisci quanto segue per eseguire una query sui risultati di Sensitive Data Protection.

    state="ACTIVE"
    AND NOT mute="MUTED"
    AND (parent_display_name="Sensitive Data Protection" OR parent_display_name="Cloud Data Loss Prevention")
    

    Per ulteriori informazioni sull'Editor query, consulta Modificare una query dei risultati nella console Google Cloud.

    Gli eventuali risultati inviati da Sensitive Data Protection vengono visualizzati nell'elenco dei risultati. Nell'elenco sono inclusi tutti i risultati di Sensitive Data Protection, che possono includere quelli dei job di ispezione e delle operazioni di rilevamento (profilazione dei dati).

Le istruzioni fornite in questa guida attivano solo alcuni dei rilevatori integrati di Sensitive Data Protection.

Esegui la pulizia

Per evitare che al tuo account Google Cloud vengano addebitati costi relativi alle risorse utilizzate in questo argomento:

Elimina il progetto

Il modo più semplice per eliminare la fatturazione è eliminare il progetto creato seguendo le istruzioni fornite in questo argomento.

  1. Nella console Google Cloud, vai alla pagina Gestisci risorse.

    Vai a Gestisci risorse

  2. Nell'elenco dei progetti, seleziona il progetto che vuoi eliminare, quindi fai clic su Elimina.
  3. Nella finestra di dialogo, digita l'ID del progetto e fai clic su Chiudi per eliminare il progetto.

Se elimini il progetto utilizzando questo metodo, sono stati eliminati anche il job di Sensitive Data Protection e il bucket Cloud Storage che hai creato. Non è necessario seguire le istruzioni riportate nelle sezioni seguenti.

Elimina il job di Sensitive Data Protection

Se hai scansionato i tuoi dati, devi eliminare solo il job di ispezione che hai creato:

  1. Vai a Explorer API nella pagina di riferimento per il metodo dlpJobs.delete facendo clic sul seguente pulsante:

    Apri Explorer API

  2. Nella casella nome, digita il nome del job dalla risposta JSON alla richiesta di scansione, che ha il seguente formato:
    projects/PROJECT_ID/dlpJobs/JOB_ID
    L'ID job è nel formato i-1234567890123456789.

Se hai creato job di ispezione aggiuntivi o se vuoi assicurarti di aver eliminato correttamente il job, puoi elencare tutti i job esistenti:

  1. Vai a Explorer API nella pagina di riferimento per il metodo dlpJobs.list facendo clic sul seguente pulsante:

    Apri Explorer API

  2. Nella casella parent, digita l'identificatore del progetto nel seguente formato:
    projects/PROJECT_ID
  3. Fai clic su Execute (Esegui).

Se nella risposta non sono elencati job, hai eliminato tutti i job. Se i job sono elencati nella risposta, ripeti la relativa procedura di eliminazione.

Elimina il bucket Cloud Storage

Se hai creato un nuovo bucket Cloud Storage per contenere dati di esempio, elimina il bucket:

  1. Apri il browser Cloud Storage.

    Apri Cloud Storage

  2. Nel browser Cloud Storage, seleziona la casella di controllo accanto al nome del bucket che hai creato, quindi fai clic su Elimina.

Passaggi successivi