使用 Security Command Center API 管理安全来源

本指南将介绍如何使用 Security Command Center API 创建来源以生成发现结果。在您添加来源时,Security Command Center 会创建适当的来源并为它们分配相关权限。

Security Command Center 的 IAM 角色可以在组织、文件夹或项目级层授予。您能否查看、修改、创建或更新发现结果、资产和安全来源,取决于您获授予的访问权限级别。如需详细了解 Security Command Center 角色,请参阅访问权限控制

准备工作

在设置来源之前,您需要设置服务账号。如果您直接调用 Security Command Center API,请获取不记名令牌

创建来源

此示例展示了如何创建具有特定显示名称和说明的来源,这些名称和说明在 Security Command Center 信息中心内使用。

该服务器会自动为该来源分配一个 ID。

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()
# organization_id is the numeric ID of the organization. e.g.:
# organization_id = "111122222444"
org_name = f"organizations/{organization_id}"

created = client.create_source(
    request={
        "parent": org_name,
        "source": {
            "display_name": "Customized Display Name",
            "description": "A new custom source that does X",
        },
    }
)
print(f"Created Source: {created.name}")

Java

static Source createSource(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to create a source in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
    Source source =
        Source.newBuilder()
            .setDisplayName("Customized Display Name")
            .setDescription("A new custom source that does X")
            .build();

    CreateSourceRequest.Builder request =
        CreateSourceRequest.newBuilder().setParent(organizationName.toString()).setSource(source);

    // Call the API.
    Source response = client.createSource(request.build());

    System.out.println("Created Source: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
)

// createSource creates a new source for organization orgID. orgID is
// the numeric identifier of the organization
func createSource(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.CreateSourceRequest{
		Source: &securitycenterpb.Source{
			DisplayName: "Customized Display Name",
			Description: "A new custom source that does X",
		},
		Parent: fmt.Sprintf("organizations/%s", orgID),
	}
	source, err := client.CreateSource(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateSource: %w", err)
	}

	fmt.Fprintf(w, "New source created: %s\n", source.Name)
	fmt.Fprintf(w, "Display Name: %s\n", source.DisplayName)
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
// organizationId is numeric organization identifier.
/*
 * TODO(developer): Uncomment the following lines
 */
// const organizationId = "1234567777";
async function createSource() {
  const [source] = await client.createSource({
    source: {
      displayName: 'Customized Display Name',
      description: 'A new custom source that does X',
    },
    parent: client.organizationPath(organizationId),
  });
  console.log('New Source: %j', source);
}
createSource();

API

在 API 中,向 organizations.sources.create 方法发出请求:请求正文包含一个 Source 实例。

  POST https://securitycenter.googleapis.com/API_VERSION/organizations/ORGANIZATION_ID/sources -d

  {
    "name": "SOURCE_NAME",
    "description": "SOURCE_DESCRIPTION",
    "displayName": "DISPLAY_NAME"
  }

替换以下内容:

  • API_VERSION:您的目标 API 版本。
  • ORGANIZATION_ID:您的组织 ID。
  • SOURCE_NAME:来源的名称。
  • SOURCE_DESCRIPTION:来源的说明(最多 1024 个字符)。
  • DISPLAY_NAME:来源的显示名(介于 1 到 64 个字符之间)。

来源只有在生成发现结果后才会显示在 Security Command Center 信息中心内。您可以按照获取特定来源中的说明来验证其已创建。

更新来源

您可以在创建来源后更新其显示名和说明。您还可以使用字段掩码仅更新一个字段。以下示例使用字段掩码来仅更新显示名,而使说明保持不变。

Python

from google.cloud import securitycenter
from google.protobuf import field_mask_pb2

client = securitycenter.SecurityCenterClient()

# Field mask to only update the display name.
field_mask = field_mask_pb2.FieldMask(paths=["display_name"])

# 'source_name' is the resource path for a source that has been
# created previously (you can use list_sources to find a specific one).
# Its format is:
# source_name = "organizations/{organization_id}/sources/{source_id}"
# e.g.:
# source_name = "organizations/111122222444/sources/1234"
updated = client.update_source(
    request={
        "source": {"name": source_name, "display_name": "Updated Display Name"},
        "update_mask": field_mask,
    }
)
print(f"Updated Source: {updated}")

Java

static Source updateSource(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to update a source.
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");
    Source source =
        Source.newBuilder()
            .setDisplayName("Updated Display Name")
            .setName(sourceName.toString())
            .build();
    FieldMask updateMask = FieldMask.newBuilder().addPaths("display_name").build();

    UpdateSourceRequest.Builder request =
        UpdateSourceRequest.newBuilder().setSource(source).setUpdateMask(updateMask);

    // Call the API.
    Source response = client.updateSource(request.build());

    System.out.println("Updated Source: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// updateSource changes a sources display name to "New Display Name" for a
// specific source. sourceName is the full resource name of the source to be
// updated.
func updateSource(w io.Writer, sourceName string) error {
	// sourceName := "organizations/111122222444/sources/1234"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.UpdateSourceRequest{
		Source: &securitycenterpb.Source{
			Name:        sourceName,
			DisplayName: "New Display Name",
		},
		// Only update the display name field (if not set all mutable
		// fields of the source will be updated.
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"display_name"},
		},
	}
	source, err := client.UpdateSource(ctx, req)
	if err != nil {
		return fmt.Errorf("UpdateSource: %w", err)
	}
	fmt.Fprintf(w, "Source Name: %s, ", source.Name)
	fmt.Fprintf(w, "Display name: %s, ", source.DisplayName)
	fmt.Fprintf(w, "Description: %s\n", source.Description)

	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
// sourceName is the full resource path to the update target.
/*
 * TODO(developer): Uncomment the following lines
 */
// const sourceName = "organizations/111122222444/sources/1234";
async function updateSource() {
  const [source] = await client.updateSource({
    source: {
      name: sourceName,
      displayName: 'New Display Name',
    },
    // Only update the display name field (if not set all mutable
    // fields of the source will be updated.
    updateMask: {paths: ['display_name']},
  });
  console.log('Updated source: %j', source);
}

updateSource();

API

在 API 中,向 organizations.sources.patch 方法发出请求:请求正文包含一个 Source 实例。

  PATCH https://securitycenter.googleapis.com/API_VERSION/organizations/ORGANIZATION_ID/sources/SOURCE_ID?updateMask=displayName -d

  {
    "description": "SOURCE_DESCRIPTION",
    "displayName": "DISPLAY_NAME",
  }

替换以下内容:

  • API_VERSION:您的目标 API 版本。
  • ORGANIZATION_ID:您的组织 ID。
  • SOURCE_ID:来源 ID。如需了解如何检索来源 ID,请参阅获取来源 ID
  • SOURCE_DESCRIPTION:来源的说明(最多 1024 个字符)。
  • DISPLAY_NAME:来源的显示名(介于 1 到 64 个字符之间)。

在来源上设置 IAM 政策

创建来源后,请更新 Identity and Access Management (IAM) 政策以允许访问。

Python

from google.cloud import securitycenter
from google.iam.v1 import policy_pb2

client = securitycenter.SecurityCenterClient()

# 'source_name' is the resource path for a source that has been
# created previously (you can use list_sources to find a specific one).
# Its format is:
# source_name = "organizations/{organization_id}/sources/{source_id}"
# e.g.:
# source_name = "organizations/111122222444/sources/1234"
# Get the old policy so we can do an incremental update.
old_policy = client.get_iam_policy(request={"resource": source_name})
print(f"Old Policy: {old_policy}")

# Setup a new IAM binding.
binding = policy_pb2.Binding()
binding.role = "roles/securitycenter.findingsEditor"
# user_email is an e-mail address known to Cloud IAM (e.g. a gmail address).
# user_mail = user@somedomain.com
binding.members.append(f"user:{user_email}")

# Setting the e-tag avoids over-write existing policy
updated = client.set_iam_policy(
    request={
        "resource": source_name,
        "policy": {"etag": old_policy.etag, "bindings": [binding]},
    }
)

print(f"Updated Policy: {updated}")

Java

static Policy setIamPolicySource(SourceName sourceName, String userEmail) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // userEmail = "someuser@domain.com"
    // Set up IAM Policy for the user userMail to use the role findingsEditor.
    // The user must be a valid google account.
    Policy oldPolicy = client.getIamPolicy(sourceName.toString());
    Binding bindings =
        Binding.newBuilder()
            .setRole("roles/securitycenter.findingsEditor")
            .addMembers("user:" + userEmail)
            .build();
    Policy policy = oldPolicy.toBuilder().addBindings(bindings).build();

    // Start setting up a request to set IAM policy for a source.
    // SourceName sourceName = SourceName.of("123234324", "423432321");
    SetIamPolicyRequest.Builder request =
        SetIamPolicyRequest.newBuilder().setPolicy(policy).setResource(sourceName.toString());

    // Call the API.
    Policy response = client.setIamPolicy(request.build());

    System.out.println("Policy: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	iam "google.golang.org/genproto/googleapis/iam/v1"
)

// setSourceIamPolicy grants user roles/securitycenter.findingsEditor permision
// for a source. sourceName is the full resource name of the source to be
// updated. user is an email address that IAM can grant permissions to.
func setSourceIamPolicy(w io.Writer, sourceName string, user string) error {
	// sourceName := "organizations/111122222444/sources/1234"
	// user := "someuser@some_domain.com
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	// Retrieve the existing policy so we can update only a specific
	// field.
	existing, err := client.GetIamPolicy(ctx, &iam.GetIamPolicyRequest{
		Resource: sourceName,
	})
	if err != nil {
		return fmt.Errorf("GetIamPolicy(%s): %w", sourceName, err)
	}

	req := &iam.SetIamPolicyRequest{
		Resource: sourceName,
		Policy: &iam.Policy{
			// Enables partial update of existing policy
			Etag: existing.Etag,
			Bindings: []*iam.Binding{{
				Role: "roles/securitycenter.findingsEditor",
				// New IAM Binding for the user.
				Members: []string{fmt.Sprintf("user:%s", user)},
			},
			},
		},
	}
	policy, err := client.SetIamPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("SetIamPolicy(%s, %v): %w", sourceName, req.Policy, err)
	}

	fmt.Fprint(w, "Bindings:\n")
	for _, binding := range policy.Bindings {
		for _, member := range binding.Members {
			fmt.Fprintf(w, "Principal: %s Role: %s\n", member, binding.Role)
		}
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();

async function setSourceIamPolicy() {
  // sourceName is the full resource name of the source to be
  // updated.
  // user is an email address that IAM can grant permissions to.
  /*
   * TODO(developer): Uncomment the following lines
   */
  // const sourceName = "organizations/111122222444/sources/1234";
  // const user = "someuser@domain.com";
  const [existingPolicy] = await client.getIamPolicy({
    resource: sourceName,
  });

  const [updatedPolicy] = await client.setIamPolicy({
    resource: sourceName,
    policy: {
      // Enables partial update of existing policy
      etag: existingPolicy.etag,
      bindings: [
        {
          role: 'roles/securitycenter.findingsEditor',
          // New IAM Binding for the user.
          members: [`user:${user}`],
        },
      ],
    },
  });
  console.log('Updated policy: %j', updatedPolicy);
}
setSourceIamPolicy();

API

在 API 中,向 organizations.sources.setIamPolicy 方法发出请求:请求正文包含一个 Policy 实例。

  POST https://securitycenter.googleapis.com/API_VERSION/organizations/ORGANIZATION_ID/sources/SOURCE_ID:setIamPolicy -d

  {
    "version": POLICY_FORMAT,
    "bindings": [
      {
        "role": IAM_ROLE,
        "members": [
          IAM_EMAIL
        ]
      }
  ],
    "auditConfigs": [
      {
        "service": "SERVICE",
          "auditLogConfigs": [
            {
              "logType": "LOG_PERMISSION",
              "exemptedMembers": [
                "user:EXEMPT_EMAIL"
                ]
            }
          ]
       }
    ],
    "etag": ETAG
  }

替换以下内容:

  • API_VERSION:您的目标 API 版本。
  • ORGANIZATION_ID:您的组织 ID。
  • SOURCE_ID:来源 ID。如需了解如何检索来源 ID,请参阅获取特定来源
  • POLICY_FORMAT:0、1 或 3,用于指定政策的格式。
  • IAM_ROLE:授予的 IAM 角色。
  • IAM_USER_EMAIL:被授予角色的用户的电子邮件地址。
  • SERVICE:要为其启用审核日志记录的 Google Cloud 服务。
  • LOG_PERMISSION:授予的日志权限:ADMIN_READDATA_READDATA_WRITE
  • EXEMPT_EMAIL:不会导致对该权限类型进行日志记录的身份。
  • ETAGgetIamPolicy 的响应中返回的字符串,应包含此字符串以帮助防止同时对政策进行的更新相互覆盖。

获取特定来源

使用来源的绝对资源名称来查询 Security Command Center,以验证来源是否已创建或更新:

gcloud

  # Note: For GCloud you can use either full resource name or just ID Flags.
  # In this example, we are using ID Flags.
  # ORGANIZATION_ID=12344321
  # SOURCE_ID=43211234

  gcloud scc sources describe $ORGANIZATION_ID --source=$SOURCE_ID

如需查看更多示例,请运行以下命令:

  gcloud scc sources describe --help

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'source_name' is the resource path for a source that has been
# created previously (you can use list_sources to find a specific one).
# Its format is:
# source_name = "organizations/{organization_id}/sources/{source_id}"
# e.g.:
# source_name = "organizations/111122222444/sources/1234"
source = client.get_source(request={"name": source_name})

print(f"Source: {source}")

Java

static Source getSource(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to get a source.
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");
    GetSourceRequest.Builder request =
        GetSourceRequest.newBuilder().setName(sourceName.toString());

    // Call the API.
    Source response = client.getSource(request.build());

    System.out.println("Source: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
)

// getSource retrieves a source by its resource name and print it to w.
// sourceName is the full resource name of the source to be updated.
func getSource(w io.Writer, sourceName string) error {
	// sourceName := "organizations/111122222444/sources/1234"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.GetSourceRequest{
		Name: sourceName,
	}
	source, err := client.GetSource(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSource: %w", err)
	}
	fmt.Fprintf(w, "Source: %v\n", source.Name)
	fmt.Fprintf(w, "Display Name: %v\n", source.DisplayName)
	fmt.Fprintf(w, "Description: %v\n", source.Description)
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
// sourceName is the full resource name of the source to be retrieved.
/*
 * TODO(developer): Uncomment the following lines
 */
// const sourceName = "organizations/111122222444/sources/1234";
async function getSource() {
  const [source] = await client.getSource({name: sourceName});
  console.log('Source: %j', source);
}

getSource();

API

在 API 中,向 organizations.sources.get 方法发出请求:请求正文为空。

  GET https://securitycenter.googleapis.com/API_VERSION/organizations/ORGANIZATION_ID/sources/SOURCE_ID

替换以下内容:

  • API_VERSION:您的目标 API 版本。
  • ORGANIZATION_ID:您的组织 ID。
  • SOURCE_ID:来源 ID。

列出来源

通过 Security Command Center,您可以列出特定来源,并列出组织中当前可用的所有来源:

Python

from google.cloud import securitycenter

# Create a new client.
client = securitycenter.SecurityCenterClient()
# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

# Call the API and print out each existing source.
for i, source in enumerate(client.list_sources(request={"parent": parent})):
    print(i, source)

Java

static ImmutableList<Source> listSources(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to list sources in an organization, project, or folder.
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListSourcesRequest.Builder request =
        ListSourcesRequest.newBuilder().setParent(organizationName.toString());

    // Call the API.
    ListSourcesPagedResponse response = client.listSources(request.build());

    // This creates one list for all sources.  If your organization has a large number of sources
    // this can cause out of memory issues.  You can process them batches by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<Source> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Sources:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/api/iterator"
)

// listSources prints all sources in  orgID to w.  orgID is the numeric
// identifier of the organization.
func listSources(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListSourcesRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent: fmt.Sprintf("organizations/%s", orgID),
	}
	it := client.ListSources(ctx, req)
	for {
		source, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("it.Next: %w", err)
		}
		fmt.Fprintf(w, "Source Name: %s, ", source.Name)
		fmt.Fprintf(w, "Display name: %s, ", source.DisplayName)
		fmt.Fprintf(w, "Description: %s\n", source.Description)
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;
// Call the API with automatic pagination.
async function listSources() {
  const [response] = await client.listSources({parent: parent});
  let count = 0;
  console.log('Sources:');
  Array.from(response).forEach(source =>
    console.log('%d %j', ++count, source)
  );
}

listSources();

API

在 API 中,向 organizations.sources.list 方法发出请求:请求正文为空。

  GET https://securitycenter.googleapis.com/API_VERSION/organizations/ORGANIZATION_ID/sources

替换以下内容:

  • API_VERSION:您的目标 API 版本。
  • ORGANIZATION_ID:您的组织 ID。

获取 IAM 政策

您可以通过从 Security Command Center 获取当前 IAM 政策数据来检查适当的 IAM 政策是否已应用于来源:

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'source_name' is the resource path for a source that has been
# created previously (you can use list_sources to find a specific one).
# Its format is:
# source_name = "organizations/{organization_id}/sources/{source_id}"
# e.g.:
# source_name = "organizations/111122222444/sources/1234"
# Get the old policy so we can do an incremental update.
policy = client.get_iam_policy(request={"resource": source_name})
print(f"Policy: {policy}")

Java

static Policy getIamPolicySource(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to get IAM policy for a source.
    // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/
    // "423432321");
    GetIamPolicyRequest request =
        GetIamPolicyRequest.newBuilder().setResource(sourceName.toString()).build();

    // Call the API.
    Policy response = client.getIamPolicy(request);

    System.out.println("Policy: " + response);
    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	iam "google.golang.org/genproto/googleapis/iam/v1"
)

// getSourceIamPolicy prints the policy for sourceName to w and return it.
// sourceName is the full resource name of the source with the policy of interest.
func getSourceIamPolicy(w io.Writer, sourceName string) error {
	// sourceName := "organizations/111122222444/sources/1234"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &iam.GetIamPolicyRequest{
		Resource: sourceName,
	}

	policy, err := client.GetIamPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("GetIamPolicy(%s): %w", sourceName, err)
	}

	fmt.Fprintf(w, "Policy: %v", policy)
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();

async function getSourceIamPolicy() {
  // sourceName is the full resource name to retrieve the policy for.
  /*
   * TODO(developer): Uncomment the following lines
   */
  // const sourceName = "organizations/111122222444/sources/1234";

  const [existingPolicy] = await client.getIamPolicy({
    resource: sourceName,
  });

  console.log('Current policy: %j', existingPolicy);
}
getSourceIamPolicy();

API

在 API 中,向 organizations.sources.getIamPolicy 方法发出请求:请求正文包含 GetIamPolicyRequest 请求消息。options 对象是可选的,用于请求政策格式。

  GET https://securitycenter.googleapis.com/API_VERSION/organizations/ORGANIZATION_ID/sources/SOURCE_ID:getIamPolicy -d

  {
    "resource": "organizations/ORGANIZATION_ID/sources/SOURCE_ID",
    "options": {
      "requestedPolicyVersion": POLICY_VERSION
    }
  }

替换以下内容:

  • API_VERSION:您的目标 API 版本。
  • ORGANIZATION_ID:您的组织 ID。
  • SOURCE_ID:来源 ID。如需了解如何检索来源 ID,请参阅获取特定来源
  • POLICY_VERSION:要返回的政策格式,0、1 或 3。

后续步骤

详细了解如何使用 SDK 访问 Security Command Center