建立自訂規則運算式偵測工具

規則運算式 (regex) 自訂 infoType 偵測工具允許您建立自己的偵測工具,讓機密資料保護功能根據規則運算式模式偵測相符項目。舉例來說,假設您的病歷編號格式為 ###-#-#####,則可定義如下所示的規則運算式:

[0-9]{3}-[0-9]{1}-[0-9]{5}

Sensitive Data Protection 接著會比對與下列內容相似的項目:

012-4-56789

規則運算式自訂 infoType 偵測工具的剖析

根據 API 總覽的摘要說明,如要建立自訂規則運算式 infoType 偵測工具,您必須定義包含下列項目的 CustomInfoType 物件:

  • InfoType 物件中您要提供給自訂 infoType 偵測工具的名稱。
  • 選用的 Likelihood 值。如果省略這個欄位,規則運算式相符項目會傳回預設的可能性 VERY_LIKELY。如果您發現規則運算式自訂 infoType 偵測工具傳回過多誤判情形,請嘗試降低可能性基準,並透過偵測規則使用情境資訊來改善可能性。詳情請參閱「自訂發現項目可能性」。
  • 選用的 DetectionRule 或啟動字詞規則。這些規則可在指定啟動字詞的特定字數範圍內,針對發現項目調整可能性。如要進一步瞭解啟動字詞規則,請參閱自訂發現項目可能性一文。
  • 選用的 SensitivityScore 值。如果省略這個欄位,與規則運算式相符的項目會傳回 HIGH 的預設敏感度等級。

    敏感度分數會用於資料剖析檔。在分析資料時,Sensitive Data Protection 會使用 infoType 的私密程度分數計算私密程度

  • 由定義規則運算式的單一模式所組成的 Regex 物件。

做為 JSON 物件,包含所有選用元件的規則運算式自訂 infoType 偵測工具看起來應與下列內容相似:

{
  "customInfoTypes":[
    {
      "infoType":{
        "name":"CUSTOM_INFOTYPE_NAME"
      },
      "likelihood":"LIKELIHOOD_LEVEL",
      "detectionRules":[
        {
          "hotwordRule":{
            HOTWORD_RULE
          }
        },
      "sensitivityScore":{
          "score": "SENSITIVITY_SCORE"
        },
      ],
      "regex":{
        "pattern":"REGULAR_EXPRESSION_PATTERN"
      }
    }
  ],
  ...
}

規則運算式範例:比對病歷號碼

下列 JSON 程式碼片段和幾種程式語言的程式碼,示範規則運算式自訂 infoType 偵測工具,這個偵測工具會指示 Sensitive Data Protection 以輸入文字「Patient's MRN 444-5-22222」比對病歷編號 (MRN),並將 POSSIBLE 的可能性指派給每個相符項目。

C#

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

public class InspectDataWithCustomRegex
{
    public static InspectContentResponse InspectDataCustomRegex(
        string projectId,
        string text,
        string customRegex,
        InfoType infoType = null)
    {
        // Instantiate a client.
        var dlp = DlpServiceClient.Create();

        // Construct content item by setting the text.
        var contentItem = new ContentItem { Value = text };

        // Construct the custom regex detector.
        var customInfoType = new CustomInfoType
        {
            InfoType = infoType ?? new InfoType { Name = "C_MRN" },
            Regex = new CustomInfoType.Types.Regex { Pattern = customRegex }
        };

        // Construct Inspect Config.
        var inspectConfig = new InspectConfig
        {
            CustomInfoTypes = { customInfoType },
            IncludeQuote = true,
            MinLikelihood = Likelihood.Possible
        };

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

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

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

        Console.WriteLine($"Findings: {resultFindings.Count}");
        foreach (var f in resultFindings)
        {
            Console.WriteLine("Quote: " + f.Quote);
            Console.WriteLine("Info type: " + f.InfoType.Name);
            Console.WriteLine("Likelihood: " + f.Likelihood);
        }

        return response;
    }
}

Go

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

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

// inspectWithCustomRegex inspect a data with custom regex pattern
func inspectWithCustomRegex(w io.Writer, projectID, textToInspect, customRegexPattern, infoTypeName string) error {
	//projectID := "my-project-id"
	//textToInspect := "Patients MRN 444-5-22222"
	//customRegexPattern := "[1-9]{3}-[1-9]{1}-[1-9]{5}"
	//infoTypeName := "C_MRN"

	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 type and content to be inspected.
	contentItem := &dlppb.ContentItem{
		DataItem: &dlppb.ContentItem_ByteItem{
			ByteItem: &dlppb.ByteContentItem{
				Type: dlppb.ByteContentItem_TEXT_UTF8,
				Data: []byte(textToInspect),
			},
		},
	}

	// Construct the custom regex detectors
	customInfoType := &dlppb.CustomInfoType{
		InfoType: &dlppb.InfoType{
			Name: infoTypeName,
		},
		// Specify the regex pattern the inspection will look for.
		Type: &dlppb.CustomInfoType_Regex_{
			Regex: &dlppb.CustomInfoType_Regex{
				Pattern: customRegexPattern,
			},
		},
		Likelihood: dlppb.Likelihood_POSSIBLE,
	}

	// Construct the Inspect request to be sent by the client.
	req := &dlppb.InspectContentRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Item:   contentItem,
		// Construct the configuration for the Inspect request.
		InspectConfig: &dlppb.InspectConfig{
			CustomInfoTypes: []*dlppb.CustomInfoType{
				customInfoType,
			},
			IncludeQuote: true,
		},
	}

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

	// Parse the response and process results
	fmt.Fprintf(w, "Findings: %v\n", len(resp.Result.Findings))
	for _, v := range resp.GetResult().Findings {
		fmt.Fprintf(w, "Quote: %v\n", v.GetQuote())
		fmt.Fprintf(w, "Infotype Name: %v\n", v.GetInfoType().GetName())
		fmt.Fprintf(w, "Likelihood: %v\n", v.GetLikelihood())
	}
	return nil
}

Java

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ByteContentItem.BytesType;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.CustomInfoType;
import com.google.privacy.dlp.v2.CustomInfoType.Regex;
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.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class InspectWithCustomRegex {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String textToInspect = "Patients MRN 444-5-22222";
    String customRegexPattern = "[1-9]{3}-[1-9]{1}-[1-9]{5}";
    inspectWithCustomRegex(projectId, textToInspect, customRegexPattern);
  }

  // Inspects a BigQuery Table
  public static void inspectWithCustomRegex(
      String projectId, String textToInspect, String customRegexPattern) 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 type and content to be inspected.
      ByteContentItem byteItem =
          ByteContentItem.newBuilder()
              .setType(BytesType.TEXT_UTF8)
              .setData(ByteString.copyFromUtf8(textToInspect))
              .build();
      ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build();

      // Specify the regex pattern the inspection will look for.
      Regex regex = Regex.newBuilder().setPattern(customRegexPattern).build();

      // Construct the custom regex detector.
      InfoType infoType = InfoType.newBuilder().setName("C_MRN").build();
      CustomInfoType customInfoType =
          CustomInfoType.newBuilder().setInfoType(infoType).setRegex(regex).build();

      // Construct the configuration for the Inspect request.
      InspectConfig config =
          InspectConfig.newBuilder()
              .addCustomInfoTypes(customInfoType)
              .setIncludeQuote(true)
              .setMinLikelihood(Likelihood.POSSIBLE)
              .build();

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

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

      // 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("\tInfo type: " + f.getInfoType().getName());
        System.out.println("\tLikelihood: " + f.getLikelihood());
      }
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// 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 = 'my-project';

// The string to inspect
// const string = 'Patients MRN 444-5-22222';

// The regex pattern to match for
// const customRegex = '[1-9]{3}-[1-9]{1}-[1-9]{5}';

async function inspectWithCustomRegex() {
  // Construct item to inspect
  const item = {
    byteItem: {
      type: DLP.protos.google.privacy.dlp.v2.ByteContentItem.BytesType
        .TEXT_UTF8,
      data: Buffer.from(string, 'utf-8'),
    },
  };

  // Construct the custom regex detector.
  const customInfoTypes = [
    {
      infoType: {
        name: 'C_MRN',
      },
      likelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.POSSIBLE,
      regex: {
        pattern: customRegex,
      },
    },
  ];

  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectConfig: {
      customInfoTypes: customInfoTypes,
      includeQuote: true,
    },
    item: item,
  };

  // Run request
  const [response] = await dlp.inspectContent(request);
  const findings = response.result.findings;
  if (findings.length > 0) {
    console.log('Findings: \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.');
  }
}
inspectWithCustomRegex();

