הסתרת נתונים בעמודה

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

כדי להטמיע הסתרת נתונים, מוסיפים מדיניות נתונים לעמודה. כדי להוסיף מדיניות להסתרת נתונים לעמודה, צריך לבצע את השלבים הבאים :

  1. יוצרים טקסונומיה עם תג מדיניות אחד לפחות.
  2. אופציונלי: אפשר להעניק את התפקיד Data Catalog Fine-Grained Reader (קריאה מפורטת של קטלוג הנתונים) לחשבון משתמש אחד או יותר בתגי מדיניות אחדים או יותר שיצרתם.
  3. יוצרים עד שלוש מדיניות נתונים לתג המדיניות, כדי למפות כללי מיסוך וגורמים (שמייצגים משתמשים או קבוצות) לתג הזה.
  4. מגדירים את תג המדיניות בעמודה. כך ממפים את מדיניות הנתונים שמשויכת לתג המדיניות לעמודה שנבחרה.
  5. מקצים למשתמשים שצריכה להיות להם גישה לנתונים מוסווים את התפקיד 'קורא נתונים מוסווים ב-BigQuery'. מומלץ להקצות את התפקיד BigQuery Masked Reader ברמת מדיניות הנתונים. הקצאת התפקיד ברמת הפרויקט או ברמה גבוהה יותר מעניקה למשתמשים הרשאות לכל מדיניות הנתונים בפרויקט, מה שעלול לגרום לבעיות שנובעות מהרשאות עודפות.

אפשר להשתמש במסוף Google Cloud או בממשק BigQuery Data Policy API כדי לעבוד עם מדיניות נתונים.

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

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

הסתרת נתונים באמצעות תגי מדיניות

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

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Data Catalog and BigQuery Data Policy APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Data Catalog and BigQuery Data Policy APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. ‫BigQuery מופעל באופן אוטומטי בפרויקטים חדשים, אבל יכול להיות שתצטרכו להפעיל אותו בפרויקט קיים.

    מפעילים את BigQuery API.

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    להפעלת ה-API

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

יצירת טקסונומיות

למשתמש או לחשבון השירות שיוצרים טקסונומיה צריך להקצות את התפקיד Data Catalog Policy Tag Admin.

המסוף

  1. פותחים את הדף Policy tag taxonomies במסוףGoogle Cloud .

    פתיחת הדף Policy tag taxonomies

  2. לוחצים על יצירת טקסונומיה.
  3. בדף New taxonomy:

    1. בשדה שם הטקסונומיה, מזינים את השם של הטקסונומיה שרוצים ליצור.
    2. בקטע תיאור, מזינים תיאור.
    3. אם צריך, משנים את הפרויקט שמופיע בקטע Project.
    4. אם צריך, משנים את המיקום שמופיע בקטע מיקום.
    5. בקטע תגי מדיניות, מזינים שם ותיאור של תג מדיניות.
    6. כדי להוסיף תג מדיניות משני לתג מדיניות, לוחצים על הוספת תג משני.
    7. כדי להוסיף תג מדיניות חדש באותה רמה של תג מדיניות אחר, לוחצים על + הוספת תג מדיניות.
    8. ממשיכים להוסיף תגי מדיניות ותגי מדיניות לילדים לפי הצורך לטקסונומיה.
    9. כשמסיימים ליצור תגי מדיניות להיררכיה, לוחצים על יצירה.

API

כדי להשתמש בטקסונומיות קיימות, קוראים ל-taxonomies.import במקום שני השלבים הראשונים בתהליך הבא.

  1. מתקשרים אל taxonomies.create כדי ליצור טקסונומיה.
  2. מתקשרים אל taxonomies.policytag.create כדי ליצור תג מדיניות.

עבודה עם תגי מדיניות

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

יצירת מדיניות בנושא נתונים

למשתמש או לחשבון השירות שיוצרים מדיניות נתונים צריכות להיות ההרשאות bigquery.dataPolicies.create, bigquery.dataPolicies.setIamPolicy ו-datacatalog.taxonomies.get.

ההרשאות bigquery.dataPolicies.create ו-bigquery.dataPolicies.setIamPolicy כלולות בתפקידים BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery), אדמין של BigQuery והבעלים של נתוני BigQuery. ההרשאה datacatalog.taxonomies.get כלולה בתפקידים Data Catalog Admin ו-Data Catalog Viewer.

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

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

אפשר ליצור עד תשעה כללי מדיניות לכל תג מדיניות. אחת מהמדיניות האלה שמורה להגדרות של בקרת גישה ברמת העמודה.

המסוף

  1. פותחים את הדף Policy tag taxonomies במסוףGoogle Cloud .

    פתיחת הדף Policy tag taxonomies

  2. לוחצים על שם הטקסונומיה כדי לפתוח אותה.
  3. בוחרים תג מדיניות.
  4. לוחצים על ניהול מדיניות בנושא נתונים.
  5. בשדה שם מדיניות הנתונים, מקלידים שם למדיניות הנתונים. שם מדיניות הנתונים חייב להיות ייחודי בפרויקט שבו מדיניות הנתונים נמצאת.
  6. בקטע כלל מיסוך, בוחרים כלל מיסוך מוגדר מראש או שגרת מיסוך בהתאמה אישית. אם בוחרים בשגרה מותאמת אישית להסתרת נתונים, צריך לוודא שיש לכם את ההרשאות bigquery.routines.get ו-bigquery.routines.list ברמת הפרויקט.
  7. בשדה Principal, מקלידים את השם של משתמש אחד או יותר או של קבוצות שרוצים להעניק להם גישה מוסתרת לעמודה. שימו לב: כל המשתמשים והקבוצות שתזינו כאן יקבלו את התפקיד BigQuery Masked Reader (משתמש עם גישה מוגבלת לקריאה ב-BigQuery).
  8. לוחצים על שליחה.

