ספריות הלקוח של Sensitive Data Protection

בדף הזה מוסבר איך להתחיל להשתמש בספריות הלקוח של Cloud עבור Cloud Data Loss Prevention API. ספריות לקוח מאפשרות לגשת בקלות ל-Google Cloud APIs בשפה נתמכת. אמנם אפשר להשתמש ישירות ב-Google Cloud APIs על ידי יצירת בקשות גולמיות חדשות לשרת, אבל ספריות לקוח מפשטות את התהליך ומפחיתות באופן משמעותי את כמות הקוד שתצטרכו לכתוב.

מידע נוסף על ספריות הלקוח ב-Cloud ועל ספריות הלקוח הישנות של Google API זמין במאמר הסבר על ספריות לקוח.

‫Cloud Data Loss Prevention API (DLP API) הוא חלק מ-Sensitive Data Protection. ספריות הלקוח של Sensitive Data Protection שמוזכרות בדף הזה נתמכות ב-Compute Engine, בסביבה גמישה של App Engine, ב-Google Kubernetes Engine ובפונקציות של Cloud Run. ספריית הלקוח של Sensitive Data Protection ל-Java נתמכת ב-Java 8 בסביבה רגילה של App Engine.

אם אתם משתמשים ב-Java 7 בסביבה הרגילה של App Engine, או בסביבה הרגילה של App Engine עם Go,‏ PHP או Python, אתם יכולים להשתמש בממשק REST כדי לגשת אל Sensitive Data Protection.

התקנת ספריית הלקוח

C#

כדי ליצור ולהפעיל דוגמה, פותחים את קובץ הפתרון (Dlp.sln) באמצעות Visual Studio 2015 ואילך ויוצרים אותו.

מידע נוסף זמין בREADME.

מידע נוסף מופיע במאמר הגדרת סביבת פיתוח בשפת C# ‎.

Go

go get cloud.google.com/go/dlp

מידע נוסף זמין במאמר הגדרת סביבת פיתוח בשפת Go.

Java

אם משתמשים ב-Maven, צריך להוסיף את הקוד הבא לקובץ pom.xml. במאמר העוסק בספריות BOM ל-Google Cloud Platform תוכלו לקרוא מידע נוסף על עצי מוצרים (BOM).

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.83.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-dlp</artifactId>
  </dependency>
</dependencies>

אם משתמשים ב-Gradle, צריך להוסיף את הקוד הבא ליחסי התלות:

implementation 'com.google.cloud:google-cloud-dlp:3.97.0'

אם משתמשים ב-sbt, צריך להוסיף את הקוד הבא ליחסי התלות:

libraryDependencies += "com.google.cloud" % "google-cloud-dlp" % "3.97.0"

אם משתמשים ב-Visual Studio Code או ב-IntelliJ, אפשר להוסיף את ספריות הלקוח לפרויקט באמצעות יישומי הפלאגין הבאים של IDE:

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

מידע נוסף זמין במאמר הגדרת סביבת פיתוח בשפת Java.

Node.js

npm install @google-cloud/dlp

מידע נוסף זמין במאמר הגדרת סביבת פיתוח של Node.js.

PHP

composer require google/cloud-dlp

מידע נוסף זמין במאמר שימוש ב-PHP ב-Google Cloud.

Python

  1. אם עדיין לא התקנתם את pip ואת virtualenv, צריך להתקין אותם. הוראות מפורטות זמינות במדריך להגדרת סביבת הפיתוח בשפת Python Google Cloud.
  2. משכפלים או מורידים את Google Cloud הדוגמאות של מסמכי Python ב-GitHub.
  3. יוצרים סביבה וירטואלית. הדוגמאות תואמות ל-Python בגרסאות 2.7.x ו-3.4 ואילך.
    $ python -m venv dlp
    $ source dlp/bin/activate
  4. בספרייה dlp בתוך הספרייה המשוכפלת או שחולצה מ-zip‏ Google Cloud Python Docs Samples, מתקינים את הרכיבים התלויים שנדרשים להרצת הדוגמאות.
    $ pip install -r requirements.txt

Ruby

gem install google-api-client

מידע נוסף זמין במאמר הגדרת סביבת פיתוח בשפת Ruby.

מגדירים אימות

כדי לאמת קריאות לממשקי ה-API של Google Cloud , ספריות הלקוח תומכות ב-Application Default Credentials ‏ (ADC). בספריות מתבצע חיפוש של פרטי כניסה בקבוצה של מיקומים מוגדרים, והמערכת משתמשת בפרטי הכניסה האלה כדי לאמת בקשות ל-API. בעזרת ADC, פרטי הכניסה לאפליקציה יכולים להיות זמינים בסביבות שונות, כמו בפיתוח מקומי או בייצור, בלי שיהיה צריך לשנות את קוד האפליקציה.