PHP

如要瞭解如何安裝及使用 Sensitive Data Protection 的用戶端程式庫,請參閱這篇文章

如要驗證 Sensitive Data Protection,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

/**
 * Inspect data with a custom regex
 * Regex example: Matching medical record numbers. The following sample uses a regular expression custom infoType detector that instructs Cloud DLP to match a medical record number (MRN) in the input text "Patient's MRN 444-5-22222," and then assigns each match a likelihood of POSSIBLE.
 *
 * @param string $projectId         The Google Cloud project id to use as a parent resource.
 * @param string $textToInspect     The string to inspect.
 */
function inspect_custom_regex(
    // TODO(developer): Replace sample parameters before running the code.
    string $projectId,
    string $textToInspect = 'Patients MRN 444-5-22222'
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

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

    // Specify what content you want the service to Inspect.
    $item = (new ContentItem())
        ->setValue($textToInspect);

    // Specify the regex pattern the inspection will look for.
    $customRegexPattern = '[1-9]{3}-[1-9]{1}-[1-9]{5}';

    // Construct the custom regex detector.
    $cMrnDetector = (new InfoType())
        ->setName('C_MRN');
    $customInfoType = (new CustomInfoType())
        ->setInfoType($cMrnDetector)
        ->setRegex((new Regex())
            ->setPattern($customRegexPattern))
        ->setLikelihood(Likelihood::POSSIBLE);

    // 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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import google.cloud.dlp


def inspect_data_with_custom_regex_detector(
    project: str,
    content_string: str,
) -> None:
    """Uses the Data Loss Prevention API to analyze string with medical record
       number custom regex detector

    Args:
        project: The Google Cloud project id to use as a parent resource.
        content_string: The string to inspect.

    Returns:
        None; the response from the API is printed to the terminal.
    """

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

    # Construct a custom regex detector info type called "C_MRN",
    # with ###-#-##### pattern, where each # represents a digit from 1 to 9.
    # The detector has a detection likelihood of POSSIBLE.
    custom_info_types = [
        {
            "info_type": {"name": "C_MRN"},
            "regex": {"pattern": "[1-9]{3}-[1-9]{1}-[1-9]{5}"},
            "likelihood": google.cloud.dlp_v2.Likelihood.POSSIBLE,
        }
    ]

    # Construct the configuration dictionary with the custom regex info type.
    inspect_config = {
        "custom_info_types": custom_info_types,
        "include_quote": True,
    }

    # Construct the `item`.
    item = {"value": content_string}

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

    # 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

如要進一步瞭解如何透過 JSON 使用 DLP API,請參閱 JSON 快速入門導覽課程

JSON 輸入:

POST https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/content:inspect?key={YOUR_API_KEY}

{
  "item":{
    "value":"Patients MRN 444-5-22222"
  },
  "inspectConfig":{
    "customInfoTypes":[
      {
        "infoType":{
          "name":"C_MRN"
        },
        "regex":{
          "pattern":"[1-9]{3}-[1-9]{1}-[1-9]{5}"
        },
        "likelihood":"POSSIBLE"
      }
    ]
  }
}

JSON 輸出:

{
  "result":{
    "findings":[
      {
        "infoType":{
          "name":"C_MRN"
        },
        "likelihood":"POSSIBLE",
        "location":{
          "byteRange":{
            "start":"13",
            "end":"24"
          },
          "codepointRange":{
            "start":"13",
            "end":"24"
          }
        },
        "createTime":"2018-11-30T01:29:37.799Z"
      }
    ]
  }
}

輸出內容顯示,透過名稱為 C_MRN 的自訂 infoType 偵測工具及自訂規則運算式,Sensitive Data Protection 已正確識別出病歷編號,並按照我們指定的方式將 POSSIBLE 的可能性指派給該編號。

自訂相符可能性一文採用本範例做為基礎並包含內容字詞。