API

  1. מבצעים קריאה ל-method‏ create. צריך להעביר משאב DataPolicy שעומד בדרישות הבאות:

    • השדה dataPolicyType מוגדר ל-DATA_MASKING_POLICY.
    • השדה dataMaskingPolicy מזהה את כלל או שגרת מיסוך הנתונים שבהם צריך להשתמש.
    • השדה dataPolicyId מספק שם למדיניות הנתונים שהוא ייחודי בפרויקט שבו נמצאת מדיניות הנתונים.
  2. מבצעים קריאה ל-method‏ setIamPolicy ומעבירים את הערך Policy. ב-Policy צריך לציין את חשבונות המשתמשים שקיבלו גישה לנתונים מוסווים, ולציין roles/bigquerydatapolicy.maskedReader בשדה role.

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

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

const datapolicy = require('@google-cloud/bigquery-datapolicies');
const {DataPolicyServiceClient} = datapolicy.v2;
const protos = datapolicy.protos.google.cloud.bigquery.datapolicies.v2;
const {status} = require('@grpc/grpc-js');

const dataPolicyServiceClient = new DataPolicyServiceClient();

/**
 * Creates a data policy to apply a data masking rule to a specific BigQuery table column.
 * This is a primary mechanism for implementing column-level security in BigQuery.
 *
 * @param {string} projectId The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} location The Google Cloud location. Example: 'us'
 * @param {string} dataPolicyId The user-assigned ID of the data policy. Example: 'example-data-policy-id'
 */
async function createDataPolicy(projectId, location, dataPolicyId) {
  const parent = `projects/${projectId}/locations/${location}`;

  const dataPolicy = {
    dataPolicyType: protos.DataPolicy.DataPolicyType.DATA_MASKING_POLICY,
    dataMaskingPolicy: {
      predefinedExpression:
        protos.DataMaskingPolicy.PredefinedExpression.SHA256,
    },
  };

  const request = {
    parent,
    dataPolicyId,
    dataPolicy,
  };

  try {
    const [response] = await dataPolicyServiceClient.createDataPolicy(request);
    console.log(`Successfully created data policy: ${response.name}`);
    console.log(`Data policy ID: ${response.dataPolicyId}`);
    console.log(`Data policy type: ${response.dataPolicyType}`);
    if (response.dataMaskingPolicy) {
      console.log(
        `Data masking expression: ${response.dataMaskingPolicy.predefinedExpression}`,
      );
    }
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.log(
        `Data policy '${dataPolicyId}' already exists in location '${location}' of project '${projectId}'.`,
      );
      console.log(
        'Consider updating the existing data policy or using a different dataPolicyId.',
      );
    } else {
      console.error('Error creating data policy:', err.message);
    }
  }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

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

from google.api_core import exceptions
from google.cloud import bigquery_datapolicies_v2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def create_data_policy(project_id: str, location: str, data_policy_id: str) -> None:
    """Creates a data policy to apply a data masking rule to a specific BigQuery table column.
    This is a primary mechanism for implementing column-level security in BigQuery.

    Args:
        project_id (str): The Google Cloud project ID.
        location (str): The geographic location of the data policy (for example, "us-central1").
        data_policy_id (str): The ID for the new data policy.
    """

    parent = f"projects/{project_id}/locations/{location}"

    # Define the data masking policy.
    # Here, we specify a SHA-256 predefined expression for data masking.
    data_masking_policy = bigquery_datapolicies_v2.DataMaskingPolicy(
        predefined_expression=bigquery_datapolicies_v2.DataMaskingPolicy.PredefinedExpression.SHA256
    )

    # Create the DataPolicy object.
    # We set the type to DATA_MASKING_POLICY and assign the defined masking policy.
    data_policy = bigquery_datapolicies_v2.DataPolicy(
        data_policy_type=bigquery_datapolicies_v2.DataPolicy.DataPolicyType.DATA_MASKING_POLICY,
        data_masking_policy=data_masking_policy,
    )

    request = bigquery_datapolicies_v2.CreateDataPolicyRequest(
        parent=parent,
        data_policy_id=data_policy_id,
        data_policy=data_policy,
    )

    try:
        response = client.create_data_policy(request=request)
        print(f"Successfully created data policy: {response.name}")
        print(f"Data Policy ID: {response.data_policy_id}")
        print(f"Data Policy Type: {response.data_policy_type.name}")
        print(
            "Data Masking Predefined Expression:"
            f" {response.data_masking_policy.predefined_expression.name}"
        )
    except exceptions.AlreadyExists as e:
        print(
            f"Error: Data policy '{data_policy_id}' already exists in project"
            f" '{project_id}' in location '{location}'. Use a unique ID or"
            " update the existing policy if needed."
        )

    except exceptions.NotFound as e:
        print(
            f"Error: The specified project '{project_id}' or location '{location}'"
            " was not found or is inaccessible. Make sure the project ID and"
            " location are correct and you have the necessary permissions."
        )
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

הגדרת תגי מדיניות בעמודות

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

למשתמש או לחשבון השירות שמגדירים תג מדיניות צריכות להיות ההרשאות datacatalog.taxonomies.get ו-bigquery.tables.setCategory. datacatalog.taxonomies.get כלולה בתפקידים 'אדמין של תגי מדיניות ב-Data Catalog' ו'צפייה בפרויקט'. ‫bigquery.tables.setCategory נכלל בתפקידים BigQuery Admin ‏ (roles/bigquery.admin) ו-BigQuery Data Owner ‏ (roles/bigquery.dataOwner).