בסביבות ייצור, אופן ההגדרה של ADC תלוי בשירות ובהקשר. מידע נוסף זמין במאמר בנושא הגדרה של Application Default Credentials.

בסביבת פיתוח מקומית, אפשר להגדיר את ADC עם פרטי הכניסה שמשויכים לחשבון Google שלכם:

  1. התקינו את ה-CLI של Google Cloud. אחר כך, אתחלו את ה-CLI של Google Cloud באמצעות הפקודה הבאה:

    gcloud init

    אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

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

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    מסך הכניסה יופיע. אחרי שנכנסים, פרטי הכניסה נשמרים בקובץ פרטי הכניסה המקומי שמשמש את ADC.

שימוש בספריית הלקוח

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

C#


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

public class ClientLibraryQuickStart
{
    public static InspectContentResponse QuickStart(
        string projectId,
        string text,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate a client.
        var dlp = DlpServiceClient.Create();

        // Construct the byte content item by specifying the type of data to be inspected
        // and data to be inspected.
        var byteContentItem = new ByteContentItem
        {
            Type = ByteContentItem.Types.BytesType.TextUtf8,
            Data = Google.Protobuf.ByteString.CopyFromUtf8(text)
        };

        // Construct content item by setting byte item.
        var contentItem = new ContentItem { ByteItem = byteContentItem };

        // Set minimum likelihood and limits.
        var minLikelihood = Likelihood.Possible;
        var limits = new InspectConfig.Types.FindingLimits
        {
            // Specifying 0 means use the maximum allowed findings.
            MaxFindingsPerRequest = 0
        };

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

        // Construct a request config.
        var request = new InspectContentRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            Item = contentItem,
            InspectConfig = inspectConfig
        };

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

        // Inspect the response.
        var resultFindings = response.Result.Findings;

        Console.WriteLine($"Findings: {resultFindings.Count}");

        foreach (var f in resultFindings)
        {
            Console.WriteLine("\tQuote: " + f.Quote);
            Console.WriteLine("\tInfo type: " + f.InfoType.Name);
            Console.WriteLine("\tLikelihood: " + f.Likelihood);
        }
        return response;
    }
}

Go


// The quickstart program is an example of using the Data Loss Prevention API.
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()

	projectID := "PROJECT_ID"

	// Creates a DLP client.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		log.Fatalf("error creating DLP client: %v", err)
	}
	defer client.Close()

	// The string to inspect.
	input := "Robert Frost"

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

	// The maximum number of findings to report (0 = server maximum).
	maxFindings := int32(0)

	// Whether to include the matching string.
	includeQuote := true

	// The infoTypes of information to match.
	infoTypes := []*dlppb.InfoType{
		{
			Name: "PERSON_NAME",
		},
		{
			Name: "US_STATE",
		},
	}

	// Construct item to inspect.
	item := &dlppb.ContentItem{
		DataItem: &dlppb.ContentItem_Value{
			Value: input,
		},
	}

	// Construct request.
	req := &dlppb.InspectContentRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		InspectConfig: &dlppb.InspectConfig{
			InfoTypes:     infoTypes,
			MinLikelihood: minLikelihood,
			Limits: &dlppb.InspectConfig_FindingLimits{
				MaxFindingsPerRequest: maxFindings,
			},
			IncludeQuote: includeQuote,
		},
		Item: item,
	}

	// Run request.
	resp, err := client.InspectContent(ctx, req)
	if err != nil {
		log.Fatal(err)
	}
	findings := resp.GetResult().GetFindings()
	if len(findings) == 0 {
		fmt.Println("No findings.")
	}
	fmt.Println("Findings:")
	for _, f := range findings {
		if includeQuote {
			fmt.Println("\tQuote: ", f.GetQuote())
		}
		fmt.Println("\tInfo type: ", f.GetInfoType().GetName())
		fmt.Println("\tLikelihood: ", f.GetLikelihood())
	}
}

