יצירת מזהה מילון גדול בהתאמה אישית

במאמר הזה מוסבר איך ליצור ולבנות מחדש מילונים גדולים בהתאמה אישית. הוא גם כולל כמה תרחישי שגיאה.

מתי כדאי לבחור במילון מותאם אישית גדול ולא במילון מותאם אישית רגיל

גלאים רגילים של מילונים בהתאמה אישית מתאימים אם יש לכם עשרות אלפי מילים או ביטויים רגישים שאתם רוצים לסרוק בתוכן. אם יש לכם יותר מונחים או שרשימת המונחים משתנה לעיתים קרובות, כדאי ליצור מילון גדול בהתאמה אישית, שיכול לתמוך בעשרות מיליוני מונחים.

מה ההבדל בין מילונים גדולים בהתאמה אישית לבין סוגי מידע אישי אחרים בהתאמה אישית

מילונים גדולים בהתאמה אישית שונים מסוגי מידע מותאמים אישית אחרים בכך שכל מילון גדול בהתאמה אישית מורכב משני רכיבים:

  • רשימה של ביטויים שאתם יוצרים ומגדירים. הרשימה מאוחסנת כקובץ טקסט ב-Cloud Storage או כעמודה בטבלה ב-BigQuery.
  • קובצי המילון, שנוצרים על ידי Sensitive Data Protection ומאוחסנים ב-Cloud Storage. קובצי המילון מורכבים מעותק של רשימת המונחים שלכם וממסנני בלום, שעוזרים בחיפוש ובהתאמה.

יצירת מילון גדול בהתאמה אישית

בקטע הזה מוסבר איך ליצור, לערוך ולבנות מחדש מילון גדול בהתאמה אישית.

יצירת רשימת מונחים

יוצרים רשימה שמכילה את כל המילים והביטויים שאתם רוצים שהגלאי החדש של infoType יחפש. מבצעים אחת מהפעולות הבאות:

  • מציבים קובץ טקסט עם כל מילה או ביטוי בשורה נפרדת בקטגוריה של Cloud Storage.
  • מגדירים עמודה אחת בטבלה ב-BigQuery כמכיל של המילים והביטויים. כל רשומה צריכה להיות בשורה נפרדת בעמודה. אפשר להשתמש בטבלה קיימת ב-BigQuery, כל עוד כל המילים והביטויים במילון נמצאים בעמודה אחת.

יכול להיות שרשימת המונחים תהיה גדולה מדי לעיבוד ב-Sensitive Data Protection. אם מופיעה הודעת שגיאה, עיינו בקטע פתרון בעיות בהמשך המאמר.

יצירת infoType מאוחסן

אחרי שיוצרים את רשימת המונחים, משתמשים ב-Sensitive Data Protection כדי ליצור מילון:

המסוף

  1. בקטגוריה של Cloud Storage, יוצרים תיקייה חדשה שבה Sensitive Data Protection יאחסן את המילון שנוצר.

    ‫Sensitive Data Protection יוצר תיקיות שמכילות את קובצי המילון במיקום שציינתם.

  2. נכנסים לדף Create infoType במסוף Google Cloud .

    כניסה לדף Create infoType

  3. בקטע סוג, בוחרים באפשרות מילון גדול בהתאמה אישית.

  4. בשדה InfoType ID, מזינים מזהה ל-infoType השמור.

    המזהה הזה ישמש אתכם להגדרת משימות הבדיקה והסרת פרטי הזיהוי. אפשר להשתמש באותיות, במספרים, במקפים ובקווים תחתונים בשם.

  5. בשדה InfoType display name, מזינים שם לסוג המידע השמור.

    אפשר להשתמש ברווחים ובסימני פיסוק בשם.

  6. בשדה Description, מזינים תיאור של מה שסוג המידע השמור מזהה.

  7. בקטע סוג אחסון, בוחרים את המיקום של רשימת המונחים:

    • ‫BigQuery: מזינים את מזהה הפרויקט, מזהה מערך הנתונים ומזהה הטבלה. בשדה Field name, מזינים את מזהה העמודה. אפשר להגדיר עמודה אחת לכל היותר מהטבלה.
    • ‫Google Cloud Storage: מזינים את הנתיב לקובץ.
  8. בשדה Output bucket or folder, מזינים את המיקום ב-Cloud Storage של התיקייה שיצרתם בשלב 1.

  9. לוחצים על יצירה.

מופיע סיכום של ה-infoType ששמור. כשהמילון נוצר וסוג המידע המאוחסן החדש מוכן לשימוש, הסטטוס של סוג המידע הוא Ready.

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class CreateStoredInfoTypes
{
    public static StoredInfoType Create(
        string projectId,
        string outputPath,
        string storedInfoTypeId)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Construct the stored infotype config by specifying the public table and 
        // cloud storage output path.
        var storedInfoTypeConfig = new StoredInfoTypeConfig
        {
            DisplayName = "Github Usernames",
            Description = "Dictionary of Github usernames used in commits.",
            LargeCustomDictionary = new LargeCustomDictionaryConfig
            {
                BigQueryField = new BigQueryField
                {
                    Table = new BigQueryTable
                    {
                        DatasetId = "samples",
                        ProjectId = "bigquery-public-data",
                        TableId = "github_nested"
                    },
                    Field = new FieldId
                    {
                        Name = "actor"
                    }
                },
                OutputPath = new CloudStoragePath
                {
                    Path = outputPath
                }
            },
        };

        // Construct the request.
        var request = new CreateStoredInfoTypeRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            Config = storedInfoTypeConfig,
            StoredInfoTypeId = storedInfoTypeId
        };

        // Call the API.
        StoredInfoType response = dlp.CreateStoredInfoType(request);

        // Inspect the response.
        Console.WriteLine($"Created the stored infotype at path: {response.Name}");

        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

// createStoredInfoType creates a custom stored info type based on your input data.
func createStoredInfoType(w io.Writer, projectID, outputPath string) error {
	// projectId := "my-project-id"
	// outputPath := "gs://" + "your-bucket-name" + "path/to/directory"

	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 name you want to give the dictionary.
	displayName := "Github Usernames"

	// Specify a description of the dictionary.
	description := "Dictionary of GitHub usernames used in commits"

	// Specify the path to the location in a Cloud Storage
	// bucket to store the created dictionary.
	cloudStoragePath := &dlppb.CloudStoragePath{
		Path: outputPath,
	}

	// Specify your term list is stored in BigQuery.
	bigQueryField := &dlppb.BigQueryField{
		Table: &dlppb.BigQueryTable{
			ProjectId: "bigquery-public-data",
			DatasetId: "samples",
			TableId:   "github_nested",
		},
		Field: &dlppb.FieldId{
			Name: "actor",
		},
	}

	// Specify the configuration of the large custom dictionary.
	largeCustomDictionaryConfig := &dlppb.LargeCustomDictionaryConfig{
		OutputPath: cloudStoragePath,
		Source: &dlppb.LargeCustomDictionaryConfig_BigQueryField{
			BigQueryField: bigQueryField,
		},
	}

	// Specify the configuration for stored infoType.
	storedInfoTypeConfig := &dlppb.StoredInfoTypeConfig{
		DisplayName: displayName,
		Description: description,
		Type: &dlppb.StoredInfoTypeConfig_LargeCustomDictionary{
			LargeCustomDictionary: largeCustomDictionaryConfig,
		},
	}

	// Combine configurations into a request for the service.
	req := &dlppb.CreateStoredInfoTypeRequest{
		Parent:           fmt.Sprintf("projects/%s/locations/global", projectID),
		Config:           storedInfoTypeConfig,
		StoredInfoTypeId: "github-usernames",
	}

	// Send the request and receive response from the service.
	resp, err := client.CreateStoredInfoType(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "output: %v", resp.Name)
	return nil

}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.BigQueryField;
import com.google.privacy.dlp.v2.BigQueryTable;
import com.google.privacy.dlp.v2.CloudStoragePath;
import com.google.privacy.dlp.v2.CreateStoredInfoTypeRequest;
import com.google.privacy.dlp.v2.FieldId;
import com.google.privacy.dlp.v2.LargeCustomDictionaryConfig;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StoredInfoType;
import com.google.privacy.dlp.v2.StoredInfoTypeConfig;
import java.io.IOException;

public class CreateStoredInfoType {

  public static void main(String[] args) throws IOException {
    // 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 path to the location in a GCS bucket to store the created dictionary.
    String outputPath = "gs://" + "your-bucket-name" + "path/to/directory";
    createStoredInfoType(projectId, outputPath);
  }

  // Creates a custom stored info type that contains GitHub usernames used in commits.
  public static void createStoredInfoType(String projectId, String outputPath)
      throws IOException {
    try (DlpServiceClient dlp = DlpServiceClient.create()) {

      // Optionally set a display name and a description.
      String displayName = "GitHub usernames";
      String description = "Dictionary of GitHub usernames used in commits";

      // The output path where the custom dictionary containing the GitHub usernames will be stored.
      CloudStoragePath cloudStoragePath =
          CloudStoragePath.newBuilder()
              .setPath(outputPath)
              .build();

      // The reference to the table containing the GitHub usernames.
      BigQueryTable table = BigQueryTable.newBuilder()
              .setProjectId("bigquery-public-data")
              .setDatasetId("samples")
              .setTableId("github_nested")
              .build();

      // The reference to the BigQuery field that contains the GitHub usernames.
      BigQueryField bigQueryField = BigQueryField.newBuilder()
              .setTable(table)
              .setField(FieldId.newBuilder().setName("actor").build())
              .build();

      LargeCustomDictionaryConfig largeCustomDictionaryConfig =
          LargeCustomDictionaryConfig.newBuilder()
              .setOutputPath(cloudStoragePath)
              .setBigQueryField(bigQueryField)
              .build();

      StoredInfoTypeConfig storedInfoTypeConfig = StoredInfoTypeConfig.newBuilder()
              .setDisplayName(displayName)
              .setDescription(description)
              .setLargeCustomDictionary(largeCustomDictionaryConfig)
              .build();

      // Combine configurations into a request for the service.
      CreateStoredInfoTypeRequest createStoredInfoType = CreateStoredInfoTypeRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setConfig(storedInfoTypeConfig)
              .setStoredInfoTypeId("github-usernames")
              .build();

      // Send the request and receive response from the service.
      StoredInfoType response = dlp.createStoredInfoType(createStoredInfoType);

      // Print the results.
      System.out.println("Created Stored InfoType: " + response.getName());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Import the required libraries
const dlp = require('@google-cloud/dlp');

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

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

// The identifier for the stored infoType
// const infoTypeId = 'github-usernames';

// The path to the location in a Cloud Storage bucket to store the created dictionary
// const outputPath = 'cloud-bucket-path';

// 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';

// Field ID to be used for constructing dictionary
// const fieldName = 'field_name';

async function createStoredInfoType() {
  // The name you want to give the dictionary.
  const displayName = 'GitHub usernames';
  // A description of the dictionary.
  const description = 'Dictionary of GitHub usernames used in commits';

  // Specify configuration for the large custom dictionary
  const largeCustomDictionaryConfig = {
    outputPath: {
      path: outputPath,
    },
    bigQueryField: {
      table: {
        datasetId: datasetId,
        projectId: dataProjectId,
        tableId: tableId,
      },
      field: {
        name: fieldName,
      },
    },
  };

  // Stored infoType configuration that uses large custom dictionary.
  const storedInfoTypeConfig = {
    displayName: displayName,
    description: description,
    largeCustomDictionary: largeCustomDictionaryConfig,
  };

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

  // Send the job creation request and process the response.
  const [response] = await dlpClient.createStoredInfoType(request);

  // Print results
  console.log(`InfoType stored successfully: ${response.name}`);
}
await createStoredInfoType();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


use Google\Cloud\Dlp\V2\BigQueryField;
use Google\Cloud\Dlp\V2\BigQueryTable;
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStoragePath;
use Google\Cloud\Dlp\V2\CreateStoredInfoTypeRequest;
use Google\Cloud\Dlp\V2\FieldId;
use Google\Cloud\Dlp\V2\LargeCustomDictionaryConfig;
use Google\Cloud\Dlp\V2\StoredInfoTypeConfig;

/**
 * Create a stored infoType.
 *
 * @param string $callingProjectId  The Google Cloud Project ID to run the API call under.
 * @param string $outputgcsPath     The path to the location in a Cloud Storage bucket to store the created dictionary.
 * @param string $storedInfoTypeId  The name of the custom stored info type.
 * @param string $displayName       The human-readable name to give the stored infoType.
 * @param string $description       A description for the stored infoType to be created.
 */
function create_stored_infotype(
    string $callingProjectId,
    string $outputgcsPath,
    string $storedInfoTypeId,
    string $displayName,
    string $description
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // The reference to the table containing the GitHub usernames.
    // The reference to the BigQuery field that contains the GitHub usernames.
    // Note: we have used public data
    $bigQueryField = (new BigQueryField())
        ->setTable((new BigQueryTable())
            ->setDatasetId('samples')
            ->setProjectId('bigquery-public-data')
            ->setTableId('github_nested'))
        ->setField((new FieldId())
            ->setName('actor'));

    $largeCustomDictionaryConfig = (new LargeCustomDictionaryConfig())
        // The output path where the custom dictionary containing the GitHub usernames will be stored.
        ->setOutputPath((new CloudStoragePath())
            ->setPath($outputgcsPath))
        ->setBigQueryField($bigQueryField);

    // Configure the StoredInfoType we want the service to perform.
    $storedInfoTypeConfig = (new StoredInfoTypeConfig())
        ->setDisplayName($displayName)
        ->setDescription($description)
        ->setLargeCustomDictionary($largeCustomDictionaryConfig);

    // Send the stored infoType creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $createStoredInfoTypeRequest = (new CreateStoredInfoTypeRequest())
        ->setParent($parent)
        ->setConfig($storedInfoTypeConfig)
        ->setStoredInfoTypeId($storedInfoTypeId);
    $response = $dlp->createStoredInfoType($createStoredInfoTypeRequest);

    // Print results.
    printf('Successfully created Stored InfoType : %s', $response->getName());
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def create_stored_infotype(
    project: str,
    stored_info_type_id: str,
    output_bucket_name: str,
) -> None:
    """Uses the Data Loss Prevention API to create stored infoType.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        stored_info_type_id: The identifier for large custom dictionary.
        output_bucket_name: The name of the bucket in Google Cloud Storage
            that would store the created dictionary.
    """

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

    # Construct the stored infoType Configuration dictionary. This example creates
    # a stored infoType from a term list stored in a publicly available BigQuery
    # database (bigquery-public-data.samples.github_nested).
    # The database contains all GitHub usernames used in commits.
    stored_info_type_config = {
        "display_name": "GitHub usernames",
        "description": "Dictionary of GitHub usernames used in commits",
        "large_custom_dictionary": {
            "output_path": {"path": f"gs://{output_bucket_name}"},
            # We can either use bigquery field or gcs file as a term list input option.
            "big_query_field": {
                "table": {
                    "project_id": "bigquery-public-data",
                    "dataset_id": "samples",
                    "table_id": "github_nested",
                },
                "field": {"name": "actor"},
            },
        },
    }

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

    # Call the API.
    response = dlp.create_stored_info_type(
        request={
            "parent": parent,
            "config": stored_info_type_config,
            "stored_info_type_id": stored_info_type_id,
        }
    )

    # Print the result
    print(f"Created Stored InfoType: {response.name}")

REST

  1. יוצרים תיקייה חדשה למילון בקטגוריה של Cloud Storage. ‫Sensitive Data Protection יוצר תיקיות שמכילות את קובצי המילון במיקום שציינתם.
  2. יוצרים את המילון באמצעות ה-method‏ storedInfoTypes.create. ה-method‏ create מקבל את הפרמטרים הבאים:
    • אובייקט StoredInfoTypeConfig, שמכיל את ההגדרה של ה-infoType השמור. הוא כולל:
      • ‫description: תיאור המילון.
      • ‫displayName: השם שרוצים לתת למילון.
      • LargeCustomDictionaryConfig: מכיל את ההגדרות של המילון הגדול בהתאמה אישית. הוא כולל:
        • ‫BigQueryField: מצוין אם רשימת המונחים מאוחסנת ב-BigQuery. כולל הפניה לטבלה שבה הרשימה מאוחסנת, וגם את השדה שמכיל כל ביטוי במילון.
        • CloudStorageFileSet: מצוין אם רשימת המונחים מאוחסנת ב-Cloud Storage. כולל את כתובת ה-URL למיקום המקור ב-Cloud Storage, בפורמט הבא: "gs://[PATH_TO_GS]". יש תמיכה בתווים כלליים לחיפוש.
        • ‫outputPath: הנתיב למיקום בקטגוריה של Cloud Storage שבו יאוחסן המילון שנוצר.
    • ‫storedInfoTypeId: המזהה של ה-infoType השמור. המזהה הזה משמש כדי להפנות ל-infoType השמור כשבונים אותו מחדש, מוחקים אותו או משתמשים בו במשימת בדיקה או במשימת הסרת פרטי זיהוי. אם משאירים את השדה הזה ריק, המערכת יוצרת מזהה בשבילכם.

בהמשך מוצגת דוגמה ל-JSON שכאשר שולחים אותו ל-method‏ storedInfoTypes.create, הוא יוצר stored infoType חדש – באופן ספציפי, גלאי מילון גדול בהתאמה אישית. בדוגמה הזו נוצר stored infoType מרשימת מונחים שמאוחסנת במסד נתונים שזמין לכולם ב-BigQuery‏ (bigquery-public-data.samples.github_nested). מסד הנתונים מכיל את כל שמות המשתמשים ב-GitHub שנעשה בהם שימוש ב-commits. נתיב הפלט של המילון שנוצר מוגדר לקטגוריה של Cloud Storage בשם dlptesting, וה-infoType שמאוחסן נקרא github-usernames.

קלט מסוג JSON

POST https://dlp.googleapis.com/v2/projects/PROJECT_ID/storedInfoTypes

{
  "config":{
    "displayName":"GitHub usernames",
    "description":"Dictionary of GitHub usernames used in commits",
    "largeCustomDictionary":{
      "outputPath":{
        "path":"gs://[PATH_TO_GS]"
      },
      "bigQueryField":{
        "table":{
          "datasetId":"samples",
          "projectId":"bigquery-public-data",
          "tableId":"github_nested"
        }
      }
    }
  },
  "storedInfoTypeId":"github-usernames"
}

בנייה מחדש של המילון

כדי לעדכן את המילון, קודם מעדכנים את רשימת המונחים במקור, ואז מנחים את Sensitive Data Protection לבנות מחדש את ה-infoType השמור.

  1. מעדכנים את רשימת מונחי המקור הקיימת ב-Cloud Storage או ב-BigQuery.

    מוסיפים, מסירים או משנים את המונחים או הביטויים לפי הצורך.

  2. יוצרים גרסה חדשה של ה-infoType המאוחסן על ידי "בנייה מחדש" שלו באמצעות מסוף Google Cloud או באמצעות השיטה storedInfoTypes.patch.

    בנייה מחדש יוצרת גרסה חדשה של המילון, שמחליפה את המילון הישן.

כשבונים מחדש גרסה חדשה של infoType מאוחסן, הגרסה הישנה נמחקת. בזמן ש-Sensitive Data Protection מעדכן את ה-infoType המאוחסן, הסטטוס שלו הוא pending. במהלך הזמן הזה, הגרסה הישנה של ה-infoType המאוחסן עדיין קיימת. כל הסריקות שתריצו בזמן שסוג המידע המאוחסן נמצא במצב המתנה יופעלו באמצעות הגרסה הישנה של סוג המידע המאוחסן.

כדי לבנות מחדש את ה-infoType השמור:

המסוף

  1. מעדכנים ושומרים את רשימת המונחים ב-Cloud Storage או ב-BigQuery.
  2. במסוף Google Cloud , נכנסים לרשימה של סוגי המידע השמורים.

    מעבר אל stored infoTypes

  3. לוחצים על המזהה של ה-infoType השמור שרוצים לעדכן.

  4. בדף InfoType details, לוחצים על Rebuild data.

‫Sensitive Data Protection בונה מחדש את ה-infoType השמור עם השינויים שביצעתם ברשימת המונחים של המקור. כשהסטטוס של ה-infoType השמור הוא "Ready", אפשר להשתמש בו. כל התבניות או הטריגרים של המשימות שמשתמשים ב-infoType המאוחסן ישתמשו באופן אוטומטי בגרסה שנבנתה מחדש.

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Cloud.Dlp.V2;
using Google.Protobuf.WellKnownTypes;

public class UpdateStoredInfoTypes
{
    public static StoredInfoType Update(
        string gcsFileUri,
        string storedInfoTypePath,
        string outputPath)
    {
        // Instantiate the client.
        var dlp = DlpServiceClient.Create();

        // Construct the stored infotype config. Here, we will change the source from bigquery table to GCS file.
        var storedConfig = new StoredInfoTypeConfig
        {
            LargeCustomDictionary = new LargeCustomDictionaryConfig
            {
                CloudStorageFileSet = new CloudStorageFileSet
                {
                    Url = gcsFileUri
                },
                OutputPath = new CloudStoragePath
                {
                    Path = outputPath
                }
            }
        };

        // Construct the request using the stored config by specifying the update mask object
        // which represent the path of field to be updated.
        var request = new UpdateStoredInfoTypeRequest
        {
            Config = storedConfig,
            Name = storedInfoTypePath,
            UpdateMask = new FieldMask
            {
                Paths =
                {
                    "large_custom_dictionary.cloud_storage_file_set.url"
                }
            }
        };

        // Call the API.
        StoredInfoType response = dlp.UpdateStoredInfoType(request);

        // Inspect the result.
        Console.WriteLine(response);
        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateStoredInfoType uses the Data Loss Prevention API to update stored infoType
// detector by changing the source term list from one stored in Bigquery
// to one stored in Cloud Storage.
func updateStoredInfoType(w io.Writer, projectID, gcsUri, fileSetUrl, infoTypeId string) error {
	// projectId := "your-project-id"
	// gcsUri := "gs://" + "your-bucket-name" + "/path/to/your/file.txt"
	// fileSetUrl := "your-cloud-storage-file-set"
	// infoTypeId := "your-stored-info-type-id"

	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()

	// Set path in Cloud Storage.
	cloudStoragePath := &dlppb.CloudStoragePath{
		Path: gcsUri,
	}
	cloudStorageFileSet := &dlppb.CloudStorageFileSet{
		Url: fileSetUrl,
	}

	// Configuration for a custom dictionary created from a data source of any size
	largeCustomDictionaryConfig := &dlppb.LargeCustomDictionaryConfig{
		OutputPath: cloudStoragePath,
		Source: &dlppb.LargeCustomDictionaryConfig_CloudStorageFileSet{
			CloudStorageFileSet: cloudStorageFileSet,
		},
	}

	// Set configuration for stored infoTypes.
	storedInfoTypeConfig := &dlppb.StoredInfoTypeConfig{
		Type: &dlppb.StoredInfoTypeConfig_LargeCustomDictionary{
			LargeCustomDictionary: largeCustomDictionaryConfig,
		},
	}

	// Set mask to control which fields get updated.
	fieldMask := &fieldmaskpb.FieldMask{
		Paths: []string{"large_custom_dictionary.cloud_storage_file_set.url"},
	}
	// Construct the job creation request to be sent by the client.
	req := &dlppb.UpdateStoredInfoTypeRequest{
		Name:       fmt.Sprint("projects/" + projectID + "/storedInfoTypes/" + infoTypeId),
		Config:     storedInfoTypeConfig,
		UpdateMask: fieldMask,
	}

	// Use the client to send the API request.
	resp, err := client.UpdateStoredInfoType(ctx, req)
	if err != nil {
		return err
	}

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

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CloudStorageFileSet;
import com.google.privacy.dlp.v2.CloudStoragePath;
import com.google.privacy.dlp.v2.LargeCustomDictionaryConfig;
import com.google.privacy.dlp.v2.StoredInfoType;
import com.google.privacy.dlp.v2.StoredInfoTypeConfig;
import com.google.privacy.dlp.v2.StoredInfoTypeName;
import com.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class UpdateStoredInfoType {
  public static void main(String[] args) throws IOException {
    // 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 path to file in GCS bucket that holds a collection of words and phrases to be searched by
    // the new infoType detector.
    String filePath = "gs://" + "your-bucket-name" + "/path/to/your/file.txt";
    // The path to the location in a GCS bucket to store the created dictionary.
    String outputPath = "your-cloud-storage-file-set";
    // The name of the stored InfoType which is to be updated.
    String infoTypeId = "your-stored-info-type-id";
    updateStoredInfoType(projectId, filePath, outputPath, infoTypeId);
  }

  // Update the stored info type rebuilding the Custom dictionary.
  public static void updateStoredInfoType(
      String projectId, String filePath, String outputPath, String infoTypeId) throws IOException {
    // 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 dlp = DlpServiceClient.create()) {
      // Set path in Cloud Storage.
      CloudStoragePath cloudStoragePath = CloudStoragePath.newBuilder().setPath(outputPath).build();
      CloudStorageFileSet cloudStorageFileSet =
          CloudStorageFileSet.newBuilder().setUrl(filePath).build();

      // Configuration for a custom dictionary created from a data source of any size
      LargeCustomDictionaryConfig largeCustomDictionaryConfig =
          LargeCustomDictionaryConfig.newBuilder()
              .setOutputPath(cloudStoragePath)
              .setCloudStorageFileSet(cloudStorageFileSet)
              .build();

      // Set configuration for stored infoTypes.
      StoredInfoTypeConfig storedInfoTypeConfig =
          StoredInfoTypeConfig.newBuilder()
              .setLargeCustomDictionary(largeCustomDictionaryConfig)
              .build();

      // Set mask to control which fields get updated.
      // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
      FieldMask fieldMask =
          FieldMask.newBuilder()
              .addPaths("large_custom_dictionary.cloud_storage_file_set.url")
              .build();

      // Construct the job creation request to be sent by the client.
      UpdateStoredInfoTypeRequest updateStoredInfoTypeRequest =
          UpdateStoredInfoTypeRequest.newBuilder()
              .setName(
                  StoredInfoTypeName.ofProjectStoredInfoTypeName(projectId, infoTypeId).toString())
              .setConfig(storedInfoTypeConfig)
              .setUpdateMask(fieldMask)
              .build();

      // Send the job creation request and process the response.
      StoredInfoType response = dlp.updateStoredInfoType(updateStoredInfoTypeRequest);

      // Print the results.
      System.out.println("Updated stored InfoType successfully: " + response.getName());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Import the required libraries
const dlp = require('@google-cloud/dlp');

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

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

// The identifier for the stored infoType
// const infoTypeId = 'github-usernames';

// The path to the location in a Cloud Storage bucket to store the created dictionary
// const outputPath = 'cloud-bucket-path';

// Path of file containing term list
// const cloudStorageFileSet = 'gs://[PATH_TO_GS]';

async function updateStoredInfoType() {
  // Specify configuration of the large custom dictionary including cloudStorageFileSet and outputPath
  const largeCustomDictionaryConfig = {
    outputPath: {
      path: outputPath,
    },
    cloudStorageFileSet: {
      url: fileSetUrl,
    },
  };

  // Construct the job creation request to be sent by the client.
  const updateStoredInfoTypeRequest = {
    name: `projects/${projectId}/storedInfoTypes/${infoTypeId}`,
    config: {
      largeCustomDictionary: largeCustomDictionaryConfig,
    },
    updateMask: {
      paths: ['large_custom_dictionary.cloud_storage_file_set.url'],
    },
  };

  // Send the job creation request and process the response.
  const [response] = await dlpClient.updateStoredInfoType(
    updateStoredInfoTypeRequest
  );

  // Print the results.
  console.log(`InfoType updated successfully: ${JSON.stringify(response)}`);
}
await updateStoredInfoType();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageFileSet;
use Google\Cloud\Dlp\V2\CloudStoragePath;
use Google\Cloud\Dlp\V2\LargeCustomDictionaryConfig;
use Google\Cloud\Dlp\V2\StoredInfoTypeConfig;
use Google\Cloud\Dlp\V2\UpdateStoredInfoTypeRequest;
use Google\Protobuf\FieldMask;

/**
 * Rebuild/Update the stored infoType.
 *
 * @param string $callingProjectId  The Google Cloud Project ID to run the API call under.
 * @param string $gcsPath           The path to file in GCS bucket that holds a collection of words and phrases to be searched by the new infoType detector.
 * @param string $outputgcsPath     The path to the location in a Cloud Storage bucket to store the created dictionary.
 * @param string $storedInfoTypeId  The name of the stored InfoType which is to be updated.
 *
 */
function update_stored_infotype(
    string $callingProjectId,
    string $gcsPath,
    string $outputgcsPath,
    string $storedInfoTypeId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Set path in Cloud Storage.
    $cloudStorageFileSet = (new CloudStorageFileSet())
        ->setUrl($gcsPath);

    // Configuration for a custom dictionary created from a data source of any size
    $largeCustomDictionaryConfig = (new LargeCustomDictionaryConfig())
        ->setOutputPath((new CloudStoragePath())
            ->setPath($outputgcsPath))
        ->setCloudStorageFileSet($cloudStorageFileSet);

    // Set configuration for stored infoTypes.
    $storedInfoTypeConfig = (new StoredInfoTypeConfig())
        ->setLargeCustomDictionary($largeCustomDictionaryConfig);

    // Send the stored infoType creation request and process the response.

    $name = "projects/$callingProjectId/locations/global/storedInfoTypes/" . $storedInfoTypeId;
    // Set mask to control which fields get updated.
    // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
    $fieldMask = (new FieldMask())
        ->setPaths([
            'large_custom_dictionary.cloud_storage_file_set.url'
        ]);

    // Run request
    $updateStoredInfoTypeRequest = (new UpdateStoredInfoTypeRequest())
        ->setName($name)
        ->setConfig($storedInfoTypeConfig)
        ->setUpdateMask($fieldMask);
    $response = $dlp->updateStoredInfoType($updateStoredInfoTypeRequest);

    // Print results
    printf('Successfully update Stored InforType : %s' . PHP_EOL, $response->getName());
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def update_stored_infotype(
    project: str,
    stored_info_type_id: str,
    gcs_input_file_path: str,
    output_bucket_name: str,
) -> None:
    """Uses the Data Loss Prevention API to update stored infoType
    detector by changing the source term list from one stored in Bigquery
    to one stored in Cloud Storage.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        stored_info_type_id: The identifier of stored infoType which is to
            be updated.
        gcs_input_file_path: The url in the format <bucket>/<path_to_file>
            for the location of the source term list.
        output_bucket_name: The name of the bucket in Google Cloud Storage
            where large dictionary is stored.
    """

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

    # Construct the stored infoType configuration dictionary.
    stored_info_type_config = {
        "large_custom_dictionary": {
            "output_path": {"path": f"gs://{output_bucket_name}"},
            "cloud_storage_file_set": {"url": f"gs://{gcs_input_file_path}"},
        }
    }

    # Set mask to control which fields get updated. For more details, refer
    # https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
    # for constructing the field mask paths.
    field_mask = {"paths": ["large_custom_dictionary.cloud_storage_file_set.url"]}

    # Convert the stored infoType id into a full resource id.
    stored_info_type_name = (
        f"projects/{project}/locations/global/storedInfoTypes/{stored_info_type_id}"
    )

    # Call the API.
    response = dlp.update_stored_info_type(
        request={
            "name": stored_info_type_name,
            "config": stored_info_type_config,
            "update_mask": field_mask,
        }
    )

    # Print the result
    print(f"Updated stored infoType successfully: {response.name}")

REST

עדכון רשימת המונחים

אם אתם מעדכנים רק את רשימת המונחים במילון המותאם אישית הגדול, בקשת ה-storedInfoTypes.patch צריכה לכלול רק את השדה name. מציינים את השם המלא של המשאב של ה-infoType השמור שרוצים לבנות מחדש.

התבניות הבאות מייצגות ערכים חוקיים בשדה name:

  • organizations/ORGANIZATION_ID/storedInfoTypes/STORED_INFOTYPE_ID
  • projects/PROJECT_ID/storedInfoTypes/STORED_INFOTYPE_ID

מחליפים את STORED_INFOTYPE_ID במזהה של ה-infoType המאוחסן שרוצים לבנות מחדש.

אם אתם לא יודעים את המזהה של ה-infoType השמור, אתם יכולים להפעיל את ה-method‏ storedInfoTypes.list כדי לראות רשימה של כל ה-infoTypes השמורים הנוכחיים.

דוגמה

PATCH https://dlp.googleapis.com/v2/projects/PROJECT_ID/storedInfoTypes/STORED_INFOTYPE_ID

במקרה כזה, לא צריך גוף בקשה.

החלפת רשימת המונחים של המקור

אתם יכולים לשנות את רשימת המונחים של המקור של infoType מאוחסן, מרשימה שמאוחסנת ב-BigQuery לרשימה שמאוחסנת ב-Cloud Storage. משתמשים ב-method‏ storedInfoTypes.patch, אבל כוללים אובייקט CloudStorageFileSet ב-LargeCustomDictionaryConfig במקום שבו השתמשתם באובייקט BigQueryField קודם לכן. אחר כך מגדירים את הפרמטר updateMask לפרמטר של סוג המידע המאוחסן שיצרתם מחדש, בפורמט FieldMask. לדוגמה, ב-JSON הבא, הפרמטר updateMask מציין שכתובת ה-URL של הנתיב ב-Cloud Storage עודכנה (large_custom_dictionary.cloud_storage_file_set.url):

דוגמה

PATCH https://dlp.googleapis.com/v2/projects/PROJECT_ID/storedInfoTypes/github-usernames

{
  "config":{
    "largeCustomDictionary":{
      "cloudStorageFileSet":{
        "url":"gs://[BUCKET_NAME]/[PATH_TO_FILE]"
      }
    }
  },
  "updateMask":"large_custom_dictionary.cloud_storage_file_set.url"
}

באופן דומה, אתם יכולים להחליף את רשימת המונחים ששמורה בטבלה ב-BigQuery ברשימה ששמורה בקטגוריה של Cloud Storage.

סריקת תוכן באמצעות גלאי מילון גדול בהתאמה אישית

סריקת תוכן באמצעות גלאי מילון מותאם אישית גדול דומה לסריקת תוכן באמצעות כל גלאי infoType מותאם אישית אחר.

ההנחה היא שכבר יש לכם infoType מאוחסן. מידע נוסף מופיע בקטע יצירת stored infoType שבדף הזה.

המסוף

אפשר להחיל גלאי של מילון גדול בהתאמה אישית כשמבצעים את הפעולות הבאות:

בקטע Configure detection בדף, בסעיף המשנה InfoTypes, אתם יכולים לציין את ה-infoType של המילון הגדול בהתאמה אישית.

  1. לוחצים על Manage infoTypes.
  2. בחלונית InfoTypes, לוחצים על הכרטיסייה Custom.
  3. לוחצים על Add custom infoType.
  4. בחלונית Add custom infoType:

    1. בשדה Type, בוחרים באפשרות Stored infoType.
    2. בשדה InfoType, מזינים שם ל-infoType בהתאמה אישית. אפשר להשתמש באותיות, במספרים ובקווים תחתונים.
    3. בשדה Likelihood, בוחרים את רמת הסבירות שרוצים להקצות כברירת מחדל לכל הממצאים שתואמים לסוג ה-infoType המותאם אישית. אפשר גם לכוונן את רמת הסבירות של ממצאים ספציפיים באמצעות כללי הרחבה (Hotword).

      אם לא מציינים ערך ברירת מחדל, רמת הסבירות שמוגדרת כברירת מחדל היא VERY_LIKELY. מידע נוסף זמין במאמר סבירות להתאמה.

    4. בקטע Sensitivity, בוחרים את רמת הרגישות שרוצים להקצות לכל הממצאים שתואמים לסוג ה-infoType המותאם אישית הזה. אם לא תציינו ערך, רמות הרגישות של הממצאים האלה יוגדרו כ-HIGH.

      ציוני רגישות משמשים בפרופילי נתונים. כשמגדירים פרופיל לנתונים, Sensitive Data Protection משתמש בציוני הרגישות של ה-infoTypes כדי לחשב את רמת הרגישות.

    5. בשדה Stored infoType name, בוחרים את ה-infoType השמור שעליו רוצים לבסס את ה-infoType החדש בהתאמה אישית.

    6. לוחצים על Done כדי לסגור את החלונית Add custom infoType.

  5. אופציונלי: בכרטיסייה Built-in, עורכים את הבחירה של סוגי המידע המובנים.

  6. לוחצים על Done כדי לסגור את החלונית InfoTypes.

    ה-infoType בהתאמה אישית נוסף לרשימת ה-infoTypes ש-Sensitive Data Protection סורק. עם זאת, הבחירה הזו לא סופית עד ששומרים את המשימה, הטריגר למשימה, התבנית או הגדרת הסריקה.

  7. כשמסיימים ליצור או לערוך את ההגדרה, לוחצים על שמירה.

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class InspectDataWithStoredInfotypes
{
    public static InspectContentResponse Inspect(
        string projectId,
        string storedInfotypePath,
        string text,
        InfoType infoType = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Construct the infotype if null.
        var infotype = infoType ?? new InfoType { Name = "GITHUB_LOGINS" };

        // Construct the inspect config using stored infotype.
        var inspectConfig = new InspectConfig
        {
            CustomInfoTypes =
            {
                new CustomInfoType
                {
                    InfoType = infotype,
                    StoredType = new StoredType { Name = storedInfotypePath }
                }
            },
            IncludeQuote = true
        };

        // Construct the request using inspect config.
        var request = new InspectContentRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectConfig = inspectConfig,
            Item = new ContentItem { Value = text }
        };

        // Call the API.
        InspectContentResponse response = dlp.InspectContent(request);

        // Inspect the results.
        var findings = response.Result.Findings;
        Console.WriteLine($"Findings: {findings.Count}");
        foreach (var f in findings)
        {
            Console.WriteLine("\tQuote: " + f.Quote);
            Console.WriteLine("\tInfo type: " + f.InfoType.Name);
            Console.WriteLine("\tLikelihood: " + f.Likelihood);
        }

        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

// inspectWithStoredInfotype inspects the given text using the specified stored infoType detector.
func inspectWithStoredInfotype(w io.Writer, projectID, infoTypeId, textToDeidentify string) error {
	// projectId := "your-project-id"
	// infoTypeId := "your-info-type-id"
	// textToDeidentify := "This commit was made by kewin2010"

	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 content to be inspected.
	contentItem := &dlppb.ContentItem{
		DataItem: &dlppb.ContentItem_Value{
			Value: textToDeidentify,
		},
	}

	// Specify the info type the inspection will look for.
	infoType := &dlppb.InfoType{
		Name: "GITHUB_LOGINS",
	}

	// Specify the stored info type the inspection will look for.
	storedType := &dlppb.StoredType{
		Name: infoTypeId,
	}

	customInfoType := &dlppb.CustomInfoType{
		InfoType: infoType,
		Type: &dlppb.CustomInfoType_StoredType{
			StoredType: storedType,
		},
	}

	// Specify how the content should be inspected.
	inspectConfig := &dlppb.InspectConfig{
		CustomInfoTypes: []*dlppb.CustomInfoType{
			customInfoType,
		},
		IncludeQuote: true,
	}

	// Construct the Inspect request to be sent by the client.
	req := &dlppb.InspectContentRequest{
		Parent:        fmt.Sprintf("projects/%s/locations/global", projectID),
		InspectConfig: inspectConfig,
		Item:          contentItem,
	}

	// Use the client to send the API request.
	resp, err := client.InspectContent(ctx, req)
	if err != nil {
		return err
	}

	// Process the results.
	fmt.Fprintf(w, "Findings: %d\n", len(resp.Result.Findings))
	for _, f := range resp.Result.Findings {
		fmt.Fprintf(w, "\tQuote: %s\n", f.Quote)
		fmt.Fprintf(w, "\tInfo type: %s\n", f.InfoType.Name)
		fmt.Fprintf(w, "\tLikelihood: %s\n", f.Likelihood)
	}
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.CustomInfoType;
import com.google.privacy.dlp.v2.Finding;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectContentRequest;
import com.google.privacy.dlp.v2.InspectContentResponse;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.ProjectStoredInfoTypeName;
import com.google.privacy.dlp.v2.StoredType;
import java.io.IOException;

public class InspectWithStoredInfotype {

  public static void main(String[] args) throws IOException {
    // 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 sample assumes that you have an existing stored infoType.
    // To create a stored InfoType refer:
    // https://cloud.google.com/dlp/docs/creating-stored-infotypes#create-storedinfotye 
    String storedInfoTypeId = "your-info-type-id";
    // The string to de-identify.
    String textToInspect =
        "My phone number is (223) 456-7890 and my email address is gary@example.com.";
    inspectWithStoredInfotype(projectId, storedInfoTypeId, textToInspect);
  }

  //  Inspects the given text using the specified stored infoType detector.
  public static void inspectWithStoredInfotype(
      String projectId, String storedInfoTypeId, String textToInspect) throws IOException {
    // 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 dlp = DlpServiceClient.create()) {

      // Specify the content to be inspected.
      ContentItem contentItem = ContentItem.newBuilder().setValue(textToInspect).build();

      InfoType infoType = InfoType.newBuilder().setName("STORED_TYPE").build();

      // Reference to the existing StoredInfoType to inspect the data.
      StoredType storedType = StoredType.newBuilder()
              .setName(ProjectStoredInfoTypeName.of(projectId, storedInfoTypeId).toString())
              .build();

      CustomInfoType customInfoType =
          CustomInfoType.newBuilder().setInfoType(infoType).setStoredType(storedType).build();

      // Construct the configuration for the Inspect request.
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addCustomInfoTypes(customInfoType)
              .setIncludeQuote(true)
              .build();

      // Construct the Inspect request to be sent by the client.
      InspectContentRequest inspectContentRequest =
          InspectContentRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectConfig(inspectConfig)
              .setItem(contentItem)
              .build();

      // Use the client to send the API request.
      InspectContentResponse response = dlp.inspectContent(inspectContentRequest);

      // Parse the response and process results.
      System.out.println("Findings: " + "" + response.getResult().getFindingsCount());
      for (Finding f : response.getResult().getFindingsList()) {
        System.out.println("\tQuote: " + f.getQuote());
        System.out.println("\tInfoType: " + f.getInfoType().getName());
        System.out.println("\tLikelihood: " + f.getLikelihood() + "\n");
      }
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// 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 custom info-type id created and stored in the bucket.
// const infoTypeId = 'your-info-type-id';

// The string to inspect.
// const string = 'My phone number is (223) 456-7890 and my email address is gary@example.com.';

async function inspectWithStoredInfotype() {
  // Reference to the existing StoredInfoType to inspect the data.
  const customInfoType = {
    infoType: {
      name: 'GITHUB_LOGINS',
    },
    storedType: {
      name: infoTypeId,
    },
  };

  // Construct the configuration for the Inspect request.
  const inspectConfig = {
    customInfoTypes: [customInfoType],
    includeQuote: true,
  };

  // Construct the Inspect request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectConfig: inspectConfig,
    item: {
      value: string,
    },
  };
  // Run request
  const [response] = await dlp.inspectContent(request);

  // Print Findings
  const findings = response.result.findings;
  if (findings.length > 0) {
    console.log(`Findings: ${findings.length}\n`);
    findings.forEach(finding => {
      console.log(`InfoType: ${finding.infoType.name}`);
      console.log(`\tQuote: ${finding.quote}`);
      console.log(`\tLikelihood: ${finding.likelihood} \n`);
    });
  } else {
    console.log('No findings.');
  }
}
await inspectWithStoredInfotype();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\CustomInfoType;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectContentRequest;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\StoredType;

/**
 * Inspect with stored infoType.
 * Scan content using a large custom dictionary detector.
 *
 * @param string $projectId             The Google Cloud Project ID to run the API call under.
 * @param string $storedInfoTypeName    The name of the stored infotype whose This value must be in the format
 * projects/projectName/(locations/locationId)/storedInfoTypes/storedInfoTypeName.
 * @param string $textToInspect         The string to inspect.
 */
function inspect_with_stored_infotype(
    string $projectId,
    string $storedInfoTypeName,
    string $textToInspect
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    $parent = "projects/$projectId/locations/global";

    // Specify the content to be inspected.
    $item = (new ContentItem())
        ->setValue($textToInspect);

    // Reference to the existing StoredInfoType to inspect the data.
    $customInfoType = (new CustomInfoType())
        ->setInfoType((new InfoType())
            ->setName('STORED_TYPE'))
        ->setStoredType((new StoredType())
            ->setName($storedInfoTypeName));

    // Construct the configuration for the Inspect request.
    $inspectConfig = (new InspectConfig())
        ->setCustomInfoTypes([$customInfoType])
        ->setIncludeQuote(true);

    // Run request.
    $inspectContentRequest = (new InspectContentRequest())
        ->setParent($parent)
        ->setInspectConfig($inspectConfig)
        ->setItem($item);
    $response = $dlp->inspectContent($inspectContentRequest);

    // Print the results.
    $findings = $response->getResult()->getFindings();
    if (count($findings) == 0) {
        printf('No findings.' . PHP_EOL);
    } else {
        printf('Findings:' . PHP_EOL);
        foreach ($findings as $finding) {
            printf('  Quote: %s' . PHP_EOL, $finding->getQuote());
            printf('  Info type: %s' . PHP_EOL, $finding->getInfoType()->getName());
            printf('  Likelihood: %s' . PHP_EOL, Likelihood::name($finding->getLikelihood()));
        }
    }
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def inspect_with_stored_infotype(
    project: str,
    stored_info_type_id: str,
    content_string: str,
) -> None:
    """Uses the Data Loss Prevention API to inspect/scan content using stored
    infoType.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        content_string: The string to inspect.
        stored_info_type_id: The identifier of stored infoType used to inspect.
    """

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

    # Convert stored infoType id into full resource id
    stored_type_name = f"projects/{project}/storedInfoTypes/{stored_info_type_id}"

    # Construct a custom info type dictionary using stored infoType.
    custom_info_types = [
        {
            "info_type": {"name": "STORED_TYPE"},
            "stored_type": {
                "name": stored_type_name,
            },
        }
    ]

    # Construct the inspection configuration dictionary.
    inspect_config = {
        "custom_info_types": custom_info_types,
        "include_quote": True,
    }

    # Construct the `item` to be inspected using stored infoType.
    item = {"value": content_string}

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

    # Call the API.
    response = dlp.inspect_content(
        request={
            "parent": parent,
            "inspect_config": inspect_config,
            "item": item,
        }
    )

    # Print out the results.
    if response.result.findings:
        for finding in response.result.findings:
            print(f"Quote: {finding.quote}")
            print(f"Info type: {finding.info_type.name}")
            print(f"Likelihood: {finding.likelihood}")
    else:
        print("No findings.")

REST

כששולחים את הדוגמה הבאה ל-method‏ content.inspect, היא סורקת את הטקסט שצוין באמצעות הגלאי של stored infoType שצוין. הפרמטר infoType נדרש כי לכל סוגי המידע המותאמים אישית חייב להיות שם שלא מתנגש עם סוגי מידע מובנים או עם סוגי מידע מותאמים אישית אחרים. הפרמטר storedType מכיל את נתיב המשאב המלא של ה-infoType השמור.

קלט מסוג JSON

POST https://dlp.googleapis.com/v2/projects/PROJECT_ID/content:inspect

{
  "inspectConfig":{
    "customInfoTypes":[
      {
        "infoType":{
          "name":"GITHUB_LOGINS"
        },
        "storedType":{
          "name":"projects/PROJECT_ID/storedInfoTypes/github-logins"
        }
      }
    ]
  },
  "item":{
    "value":"The commit was made by githubuser."
  }
}

פתרון בעיות במקרה של שגיאות

אם אתם מקבלים הודעת שגיאה כשאתם מנסים ליצור stored infoType מרשימת מונחים שמאוחסנת ב-Cloud Storage, יכול להיות שהסיבה היא:

  • הגעתם למגבלה המקסימלית של סוגי מידע מאוחסנים. יש כמה פתרונות עקיפים, בהתאם לבעיה:
    • אם הגעתם למגבלה העליונה של קובץ קלט יחיד ב-Cloud Storage‏ (200MB), נסו לפצל את הקובץ לכמה קבצים. אתם יכולים להשתמש בכמה קבצים כדי ליצור מילון אחד בהתאמה אישית, כל עוד הגודל הכולל של כל הקבצים לא עולה על 1GB.
    • המגבלות של BigQuery שונות מאלה של Cloud Storage. כדאי להעביר את המונחים לטבלה ב-BigQuery. הגודל המקסימלי של עמודת מילון בהתאמה אישית ב-BigQuery הוא 1GB, ומספר השורות המקסימלי הוא 5,000,000.
    • אם קובץ רשימת המונחים חורג מכל המגבלות שחלות על רשימות של מונחי מקור, צריך לפצל את קובץ רשימת המונחים לכמה קבצים וליצור מילון לכל קובץ. אחר כך, יוצרים משימת סריקה נפרדת לכל מילון.
  • באחד או יותר מהמונחים אין לפחות אות אחת או מספר אחד. ‫Sensitive Data Protection לא יכול לסרוק מונחים שמורכבים רק מרווחים או מסמלים. הוא חייב להכיל לפחות אות אחת או מספר אחד. בדקו את רשימת המונחים שלכם כדי לראות אם יש בה מונחים כאלה, ואז תקנו או מחקו אותם.
  • רשימת המונחים מכילה ביטוי עם יותר מדי "רכיבים". רכיב בהקשר הזה הוא רצף שמכיל רק אותיות, רק מספרים או רק תווים שהם לא אותיות או מספרים, כמו רווחים או סמלים. בדקו את רשימת המונחים שלכם כדי לראות אם יש בה מונחים כאלה, ואז תקנו או מחקו אותם.
  • לסוכן השירות של Sensitive Data Protection אין גישה לנתוני המקור של המילון או לקטגוריה של Cloud Storage שבה מאוחסנים קובצי המילון. כדי לפתור את הבעיה, צריך לתת לסוכן השירות של Sensitive Data Protection את התפקיד "אדמין של Storage"‏ (roles/storage.admin) או את התפקידים "בעלים של נתוני BigQuery"‏ (roles/bigquery.dataOwner) ו"משתמש במשימות של BigQuery"‏ (roles/bigquery.jobUser).

סקירה כללית על ממשקי API

אם אתם יוצרים גלאי מילון גדול בהתאמה אישית, אתם צריכים ליצור סוג מידע מאוחסן.

סוג infoType מאוחסן מיוצג ב-Sensitive Data Protection באמצעות האובייקט StoredInfoType. הוא מורכב מהאובייקטים הקשורים הבאים:

  • StoredInfoTypeVersion כולל את התאריך והשעה של היצירה, ואת חמש הודעות השגיאה האחרונות שהתרחשו כשהגרסה הנוכחית נוצרה.

    • ‫StoredInfoTypeConfig מכיל את ההגדרה של infoType השמור, כולל השם והתיאור שלו. אם המילון המותאם אישית גדול, הערך של type צריך להיות LargeCustomDictionaryConfig.

      • LargeCustomDictionaryConfig מציין את שני הדברים הבאים:
        • המיקום ב-Cloud Storage או ב-BigQuery שבו מאוחסנת רשימת הביטויים.
        • המיקום ב-Cloud Storage שבו יאוחסנו קובצי המילון שנוצרו.
    • השדה StoredInfoTypeState מכיל את המצב של הגרסה העדכנית ביותר ושל כל הגרסאות בהמתנה של ה-infoType השמור. פרטי המצב כוללים מידע על סוג המידע השמור, למשל אם הוא נוצר מחדש, מוכן לשימוש או לא תקין.

פרטים על התאמה למילון

בהמשך מוסבר איך Sensitive Data Protection מתאים מילים וביטויים במילון. הנקודות הבאות רלוונטיות גם למילונים רגילים וגם למילונים גדולים בהתאמה אישית:

  • המילים במילון לא תלויות-רישיות. אם המילון כולל את המילה Abby, תהיה התאמה ל-abby, ל-ABBY, ל-Abby וכן הלאה.
  • כל התווים – במילונים או בתוכן שצריך לסרוק – שאינם אותיות, ספרות ותווים אלפביתיים אחרים שנכללים ב-Basic Multilingual Plane של Unicode, נחשבים לרווחים כשסורקים כדי למצוא התאמות. אם המילון סורק את Abby Abernathy, הוא יתאים ל-abby abernathy, ל-Abby, Abernathy, ל-Abby (ABERNATHY) וכן הלאה.
  • התווים שמסביב להתאמה חייבים להיות מסוג שונה (אותיות או ספרות) מהתווים הסמוכים בתוך המילה. אם המילון סורק את Abi, הוא יתאים לשלושת התווים הראשונים של Abi904, אבל לא של Abigail.
  • מילים במילון שמכילות תווים במישור הרב-לשוני המשלים של תקן Unicode יכולות להניב ממצאים לא צפויים. דוגמאות לתווים כאלה: אמוג'י, סמלים מדעיים וכתבים היסטוריים.

אותיות, ספרות ותווים אלפביתיים אחרים מוגדרים כך:

  • אותיות: תווים עם הקטגוריות הכלליות Lu,‏ Ll,‏ Lt,‏ Lm או Lo במפרט של Unicode
  • ספרות: תווים עם הקטגוריה הכללית Nd במפרט של Unicode
  • תווים אלפביתיים אחרים: תווים עם קטגוריה כללית Nl במפרט של Unicode או עם מאפיין תורם Other_Alphabetic כפי שמוגדר בתקן Unicode

כדי ליצור, לערוך או למחוק סוג מידע מאוחסן, משתמשים בשיטות הבאות:

  • ‫storedInfoTypes.create: יוצרת stored infoType חדש לפי ה-StoredInfoTypeConfig שציינתם.
  • ‫storedInfoTypes.patch: בנייה מחדש של ה-infoType השמור עם StoredInfoTypeConfig חדש שאתם מציינים. אם לא מציינים גרסה, השיטה הזו יוצרת גרסה חדשה של ה-infoType השמור עם ה-StoredInfoTypeConfig הקיים.
  • ‫storedInfoTypes.get: מאחזר את StoredInfoTypeConfig ואת כל הגרסאות בהמתנה של ה-infoType שצוין ונשמר.
  • ‫storedInfoTypes.list: הצגת רשימה של כל סוגי המידע המאוחסנים הנוכחיים.
  • storedInfoTypes.delete: מחיקה של ה-infoType השמור שצוין.