כדי להציג טקסונומיות ותגי מדיניות בכל הפרויקטים בארגון ב-Google Cloud console, המשתמשים צריכים את ההרשאה resourcemanager.organizations.get, שנכללת בתפקיד 'צפייה בארגון'. לא נדרשת הרשאה כזו כשמשתמשים ב-API או בכלי bq של שורת הפקודה.

המסוף

מגדירים את תג המדיניות על ידי שינוי סכימה באמצעות מסוףGoogle Cloud .

  1. פותחים את הדף BigQuery במסוף Google Cloud .

    לדף BigQuery

  2. ב-BigQuery Explorer, מאתרים את הטבלה שרוצים לעדכן ובוחרים אותה. תיפתח סכימת הטבלה של הטבלה הזו.

  3. לוחצים על עריכת סכימה.

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

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

  6. לוחצים על בחירה. המסך שלכם אמור להיראות כמו בדוגמה הבאה:

    עריכת הסכימה.

  7. לוחצים על Save.

BQ

  1. כותבים את הסכימה לקובץ מקומי.

    bq show --schema --format=prettyjson \
       project-id:dataset.table > schema.json

    where:

    • project-id הוא מזהה הפרויקט.
    • dataset הוא שם מערך הנתונים שמכיל את הטבלה שאתם מעדכנים.
    • table הוא השם של הטבלה שאתם מעדכנים.
  2. משנים את schema.json כדי להגדיר תג מדיניות בעמודה. כדי להגדיר את הערך של השדה names של policyTags, משתמשים בשם המשאב של תג המדיניות.

    [
     ...
     {
       "name": "ssn",
       "type": "STRING",
       "mode": "REQUIRED",
       "policyTags": {
         "names": ["projects/project-id/locations/location/taxonomies/taxonomy-id/policyTags/policytag-id"]
       }
     },
     ...
    ]
  3. מעדכנים את הסכימה.

    bq update \
       project-id:dataset.table schema.json

API

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

כשעובדים עם טבלה קיימת, עדיף להשתמש ב-method‏ tables.patch, כי ה-method‏ tables.update מחליף את כל משאב הטבלה.

אכיפת בקרת גישה

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

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

קבלת מדיניות בנושא נתונים

כדי לקבל מידע על מדיניות בנושא נתונים:

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

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

const {DataPolicyServiceClient} =
  require('@google-cloud/bigquery-datapolicies').v2;
const {status} = require('@grpc/grpc-js');

const client = new DataPolicyServiceClient();

/**
 * Gets a specific data policy from the BigQuery Data Policy API by its name.
 *
 * This sample demonstrates how to fetch the details of an existing data policy.
 * Data policies are used to define rules for data masking or row-level security
 * on BigQuery tables.
 *
 * @param {string} projectId The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} [location='us'] The Google Cloud location of the data policy (For example, 'us', 'europe-west2').
 * @param {string} [dataPolicyId='example-data-policy'] The ID of the data policy to retrieve.
 */
async function getDataPolicy(
  projectId,
  location = 'us',
  dataPolicyId = 'example-data-policy',
) {
  const name = client.dataPolicyPath(projectId, location, dataPolicyId);

  const request = {
    name,
  };

  try {
    const [dataPolicy] = await client.getDataPolicy(request);
    console.log('Successfully retrieved data policy:');
    console.log(`  Name: ${dataPolicy.name}`);
    console.log(`  Type: ${dataPolicy.dataPolicyType}`);
    if (dataPolicy.dataMaskingPolicy) {
      console.log(
        `  Data Masking Policy: ${dataPolicy.dataMaskingPolicy.predefinedExpression || dataPolicy.dataMaskingPolicy.routine}`,
      );
    }
    if (dataPolicy.grantees && dataPolicy.grantees.length > 0) {
      console.log(`  Grantees: ${dataPolicy.grantees.join(', ')}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: Data policy '${dataPolicyId}' not found in location '${location}' for project '${projectId}'.`,
      );
      console.error(
        'Make sure the data policy ID, project ID, and location are correct.',
      );
    } else {
      console.error('Error retrieving data policy:', err.message);
    }
  }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

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

from google.api_core import exceptions
from google.cloud import bigquery_datapolicies_v2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def get_data_policy(
    project_id: str,
    location: str,
    data_policy_id: str,
) -> None:
    """Gets a specific data policy from the BigQuery Data Policy API by its name.


    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the data policy (for example, "us", "eu").
        data_policy_id: The user-assigned ID of the data policy.
    """
    client = bigquery_datapolicies_v2.DataPolicyServiceClient()

    data_policy_name = client.data_policy_path(
        project=project_id,
        location=location,
        data_policy=data_policy_id,
    )

    try:
        response = client.get_data_policy(name=data_policy_name)

        print(f"Successfully retrieved data policy: {response.name}")
        print(f"  Data Policy ID: {response.data_policy_id}")
        print(f"  Data Policy Type: {response.data_policy_type.name}")
        if response.policy_tag:
            print(f"  Policy Tag: {response.policy_tag}")
        if response.grantees:
            print(f"  Grantees: {', '.join(response.grantees)}")
        if response.data_masking_policy:
            masking_policy = response.data_masking_policy
            if masking_policy.predefined_expression:
                print(
                    f"  Data Masking Predefined Expression: {masking_policy.predefined_expression.name}"
                )
            elif masking_policy.routine:
                print(f"  Data Masking Routine: {masking_policy.routine}")

    except exceptions.NotFound:
        print(f"Error: Data policy '{data_policy_name}' not found.")
        print("Make sure the data policy ID, project ID, and location are correct.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

בדיקת הרשאות IAM במדיניות נתונים

כדי לקבל את מדיניות IAM למדיניות נתונים:

API

מבצעים קריאה ל-testIamPermissions.

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

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

const {DataPolicyServiceClient} =
  require('@google-cloud/bigquery-datapolicies').v2;
const {status} = require('@grpc/grpc-js');

const client = new DataPolicyServiceClient();

/**
 * Get the IAM policy for a specified data policy resource from the BigQuery Data Policy API.
 * This is useful for auditing which members have which roles on the policy.
 *
 *
 * @param {string} projectId Google Cloud Project ID (For example, 'example-project-id')
 * @param {string} location Google Cloud Location (For example, 'us-central1')
 * @param {string} dataPolicyId The ID of the data policy (For example, 'example-data-policy-id')
 */
async function getIamPolicy(projectId, location, dataPolicyId) {
  const resourceName = client.dataPolicyPath(projectId, location, dataPolicyId);

  const request = {
    resource: resourceName,
  };

  try {
    const [policy] = await client.getIamPolicy(request);
    console.log(
      'Successfully retrieved IAM policy for data policy %s:',
      resourceName,
    );
    console.log(JSON.stringify(policy, null, 2));
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: Data Policy '${dataPolicyId}' not found in location '${location}' of project '${projectId}'. ` +
          'Make sure the data policy exists and the resource name is correct.',
      );
    } else {
      console.error(
        `Error getting IAM policy for data policy '${dataPolicyId}':`,
        err,
      );
    }
  }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

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

from google.api_core import exceptions
from google.cloud import bigquery_datapolicies_v2
from google.iam.v1 import iam_policy_pb2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def get_data_policy_iam_policy(
    project_id: str,
    location: str,
    data_policy_id: str,
) -> None:
    """Get the IAM policy for a specified data policy resource from the BigQuery Data Policy API.
    This is useful for auditing which members have which roles on the policy.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the data policy (for example, "us").
        data_policy_id: The ID of the data policy.
    """

    resource_name = client.data_policy_path(
        project=project_id,
        location=location,
        data_policy=data_policy_id,
    )

    request = iam_policy_pb2.GetIamPolicyRequest(resource=resource_name)

    try:
        policy = client.get_iam_policy(request=request)

        print(f"Successfully retrieved IAM policy for data policy: {resource_name}")
        print("Policy Version:", policy.version)
        if policy.bindings:
            print("Policy Bindings:")
            for binding in policy.bindings:
                print(f"  Role: {binding.role}")
                print(f"  Members: {', '.join(binding.members)}")
                if binding.condition.expression:
                    print(f"  Condition: {binding.condition.expression}")
        else:
            print("No bindings found in the policy.")

    except exceptions.NotFound:
        print(f"Error: Data policy '{resource_name}' not found.")
        print("Make sure the project ID, location, and data policy ID are correct.")
    except exceptions.GoogleAPIError as e:
        print(f"An API error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

הצגת רשימה של כללי מדיניות בנושא נתונים

כדי לפרט את כללי המדיניות בנושא נתונים:

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

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

const {DataPolicyServiceClient} =
  require('@google-cloud/bigquery-datapolicies').v2;
const {status} = require('@grpc/grpc-js');

const client = new DataPolicyServiceClient();

/**
 * Lists all data policies in a given project and location.
 *
 * Data policies define rules for data masking, row-level security, or column-level security.
 *
 * @param {string} projectId The Google Cloud project ID. (for example, 'example-project-id')
 * @param {string} location The Google Cloud location of the data policies. (For example, 'us')
 */
async function listDataPolicies(projectId, location) {
  const parent = `projects/${projectId}/locations/${location}`;

  const request = {
    parent,
  };

  try {
    console.log(
      `Listing data policies for project: ${projectId} in location: ${location}`,
    );
    const [dataPolicies] = await client.listDataPolicies(request);

    if (dataPolicies.length === 0) {
      console.log(
        `No data policies found in location ${location} for project ${projectId}.`,
      );
      return;
    }

    console.log('Data Policies:');
    for (const dataPolicy of dataPolicies) {
      console.log(`  Data Policy Name: ${dataPolicy.name}`);
      console.log(`    ID: ${dataPolicy.dataPolicyId}`);
      console.log(`    Type: ${dataPolicy.dataPolicyType}`);
      if (dataPolicy.policyTag) {
        console.log(`    Policy Tag: ${dataPolicy.policyTag}`);
      }
      if (dataPolicy.grantees && dataPolicy.grantees.length > 0) {
        console.log(`    Grantees: ${dataPolicy.grantees.join(', ')}`);
      }
      if (dataPolicy.dataMaskingPolicy) {
        if (dataPolicy.dataMaskingPolicy.predefinedExpression) {
          console.log(
            `    Data Masking Predefined Expression: ${dataPolicy.dataMaskingPolicy.predefinedExpression}`,
          );
        } else if (dataPolicy.dataMaskingPolicy.routine) {
          console.log(
            `    Data Masking Routine: ${dataPolicy.dataMaskingPolicy.routine}`,
          );
        }
      }
    }

    console.log(`Successfully listed ${dataPolicies.length} data policies.`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: The project or location '${location}' for project '${projectId}' was not found. ` +
          'Make sure the project ID and location are correct and that the BigQuery Data Policy API is enabled.',
      );
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(
        `Error: Permission denied when listing data policies for project '${projectId}' in location '${location}'. ` +
          'Make sure the authenticated account has the necessary permissions (For example, bigquery.datapolicies.list).',
      );
    } else {
      console.error(`Error listing data policies: ${err.message}`);
    }
  }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

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

import google.api_core.exceptions
from google.cloud import bigquery_datapolicies_v2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def list_data_policies(project_id: str, location: str) -> None:
    """Lists all data policies in a specified project.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location of the data policies (for example, "us", "us-central1").
    """

    parent = f"projects/{project_id}/locations/{location}"

    try:
        request = bigquery_datapolicies_v2.ListDataPoliciesRequest(parent=parent)

        print(
            f"Listing data policies for project '{project_id}' in location '{location}':"
        )
        page_result = client.list_data_policies(request=request)

        found_policies = False
        for data_policy in page_result:
            found_policies = True
            print(f"  Data Policy Name: {data_policy.name}")
            print(f"  Data Policy ID: {data_policy.data_policy_id}")
            print(f"  Data Policy Type: {data_policy.data_policy_type.name}")
            if data_policy.policy_tag:
                print(f"  Policy Tag: {data_policy.policy_tag}")
            if data_policy.grantees:
                print(f"  Grantees: {', '.join(data_policy.grantees)}")
            print("-" * 20)

        if not found_policies:
            print("No data policies found.")

    except google.api_core.exceptions.NotFound as e:
        print(f"Error: The specified project or location was not found or accessible.")
        print(f"Details: {e}")
        print(
            "Make sure the project ID and location are correct and you have the necessary permissions."
        )
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

עדכון מדיניות בנושא נתונים

למשתמש או לחשבון השירות שמעדכנים את מדיניות הנתונים צריכה להיות ההרשאה bigquery.dataPolicies.update. אם מעדכנים את תג המדיניות שמדיניות הנתונים משויכת אליו, צריך גם את ההרשאה datacatalog.taxonomies.get.

אם אתם מעדכנים את חשבונות המשתמש שמשויכים למדיניות הנתונים, אתם צריכים את ההרשאה bigquery.dataPolicies.setIamPolicy.

ההרשאות bigquery.dataPolicies.update ו-bigquery.dataPolicies.setIamPolicy כלולות בתפקידים BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery), אדמין של BigQuery והבעלים של נתוני BigQuery. ההרשאה datacatalog.taxonomies.get כלולה בתפקידים Data Catalog Admin ו-Data Catalog Viewer.

המסוף

  1. פותחים את הדף Policy tag taxonomies במסוףGoogle Cloud .

    פתיחת הדף Policy tag taxonomies

  2. לוחצים על שם הטקסונומיה כדי לפתוח אותה.
  3. בוחרים תג מדיניות.
  4. לוחצים על ניהול מדיניות בנושא נתונים.
  5. אפשר גם לשנות את כלל המיסוך.
  6. אם רוצים, מוסיפים או מסירים ישויות.
  7. לוחצים על שליחה.

API

כדי לשנות את כלל מיסוך הנתונים, צריך לבצע קריאה ל-method‏ patch ולהעביר משאב DataPolicy עם שדה dataMaskingPolicy מעודכן.

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

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

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

const datapolicy = require('@google-cloud/bigquery-datapolicies');
const {DataPolicyServiceClient} = datapolicy.v2;
const protos = datapolicy.protos.google.cloud.bigquery.datapolicies.v2;
const {status} = require('@grpc/grpc-js');

const client = new DataPolicyServiceClient();

/**
 * Updates the data masking configuration of an existing data policy.
 * This example demonstrates how to use a FieldMask to selectively update the
 * `data_masking_policy` (for example, changing the masking expression from
 * ALWAYS_NULL to SHA256) without affecting other fields or recreating the policy.
 *
 * @param {string} projectId The Google Cloud project ID (For example, 'example-project-id').
 * @param {string} location The location of the data policy (For example, 'us').
 * @param {string} dataPolicyId The ID of the data policy to update (For example, 'example-data-policy-id').
 */
async function updateDataPolicy(projectId, location, dataPolicyId) {
  const resourceName = client.dataPolicyPath(projectId, location, dataPolicyId);

  const getRequest = {
    name: resourceName,
  };

  try {
    // To prevent race conditions, use the policy's etag in the update.
    const [currentDataPolicy] = await client.getDataPolicy(getRequest);
    const currentETag = currentDataPolicy.etag;

    // This example transitions a masking rule from ALWAYS_NULL to SHA256.
    const dataPolicy = {
      name: resourceName,
      etag: currentETag,
      dataMaskingPolicy: {
        predefinedExpression:
          protos.DataMaskingPolicy.PredefinedExpression.SHA256,
      },
    };

    // Use a field mask to selectively update only the data masking policy.
    const updateMask = {
      paths: ['data_masking_policy'],
    };

    const request = {
      dataPolicy,
      updateMask,
    };

    const [response] = await client.updateDataPolicy(request);
    console.log(`Successfully updated data policy: ${response.name}`);
    console.log(
      `New masking expression: ${response.dataMaskingPolicy.predefinedExpression}`,
    );
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: Data policy '${resourceName}' not found. ` +
          'Make sure the data policy exists and the project, location, and data policy ID are correct.',
      );
    } else {
      console.error('Error updating data policy:', err.message, err);
    }
  }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

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

from google.api_core import exceptions
from google.cloud import bigquery_datapolicies_v2
from google.protobuf import field_mask_pb2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def update_data_policy(project_id: str, location: str, data_policy_id: str) -> None:
    """Updates the data masking configuration of an existing data policy.

    This example demonstrates how to use a FieldMask to selectively update the
    `data_masking_policy` (for example, changing the masking expression from
    ALWAYS_NULL to SHA256) without affecting other fields or recreating the policy.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location (for example, "us") of the data policy.
        data_policy_id: The ID of the data policy to update.
    """

    data_policy_name = client.data_policy_path(
        project=project_id,
        location=location,
        data_policy=data_policy_id,
    )

    # To prevent race conditions, use the policy's etag in the update.
    existing_policy = client.get_data_policy(name=data_policy_name)

    # This example transitions a masking rule from ALWAYS_NULL to SHA256.
    updated_data_policy = bigquery_datapolicies_v2.DataPolicy(
        name=data_policy_name,
        data_masking_policy=bigquery_datapolicies_v2.DataMaskingPolicy(
            predefined_expression=bigquery_datapolicies_v2.DataMaskingPolicy.PredefinedExpression.SHA256
        ),
        etag=existing_policy.etag,
    )

    # Use a field mask to selectively update only the data masking policy.
    update_mask = field_mask_pb2.FieldMask(paths=["data_masking_policy"])
    request = bigquery_datapolicies_v2.UpdateDataPolicyRequest(
        data_policy=updated_data_policy,
        update_mask=update_mask,
    )

    try:
        response = client.update_data_policy(request=request)
        print(f"Successfully updated data policy: {response.name}")
        print(f"New data policy type: {response.data_policy_type.name}")
        if response.data_masking_policy:
            print(
                f"New masking expression: {response.data_masking_policy.predefined_expression.name}"
            )
    except exceptions.NotFound:
        print(f"Error: Data policy '{data_policy_name}' not found.")
        print("Make sure the data policy ID and location are correct.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

מחיקת מדיניות בנושא נתונים

למשתמש או לחשבון השירות שיוצרים מדיניות נתונים צריכה להיות ההרשאה bigquery.dataPolicies.delete. ההרשאה הזו כלולה בתפקידים BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery), BigQuery Admin (אדמין של BigQuery) ו-BigQuery Data Owner (הבעלים של נתוני BigQuery).

המסוף

  1. פותחים את הדף Policy tag taxonomies במסוףGoogle Cloud .

    פתיחת הדף Policy tag taxonomies

  2. לוחצים על שם הטקסונומיה כדי לפתוח אותה.
  3. בוחרים תג מדיניות.
  4. לוחצים על ניהול מדיניות בנושא נתונים.
  5. לוחצים על לצד מדיניות הנתונים שרוצים למחוק.
  6. לוחצים על שליחה.
  7. לוחצים על אישור.

API

כדי למחוק מדיניות נתונים, צריך לבצע קריאה ל-method‏ delete.

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

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

const {DataPolicyServiceClient} =
  require('@google-cloud/bigquery-datapolicies').v2;
const {status} = require('@grpc/grpc-js');

const client = new DataPolicyServiceClient();

/**
 * Deletes a data policy from the BigQuery Data Policy API, which is identified by its project ID, location, and data policy ID.
 *
 * @param {string} projectId The Google Cloud project ID.
 * @param {string} location The Google Cloud location (For example, 'us').
 * @param {string} dataPolicyId The ID of the data policy to delete (For example, 'example-data-policy').
 */
async function deleteDataPolicy(projectId, location, dataPolicyId) {
  const name = client.dataPolicyPath(projectId, location, dataPolicyId);

  const request = {
    name,
  };

  try {
    await client.deleteDataPolicy(request);
    console.log(`Successfully deleted data policy: ${name}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Data policy ${name} not found. Make sure the data policy ID and location are correct.`,
      );
    } else {
      console.error(`Error deleting data policy ${name}:`, err.message);
    }
  }
}

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

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

from google.api_core import exceptions as core_exceptions
from google.cloud import bigquery_datapolicies_v2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def delete_data_policy(project_id: str, location: str, data_policy_id: str) -> None:
    """Deletes a data policy from the BigQuery Data Policy APIs.

    Args:
        project_id: The Google Cloud project ID.
        location: The location of the data policy (for example, "us").
        data_policy_id: The ID of the data policy to delete.
    """

    name = client.data_policy_path(
        project=project_id, location=location, data_policy=data_policy_id
    )

    try:
        client.delete_data_policy(name=name)
        print(f"Successfully deleted data policy: {name}")
    except core_exceptions.NotFound:
        print(f"Data policy '{name}' not found. It may have already been deleted.")
    except Exception as e:
        print(f"Error deleting data policy '{name}': {e}")

החלת מדיניות נתונים על עמודה כדי להסתיר נתונים

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

עבודה עם כללי מדיניות בנושא נתונים

אפשר ליצור, לעדכן ולמחוק מדיניות נתונים באמצעות BigQuery Data Policy API. כדי להחיל מדיניות נתונים ישירות על עמודה, אי אפשר להשתמש בדף תג מדיניות taxonomies במסוף Google Cloud .

כדי לעבוד עם מדיניות נתונים, משתמשים במשאב v2.projects.locations.datapolicies.

יצירת מדיניות בנושא נתונים

למשתמש או לחשבון השירות שיוצרים מדיניות נתונים צריכה להיות ההרשאה bigquery.dataPolicies.create.

ההרשאה bigquery.dataPolicies.create כלולה בתפקידים BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery),‏ BigQuery Admin (אדמין של BigQuery) ו-BigQuery Data Owner (הבעלים של נתונים ב-BigQuery). ההרשאה datacatalog.taxonomies.get כלולה בתפקידים Data Catalog Admin ו-Data Catalog Viewer.

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

אם אתם משתמשים בהסתרת נתונים בהתאמה אישית, צריך להעניק למשתמשים את התפקיד 'בעלים של נתונים ב-BigQuery' כדי לוודא שיש להם את ההרשאות הנדרשות גם לשגרות וגם למדיניות נתונים.

API

כדי ליצור מדיניות לגבי נתונים, צריך להפעיל את method‏ create. צריך להעביר משאב DataPolicy שעומד בדרישות הבאות:

  • השדה dataPolicyType מוגדר ל-DATA_MASKING_POLICY או ל-RAW_DATA_ACCESS_POLICY.
  • השדה dataMaskingPolicy מזהה את כלל או שגרת מיסוך הנתונים שבהם צריך להשתמש.
  • בשדה dataPolicyId מזינים שם למדיניות הנתונים, שיהיה ייחודי בפרויקט שבו נמצאת מדיניות הנתונים.

SQL

כדי ליצור מדיניות גישה לנתונים עם גישה מוסתרת, משתמשים בהצהרת CREATE DATA_POLICY ומגדירים את הערך של data_policy_type ל-DATA_MASKING_POLICY:

    CREATE[ OR REPLACE] DATA_POLICY [IF NOT EXISTS] `myproject.region-us.data_policy_name`
    OPTIONS (
      data_policy_type="DATA_MASKING_POLICY",
      masking_expression="ALWAYS_NULL"
    );

כדי ליצור מדיניות גישה לנתונים עם גישה גולמית, משתמשים בהצהרה CREATE DATA_POLICY ומגדירים את הערך של data_policy_type ל-RAW_DATA_ACCESS_POLICY:

    CREATE[ OR REPLACE] DATA_POLICY [IF NOT EXISTS] `myproject.region-us.data_policy_name`
    OPTIONS (data_policy_type="RAW_DATA_ACCESS_POLICY");

אם לא מציינים את הערך של data_policy_type, ערך ברירת המחדל הוא RAW_DATA_ACCESS_POLICY.

    CREATE[ OR REPLACE] DATA_POLICY [IF NOT EXISTS] myproject.region-us.data_policy_name;

  • השדה data_policy_type מוגדר ל-DATA_MASKING_POLICY או ל-RAW_DATA_ACCESS_POLICY. אי אפשר לעדכן את השדה הזה אחרי שיוצרים את מדיניות הנתונים.
  • השדה masking_expression מזהה את כלל או שגרת מיסוך הנתונים שבהם צריך להשתמש.

עדכון מדיניות בנושא נתונים

למשתמש או לחשבון השירות שמעדכנים את מדיניות הנתונים צריכה להיות ההרשאה bigquery.dataPolicies.update.

ההרשאה bigquery.dataPolicies.update כלולה בתפקידים BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery),‏ BigQuery Admin (אדמין של BigQuery) ו-BigQuery Data Owner (הבעלים של נתונים ב-BigQuery).

API

כדי לשנות את כלל מיסוך הנתונים, צריך לבצע קריאה ל-method‏ patch ולהעביר משאב DataPolicy עם שדה dataMaskingPolicy מעודכן.

SQL

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

    ALTER DATA_POLICY `myproject.region-us.data_policy_name`
    SET OPTIONS (
      data_policy_type="DATA_MASKING_POLICY",
      masking_expression="SHA256"
    );

אפשר גם להעניק גישה פרטנית לבקרת גישה למדיניות נתונים.

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

כדי להגדיר מקבלי הרשאות במדיניות נתונים, משתמשים ב-method ‏v2 patch . כדי לנהל את ההרשאות של מדיניות הנתונים, משתמשים ב-method ‏v1 setIamPolicy.

API

כדי להעניק הרשאת גישה פרטנית לכללי מדיניות בנושא נתונים, צריך לבצע קריאה ל-method‏ patch ולהעביר משאב DataPolicy עם שדה grantees מעודכן.

SQL

כדי להעניק בקרת גישה פרטנית לנתונים באמצעות כללי מדיניות, משתמשים בהצהרת GRANT FINE_GRAINED_READ כדי להוסיף את grantees. לדוגמה:

    GRANT FINE_GRAINED_READ ON DATA_POLICY `myproject.region-us.data_policy_name`
    TO "principal://goog/subject/user1@example.com","principal://goog/subject/user2@example.com"

כדי לבטל את הגישה לבקרת גישה פרטנית ממדיניות נתונים, משתמשים בהצהרה REVOKE FINE_GRAINED_READ כדי להסיר את grantees. לדוגמה:

    REVOKE FINE_GRAINED_READ ON DATA_POLICY `myproject.region-us.data_policy_name`
    FROM "principal://goog/subject/user1@example.com","principal://goog/subject/user2@example.com"

מחיקת מדיניות בנושא נתונים

למשתמש או לחשבון השירות שיוצרים מדיניות נתונים צריכה להיות ההרשאה bigquery.dataPolicies.delete. ההרשאה הזו כלולה בתפקידים BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery), BigQuery Admin (אדמין של BigQuery) ו-BigQuery Data Owner (הבעלים של נתוני BigQuery).

API

כדי למחוק מדיניות נתונים, צריך לבצע קריאה ל-method‏ delete.

SQL

כדי למחוק מדיניות בנושא נתונים, משתמשים בהצהרה DROP DATA_POLICY:

    DROP DATA_POLICY `myproject.region-us.data_policy_name`;

הקצאת מדיניות נתונים ישירות בעמודה

אתם יכולים להקצות מדיניות נתונים ישירות לעמודה בלי להשתמש בתגי מדיניות.

לפני שמתחילים

כדי לקבל את ההרשאות שנדרשות להקצאת מדיניות נתונים ישירות לעמודה, צריך לבקש מהאדמין להקצות לכם את תפקיד ה-IAM‏ BigQuery Data Policy Admin (אדמין של מדיניות נתונים ב-BigQuery) ‏(roles/bigquerydatapolicy.admin) בטבלה. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

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

ההרשאות הנדרשות

כדי להקצות מדיניות נתונים ישירות לעמודה, צריך את ההרשאות הבאות:

  • bigquery.tables.update
  • bigquery.tables.setColumnDataPolicy
  • bigquery.dataPolicies.attach

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

הקצאת מדיניות בנושא נתונים

כדי להקצות מדיניות נתונים ישירות לעמודה, אפשר לבצע אחת מהפעולות הבאות:

SQL

כדי לצרף מדיניות נתונים לעמודה, משתמשים בהצהרות DDL‏ CREATE TABLE, ALTER TABLE ADD COLUMN, או ALTER COLUMN SET OPTIONS.

בדוגמה הבאה משתמשים בהצהרה CREATE TABLE ומגדירים מדיניות נתונים בעמודה:

    CREATE TABLE myproject.table1 (
    name INT64 OPTIONS (data_policies=["{'name':'myproject.region-us.data_policy_name1'}",
                                      "{'name':'myproject.region-us.data_policy_name2'}"])
    );

בדוגמה הבאה נעשה שימוש ב-ALTER COLUMN SET OPTIONS כדי להוסיף מדיניות נתונים לעמודה קיימת בטבלה:

ALTER TABLE myproject.table1
ALTER COLUMN column_name SET OPTIONS (
  data_policies += ["{'name':'myproject.region-us.data_policy_name1'}",
                    "{'name':'myproject.region-us.data_policy_name2'}"]);

API

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

ביטול ההקצאה של מדיניות בנושא נתונים

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

SQL

כדי לנתק מדיניות נתונים מעמודה, משתמשים בהצהרת DDL‏ ALTER COLUMN SET OPTIONS.

בדוגמה הבאה נעשה שימוש ב-ALTER COLUMN SET OPTIONS כדי להסיר את כל מדיניות הנתונים מעמודה קיימת בטבלה:

ALTER TABLE myproject.table1
ALTER COLUMN column_name SET OPTIONS (
  data_policies = []);

בדוגמה הבאה נעשה שימוש ב-ALTER COLUMN SET OPTIONS כדי להחליף מדיניות נתונים מעמודה קיימת בטבלה:

ALTER TABLE myproject.table1
ALTER COLUMN column_name SET OPTIONS (
  data_policies = ["{'name':'myproject.region-us.new_data_policy_name'}"]);

API

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

מגבלות

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

  • חובה להשתמש במשאב v2.projects.locations.datapolicies.
  • אי אפשר להחיל על אותה עמודה גם תגי מדיניות וגם מדיניות נתונים.
  • אפשר לצרף עד שמונה מדיניות נתונים לעמודה.
  • טבלה יכולה להפנות ל-1,000 מדיניות ייחודית לכל היותר בנושא נתונים דרך העמודות שלה.
  • כל שאילתה יכולה להפנות לעד 2,000 מדיניות נתונים.
  • אפשר למחוק מדיניות נתונים רק אם אף עמודה בטבלה לא מפנה אליה.
  • אם למשתמש יש רק את התפקיד maskedAccess, הקריאה ל-API‏ tabledata.list תיכשל.
  • פעולות העתקה של טבלאות נכשלות בטבלאות שמוגנות על ידי מדיניות נתוני עמודות אם למשתמש אין גישה לנתונים הגולמיים.
  • פעולות העתקה של טבלאות בין אזורים לא תומכות בטבלאות שמוגנות על ידי מדיניות נתונים של עמודות.
  • מדיניות לגבי נתוני עמודות לא זמינה באזורים של BigQuery Omni.
  • הדיאלקט 'SQL מדור קודם' נכשל אם בטבלת היעד יש מדיניות לגבי נתוני עמודות.
  • משימות טעינה לא תומכות בסכימות שצוינו על ידי המשתמש עם מדיניות נתונים של עמודות.
  • אם מחליפים טבלת יעד, המערכת מסירה מהטבלה את כל תגי המדיניות הקיימים, אלא אם משתמשים בדגל --destination_schema כדי לציין סכימה עם מדיניות נתוני עמודות.
  • כברירת מחדל, הסתרת נתונים לא תומכת בעמודות עם חלוקה למחיצות או עם אשכולות. זוהי מגבלה כללית של מיסוך נתונים, ולא מגבלה שספציפית למדיניות של עמודות נתונים. הסתרת נתונים בעמודות מחולקות או מקובצות יכולה להגדיל באופן משמעותי את עלויות השאילתות.
  • אי אפשר להקצות מדיניות נתונים ישירות לעמודה בטבלאות אובייקטים, בטבלאות חיצוניות שאינן BigLake, בטבלאות חיצוניות של Apache Iceberg וב-Delta Lake.
  • אפשר להעניק גישה פרטנית רק ברמת מדיניות הנתונים. מידע נוסף זמין במאמר בנושא עדכון מדיניות בנושא נתונים.
  • אי אפשר לבטל את ההקצאה של מדיניות הנתונים האחרונה שנותרה בעמודה באמצעות BigQuery Data Policy API. אפשר לבטל את ההקצאה של מדיניות הנתונים האחרונה שנותרה בעמודה באמצעות הצהרת ה-DDL‏ ALTER COLUMN SET OPTIONS.