Java


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ContentItem;
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.InspectResult;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class QuickStart {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    quickstart(projectId);
  }

  public static void quickstart(String projectId) 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 dlpServiceClient = DlpServiceClient.create()) {
      // Configure that content that will be inspected
      String text = "His name was Robert Frost";
      ByteContentItem byteContentItem =
          ByteContentItem.newBuilder()
              .setType(ByteContentItem.BytesType.TEXT_UTF8)
              .setData(ByteString.copyFromUtf8(text))
              .build();
      ContentItem contentItem = ContentItem.newBuilder().setByteItem(byteContentItem).build();

      // The types of information to match:
      // See: https://cloud.google.com/dlp/docs/infotypes-reference
      List<InfoType> infoTypes =
          Stream.of("PERSON_NAME", "US_STATE")
              .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.POSSIBLE;

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

      // Specify the inspection configuration
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .setIncludeQuote(true)
              .build();

      // Create the request from previous configs
      InspectContentRequest request =
          InspectContentRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectConfig(inspectConfig)
              .setItem(contentItem)
              .build();

      // Send the request to the service and receive the results
      InspectContentResponse response = dlpServiceClient.inspectContent(request);

      // Process the results
      System.out.println("Inspect of text complete: ");
      InspectResult result = response.getResult();
      if (result.getFindingsCount() < 0) {
        System.out.println("No findings.");
        return;
      }
      System.out.println("Findings: ");
      for (Finding finding : result.getFindingsList()) {
        System.out.println("\tQuote: " + finding.getQuote());
        System.out.println("\tInfo type: " + finding.getInfoType().getName());
        System.out.println("\tLikelihood: " + finding.getLikelihood());
      }
    }
  }
}

Node.js


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

// The string to inspect
const string = 'Robert Frost';

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

async function quickStart() {
  // The minimum likelihood required before returning a match
  const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

  // The maximum number of findings to report (0 = server maximum)
  const maxFindings = 0;

  // The infoTypes of information to match
  const infoTypes = [{name: 'PERSON_NAME'}, {name: 'US_STATE'}];

  // Whether to include the matching string
  const includeQuote = true;

  // Construct item to inspect
  const item = {value: string};

  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectConfig: {
      infoTypes: infoTypes,
      minLikelihood: minLikelihood,
      limits: {
        maxFindingsPerRequest: maxFindings,
      },
      includeQuote: includeQuote,
    },
    item: item,
  };

  // Run request
  const [response] = await dlp.inspectContent(request);
  const findings = response.result.findings;
  if (findings.length > 0) {
    console.log('Findings:');
    findings.forEach(finding => {
      if (includeQuote) {
        console.log(`\tQuote: ${finding.quote}`);
      }
      console.log(`\tInfo type: ${finding.infoType.name}`);
      console.log(`\tLikelihood: ${finding.likelihood}`);
    });
  } else {
    console.log('No findings.');
  }
}
quickStart();

PHP

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

// Instantiate a client.
$dlp = new DlpServiceClient();

// The infoTypes of information to match
$usNameInfoType = (new InfoType())
    ->setName('PERSON_NAME');
$phoneNumberInfoType = (new InfoType())
    ->setName('PHONE_NUMBER');
$infoTypes = [$usNameInfoType, $phoneNumberInfoType];

// Set the string to inspect
$stringToInspect = 'Robert Frost';

// Only return results above a likelihood threshold, 0 for all
$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

// Limit the number of findings, 0 for no limit
$maxFindings = 0;

// Whether to include the matching string in the response
$includeQuote = true;

// Specify finding limits
$limits = (new FindingLimits())
    ->setMaxFindingsPerRequest($maxFindings);

// Create the configuration object
$inspectConfig = (new InspectConfig())
    ->setMinLikelihood($minLikelihood)
    ->setLimits($limits)
    ->setInfoTypes($infoTypes)
    ->setIncludeQuote($includeQuote);

$content = (new ContentItem())
    ->setValue($stringToInspect);

$projectId = getenv('GCLOUD_PROJECT');
$parent = $dlp->projectName($projectId);

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

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

Python

# Import the client library
import google.cloud.dlp

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

# The string to inspect
content = "Robert Frost"

# Construct the item to inspect.
item = {"value": content}

# The info types to search for in the content. Required.
info_types = [{"name": "FIRST_NAME"}, {"name": "LAST_NAME"}]

# The minimum likelihood to constitute a match. Optional.
min_likelihood = google.cloud.dlp_v2.Likelihood.LIKELIHOOD_UNSPECIFIED

# The maximum number of findings to report (0 = server maximum). Optional.
max_findings = 0

# Whether to include the matching string in the results. Optional.
include_quote = True

# Construct the configuration dictionary. Keys which are None may
# optionally be omitted entirely.
inspect_config = {
    "info_types": info_types,
    "min_likelihood": min_likelihood,
    "include_quote": include_quote,
    "limits": {"max_findings_per_request": max_findings},
}

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

# Call the API.
response = dlp_client.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:
        try:
            print(f"Quote: {finding.quote}")
        except AttributeError:
            pass
        print(f"Info type: {finding.info_type.name}")
        # Convert likelihood value to string respresentation.
        likelihood = finding.likelihood.name
        print(f"Likelihood: {likelihood}")
else:
    print("No findings.")

מקורות מידע נוספים

C#

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של C#:

Go

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Go:

Java

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Java:

Node.js

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Node.js:

PHP

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של PHP:

Python

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Python:

Ruby

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Ruby: