שימוש במניעת גישה ציבורית

סקירה כללית

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

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

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

קבלת התפקידים הנדרשים

כדי לנהל את מדיניות הארגון למניעת גישה ציבורית לנתונים ברמת הפרויקט, התיקייה או הארגון, צריך לבקש מהאדמין להקצות לכם את התפקיד Organization Policy Administrator (אדמין מדיניות הארגון) ‏(roles/orgpolicy.policyAdmin) בארגון. התפקיד המוגדר מראש הזה מכיל את ההרשאות שדרושות לניהול מניעת גישה ציבורית ברמת הפרויקט, התיקייה או הארגון. מידע על ההרשאות שכלולות בתפקיד הזה מופיע בפרטים על התפקיד אדמין ארגוני.

כדי לנהל את ההגדרה של מניעת הגישה הציבורית לנתונים בקטגוריה מסוימת, צריך לבקש מהאדמין להקצות לכם את התפקיד 'אדמין לניהול אחסון' (roles/storage.admin) בקטגוריה. התפקיד הזה מכיל את ההרשאות שנדרשות לניהול מניעת גישה ציבורית לקטגוריה. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

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

  • storage.buckets.update
  • storage.buckets.setIamPolicy

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

שיקולים לבדיקה

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

שימוש בהגדרת הקטגוריה

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

הגדרה של מניעת גישה ציבורית

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

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

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

  3. בדף Bucket details, לוחצים על הכרטיסייה Permissions.

  4. בכרטיס Public access, לוחצים על Prevent public access כדי לאכוף מניעת גישה ציבורית, או על Allow Public access כדי להסיר את מניעת הגישה הציבורית.

  5. לוחצים על אישור.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בפקודה gcloud storage buckets update עם הדגל המתאים:

gcloud storage buckets update gs://BUCKET_NAME FLAG

כאשר:

  • BUCKET_NAME הוא שם הקטגוריה הרלוונטית. לדוגמה, my-bucket.

  • FLAG הוא --public-access-prevention כדי להפעיל מניעת גישה ציבורית, או --no-public-access-prevention כדי להשבית אותה.

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

Updating gs://my-bucket/...
  Completed 1  

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

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

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.public_access_prevention =
      gcs::PublicAccessPreventionEnforced();
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

  std::cout << "Public Access Prevention is set to 'enforced' for "
            << updated->name() << "\n";
}

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.public_access_prevention =
      gcs::PublicAccessPreventionInherited();
  auto updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

  std::cout << "Public Access Prevention is set to 'inherited' for "
            << updated->name() << "\n";
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

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

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class SetPublicAccessPreventionEnforcedSample
{
    public Bucket SetPublicAccessPreventionEnforced(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        // Set public access prevention to "enforced" for the bucket.
        bucket.IamConfiguration.PublicAccessPrevention = "enforced";
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Public access prevention is 'enforced' for {bucketName}.");
        return bucket;
    }
}

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class SetPublicAccessPreventionInheritedSample
{
    public Bucket SetPublicAccessPreventionInherited(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        // Sets public access prevention to "inherited" for the bucket.
        bucket.IamConfiguration.PublicAccessPrevention = "inherited";
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Public access prevention is 'inherited' for {bucketName}.");
        return bucket;
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setPublicAccessPreventionEnforced sets public access prevention to
// "enforced" for the bucket.
func setPublicAccessPreventionEnforced(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setPublicAccessPrevention := storage.BucketAttrsToUpdate{
		PublicAccessPrevention: storage.PublicAccessPreventionEnforced,
	}
	if _, err := bucket.Update(ctx, setPublicAccessPrevention); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is 'enforced' for %v", bucketName)
	return nil
}

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setPublicAccessPreventionInherited sets public access prevention to
// "inherited" for the bucket.
func setPublicAccessPreventionInherited(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setPublicAccessPrevention := storage.BucketAttrsToUpdate{
		PublicAccessPrevention: storage.PublicAccessPreventionInherited,
	}
	if _, err := bucket.Update(ctx, setPublicAccessPrevention); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is 'inherited' for %v", bucketName)
	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

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

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

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetPublicAccessPreventionEnforced {
  public static void setPublicAccessPreventionEnforced(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    // Enforces public access prevention for the bucket
    bucket.toBuilder()
        .setIamConfiguration(
            BucketInfo.IamConfiguration.newBuilder()
                .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)
                .build())
        .build()
        .update();

    System.out.println("Public access prevention is set to enforced for " + bucketName);
  }
}

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetPublicAccessPreventionInherited {
  public static void setPublicAccessPreventionInherited(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    // Sets public access prevention to 'inherited' for the bucket
    bucket.toBuilder()
        .setIamConfiguration(
            BucketInfo.IamConfiguration.newBuilder()
                .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED)
                .build())
        .build()
        .update();

    System.out.println("Public access prevention is set to 'inherited' for " + bucketName);
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

// Enforces public access prevention for the bucket
async function setPublicAccessPreventionEnforced() {
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      publicAccessPrevention: 'enforced',
    },
  });

  console.log(
    `Public access prevention is set to enforced for ${bucketName}.`
  );
}

setPublicAccessPreventionEnforced();

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();
async function setPublicAccessPreventionInherited() {
  // Sets public access prevention to 'inherited' for the bucket
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      publicAccessPrevention: 'inherited',
    },
  });

  console.log(`Public access prevention is 'inherited' for ${bucketName}.`);
}

setPublicAccessPreventionInherited();

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket Public Access Prevention to enforced.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_public_access_prevention_enforced(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'iamConfiguration' => [
            'publicAccessPrevention' => 'enforced'
        ]
    ]);

    printf(
        'Public Access Prevention has been set to enforced for %s.' . PHP_EOL,
        $bucketName
    );
}

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket Public Access Prevention to inherited.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_public_access_prevention_inherited(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'iamConfiguration' => [
            'publicAccessPrevention' => 'inherited'
        ]
    ]);

    printf(
        'Public Access Prevention has been set to inherited for %s.' . PHP_EOL,
        $bucketName
    );
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

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

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

from google.cloud import storage
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_ENFORCED


def set_public_access_prevention_enforced(bucket_name):
    """Enforce public access prevention for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    bucket.iam_configuration.public_access_prevention = (
        PUBLIC_ACCESS_PREVENTION_ENFORCED
    )
    bucket.patch()

    print(f"Public access prevention is set to enforced for {bucket.name}.")

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:


from google.cloud import storage
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_INHERITED


def set_public_access_prevention_inherited(bucket_name):
    """Sets the public access prevention status to inherited, so that the bucket inherits its setting from its parent project."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    bucket.iam_configuration.public_access_prevention = (
        PUBLIC_ACCESS_PREVENTION_INHERITED
    )
    bucket.patch()

    print(f"Public access prevention is 'inherited' for {bucket.name}.")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

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

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

def set_public_access_prevention_enforced bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.public_access_prevention = :enforced

  puts "Public access prevention is set to enforced for #{bucket_name}."
end

הדוגמה הבאה מגדירה את מניעת הגישה הציבורית כ-inherited בקטגוריה מסוימת:

def set_public_access_prevention_inherited bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.public_access_prevention = :inherited

  puts "Public access prevention is 'inherited' for #{bucket_name}."
end

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

     {
        "iamConfiguration": {
          "publicAccessPrevention": "STATE",
        }
      }
    

    כאשר <var>STATE</var> הוא enforced או inherited.

  3. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית PATCH שכוללת את fields הרצוי:

    curl -X PATCH --data-binary @JSON_FILE_NAME \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=iamConfiguration"

    כאשר:

    • JSON_FILE_NAME הוא הנתיב לקובץ JSON שיצרתם בשלב הקודם.
    • BUCKET_NAME הוא שם הקטגוריה הרלוונטית. לדוגמה, my-bucket.

‫API בפורמט XML

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

צפייה בסטטוס של מניעת גישה ציבורית

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

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

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

  3. לוחצים על הכרטיסייה Permissions.

  4. בכרטיס Public access מוצג הסטטוס של הקטגוריה.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בפקודה gcloud storage buckets describe עם הדגל --format:

gcloud storage buckets describe gs://BUCKET_NAME --format="default(public_access_prevention)"

כאשר BUCKET_NAME הוא השם של הקטגוריה שבסטטוס שלה אתם רוצים לצפות. לדוגמה, my-bucket.

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

public_access_prevention:inherited

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!bucket_metadata) throw std::move(bucket_metadata).status();

  if (bucket_metadata->has_iam_configuration() &&
      bucket_metadata->iam_configuration()
          .public_access_prevention.has_value()) {
    std::cout
        << "Public Access Prevention is "
        << *bucket_metadata->iam_configuration().public_access_prevention
        << " for bucket " << bucket_metadata->name() << "\n";
  } else {
    std::cout << "Public Access Prevention is not set for "
              << bucket_metadata->name() << "\n";
  }
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetPublicAccessPreventionSample
{
    public string GetPublicAccessPrevention(string bucketName = "your-unique-bucket-name")
    {
        // Gets Bucket Metadata and prints publicAccessPrevention value (either "unspecified" or "enforced").
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        var publicAccessPrevention = bucket.IamConfiguration.PublicAccessPrevention;

        Console.WriteLine($"Public access prevention is {publicAccessPrevention} for {bucketName}.");
        return publicAccessPrevention;
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getPublicAccessPrevention gets the current public access prevention setting
// for the bucket, either "enforced" or "inherited".
func getPublicAccessPrevention(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is %s for %v", attrs.PublicAccessPrevention, bucketName)
	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

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

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class GetPublicAccessPrevention {
  public static void getPublicAccessPrevention(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or
    // 'enforced').
    BucketInfo.PublicAccessPrevention publicAccessPrevention =
        bucket.getIamConfiguration().getPublicAccessPrevention();

    System.out.println(
        "Public access prevention is set to "
            + publicAccessPrevention.getValue()
            + " for "
            + bucketName);
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getPublicAccessPrevention() {
  // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or 'enforced').
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(
    `Public access prevention is ${metadata.iamConfiguration.publicAccessPrevention} for ${bucketName}.`
  );
}

getPublicAccessPrevention();

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

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

use Google\Cloud\Storage\StorageClient;

/**
 * Get the Public Access Prevention setting for a bucket
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_public_access_prevention(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $iamConfiguration = $bucket->info()['iamConfiguration'];

    printf(
        'The bucket public access prevention is %s for %s.' . PHP_EOL,
        $iamConfiguration['publicAccessPrevention'],
        $bucketName
    );
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

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

from google.cloud import storage


def get_public_access_prevention(bucket_name):
    """Gets the public access prevention setting (either 'inherited' or 'enforced') for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    iam_configuration = bucket.iam_configuration

    print(
        f"Public access prevention is {iam_configuration.public_access_prevention} for {bucket.name}."
    )

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

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

def get_public_access_prevention bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  puts "Public access prevention is '#{bucket.public_access_prevention}' for #{bucket_name}."
end

ממשקי API ל-REST

API ל-JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. משתמשים ב- cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית GET שכוללת את fields הרצוי:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=iamConfiguration"

    כאשר BUCKET_NAME הוא השם של הקטגוריה הרלוונטית. לדוגמה, my-bucket.

    התגובה אמורה להיות דומה לדוגמה הבאה:

     {
      "iamConfiguration": {
          ...
          "publicAccessPrevention": "FLAG"
        }
      }

    כאשר FLAG הוא inherited או enforced.

‫API בפורמט XML

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

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

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

הגדרה של מניעת גישה ציבורית

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

המסוף

פועלים לפי ההוראות במאמר יצירה וניהול של מדיניות ארגון באמצעות האילוץ storage.publicAccessPrevention.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בפקודה gcloud beta resource-manager org-policies:

gcloud beta resource-manager org-policies STATE \
  constraints/storage.publicAccessPrevention \
  --RESOURCE RESOURCE_ID

כאשר:

  • STATE יכול לקבל את הערכים הבאים:

    • enable-enforce: אכיפה של מניעת גישה ציבורית למשאב.
    • disable-enforce: השבתה של מניעת הגישה הציבורית למשאב.
    • delete: הסרת האילוץ של מדיניות הארגון מהמשאב, כדי שהמשאב יירש את הערך של משאב ההורה שלו.
  • RESOURCE הוא המשאב שרוצים להגדיר לו מניעת גישה ציבורית. לדוגמה, organization, project או folder.

  • RESOURCE_ID הוא המזהה של המשאב. לדוגמה, 123456789012 למזהה ארגון, 245321 למזהה תיקייה או my-pet-project למזהה פרויקט.

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

הדוגמה הבאה היא של הפלט שמתקבל כשאתם משתמשים ב-disable-enforce:

etag: BwVJi0OOESU=
booleanPolicy: {}
constraint: constraints/storage.publicAccessPrevention

צפייה בסטטוס של מניעת גישה ציבורית

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

המסוף

פועלים לפי ההוראות במאמר יצירה וניהול של מדיניות ארגון באמצעות האילוץ storage.publicAccessPrevention.

במאמר פתרון בעיות מוסבר איך מקבלים מידע מפורט על שגיאות בנושא פעולות ב-Cloud Storage שנכשלו במסוף Google Cloud .

שורת הפקודה

משתמשים בפקודה describe --effective:

gcloud beta resource-manager org-policies describe \
  constraints/storage.publicAccessPrevention --effective \
  --RESOURCE RESOURCE_ID

כאשר:

  • RESOURCE הוא המשאב שבסטטוס מניעת הגישה הציבורית שלו אתם רוצים לצפות. לדוגמה, organization, project או folder.

  • RESOURCE_ID הוא המזהה של המשאב. לדוגמה, 123456789012 למזהה ארגון, 245321 למזהה תיקייה ו-my-pet-project למזהה פרויקט.

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

המאמרים הבאים