יצירה וניהול של הגדרות התראות

Standard-legacy,‏ Standard,‏ Premium ו-Enterprise (הוצאה משימוש)

בדף הזה מוסבר איך להשתמש בתכונה "התראות" של Security Command Center API, כולל הדוגמאות הבאות:

  • יצירת NotificationConfig
  • רוצה NotificationConfig?
  • עדכון של NotificationConfig
  • מחיקת NotificationConfig
  • רשימה NotificationConfig
  • קבלת התראות Pub/Sub

אפשר גם להגדיר ייצוא רציף ל-Pub/Sub ב-Security Command Center.

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

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

כדי להריץ את הדוגמאות הבאות, צריך תפקיד בניהול זהויות והרשאות גישה (IAM) עם ההרשאות המתאימות:

  • יצירת NotificationConfig: עריכת הגדרות ההתראות של מרכז האבטחה (roles/securitycenter.notificationConfigEditor)
  • Get ו-List NotificationConfig: צפייה בהגדרות של התראות במרכז האבטחה (roles/securitycenter.notificationConfigViewer) או עריכה של הגדרות ההתראות במרכז האבטחה (roles/securitycenter.notificationConfigEditor)
  • עדכון ומחיקה של NotificationConfig: עריכת הגדרות ההתראות של מרכז האבטחה (roles/securitycenter.notificationConfigEditor)

כדי להקצות תפקידים מתאימים לחשבון ראשי שניגש אל notificationConfig, אתם צריכים אחד מתפקידי ה-IAM הבאים:

  • אדמין של הארגון (roles/resourcemanager.organizationAdmin)
  • אדמין IAM בתיקייה (roles/resourcemanager.folderIamAdmin)
  • אדמין IAM בפרויקט (roles/resourcemanager.projectIamAdmin)

אפשר להקצות את התפקידים ב-IAM ל-Security Command Center ברמת הארגון, התיקייה או הפרויקט. היכולת להציג, לערוך, ליצור או לעדכן ממצאים, נכסים ומקורות אבטחה תלויה ברמת הגישה שקיבלתם. בקרת גישה – מידע נוסף על התפקידים ב-Security Command Center.

מיקום אחסון הנתונים והתראות

אם מיקום אחסון הנתונים מופעל ב-Security Command Center, ההגדרות שקובעות את הייצוא הרציף למשאבי Pub/Sub (notificationConfig) כפופות לבקרת מיקום אחסון הנתונים, והן מאוחסנות במיקום של Security Command Center.

כדי לייצא ל-Pub/Sub ממצאים במיקום של Security Command Center, צריך להגדיר את הייצוא הרציף באותו מיקום של Security Command Center שבו נמצאים הממצאים.

המסננים שמשמשים לייצוא רציף יכולים להכיל נתונים שכפופים לבקרות על מיקום אחסון הנתונים, ולכן חשוב לציין את המיקום הנכון לפני שיוצרים אותם. ב-Security Command Center אין הגבלה על המיקום שבו יוצרים את הייצוא.

הייצוא הרציף נשמר רק במיקום שבו הוא נוצר, ואי אפשר לראות או לערוך אותו במיקומים אחרים.

אחרי שיוצרים ייצוא רציף, אי אפשר לשנות את המיקום שלו. כדי לשנות את המיקום, צריך למחוק את הייצוא הרציף וליצור אותו מחדש במיקום החדש.

במאמר נקודות קצה אזוריות של Security Command Center מוסבר איך משתמשים ב-Security Command Center כשמיקום אחסון הנתונים מופעל.

יצירת NotificationConfig

כדי ליצור NotificationConfig, צריך:

  • נושא Pub/Sub קיים שאליו אתם רוצים לשלוח התראות.
  • התפקידים הנדרשים ב-IAM לחשבון המשתמש שיוצר את notificationConfig.

מידע נוסף זמין בשלב הגדרת נושא Pub/Sub במדריך הגדרת התראות על ממצאים.

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

ה-NotificationConfig כולל שדה filter שמגביל את ההתראות לאירועים שימושיים. בשדה הזה אפשר להזין את כל המסננים שזמינים ב-method‏ findings.list של Security Command Center API.

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

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

gcloud

gcloud scc notifications create NOTIFICATION_NAME \
  --PARENT=PARENT_ID \
  --location=LOCATION \
  --description="NOTIFICATION_DESCRIPTION" \
  --pubsub-topic=PUBSUB_TOPIC \
  --filter="FILTER" \
  --deletion-notifications-enabled

מחליפים את מה שכתוב בשדות הבאים:

  • ‫NOTIFICATION_NAME: שם ההתראה. השם צריך להיות באורך של 1 עד 128 תווים, ויכול להכיל רק תווים אלפאנומריים, קווים תחתונים או מקפים.
  • ‫PARENT: ההיקף בהיררכיית המשאבים שההתראה חלה עליו, organization,‏ folder או project.
  • ‫PARENT_ID: המזהה של הארגון, התיקייה או הפרויקט ברמה שמעל, בפורמט organizations/123, folders/456 או projects/789.
  • ‫LOCATION: המיקום של Security Command Center שבו רוצים ליצור את NotificationConfig. אם מופעלת דרישה למיקום אחסון הנתונים, משתמשים ב-eu, ב-sa או ב-us. אחרת, משתמשים בערך global.
  • ‫NOTIFICATION_DESCRIPTION: תיאור של ההתראה, באורך של עד 1,024 תווים.
  • ‫PUBSUB_TOPIC: נושא Pub/Sub שיקבל התראות. הפורמט שלו הוא projects/PROJECT_ID/topics/TOPIC.
  • ‫FILTER: הביטוי שאתם מגדירים כדי לבחור אילו ממצאים יישלחו ל-Pub/Sub. לדוגמה, state=\"ACTIVE\".

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

  • ‫--deletion-notifications-enabled: הפעלת התראות על ממצאים שנמחקו בגלל מדיניות שמירת הנתונים. אם מגדירים את המסנן, ההתראות מופעלות כשממצא נמחק. ההתראה כוללת את המאפיין deletedFinding שמוגדר כ-true.
  • ‫--no-deletion-notifications-enabled: השבתת ההתראות על ממצאים שנמחקו בגלל מדיניות שמירת הנתונים.

Terraform

יצירת NotificationConfig לארגון:

resource "google_pubsub_topic" "scc_v2_organization_notification_config" {
  name = "my-topic"
}

resource "google_scc_v2_organization_notification_config" "custom_organization_notification_config" {
  config_id    = "my-config"
  organization = "123456789"
  location     = "global"
  description  = "My custom Cloud Security Command Center Finding Organization Notification Configuration"
  pubsub_topic = google_pubsub_topic.scc_v2_organization_notification_config.id

  streaming_config {
    filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\""
  }
}

יצירת NotificationConfig לתיקייה:

resource "google_folder" "folder" {
  parent       = "organizations/123456789"
  display_name = "folder-name"
}

resource "google_pubsub_topic" "scc_v2_folder_notification_config" {
  name = "my-topic"
}

resource "google_scc_v2_folder_notification_config" "custom_notification_config" {
  config_id    = "my-config"
  folder       = google_folder.folder.folder_id
  location     = "global"
  description  = "My custom Cloud Security Command Center Finding Notification Configuration"
  pubsub_topic =  google_pubsub_topic.scc_v2_folder_notification_config.id

  streaming_config {
    filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\""
  }
}

יוצרים NotificationConfig לפרויקט:

resource "google_pubsub_topic" "scc_v2_project_notification" {
  name = "my-topic"
}

resource "google_scc_v2_project_notification_config" "custom_notification_config" {
  config_id    = "my-config"
  project      = "my-project-name"
  description  = "My custom Cloud Security Command Center Finding Notification Configuration"
  pubsub_topic =  google_pubsub_topic.scc_v2_project_notification.id

  streaming_config {
    filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\""
  }
}

המשך

import (
	"context"
	"fmt"
	"io"

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

func createNotificationConfig(w io.Writer, orgID string, pubsubTopic string, notificationConfigID string) error {
	// orgID := "your-org-id"
	// pubsubTopic := "projects/{your-project}/topics/{your-topic}"
	// notificationConfigID := "your-config-id"

	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)

	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close()

	req := &securitycenterpb.CreateNotificationConfigRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}/locations/global"
		//		"projects/{projectId}/locations/global"
		//		"folders/{folderId}/locations/global"
		Parent:   fmt.Sprintf("organizations/%s/locations/global", orgID),
		ConfigId: notificationConfigID,
		NotificationConfig: &securitycenterpb.NotificationConfig{
			Description: "Go sample config",
			PubsubTopic: pubsubTopic,
			NotifyConfig: &securitycenterpb.NotificationConfig_StreamingConfig_{
				StreamingConfig: &securitycenterpb.NotificationConfig_StreamingConfig{
					Filter: `state = "ACTIVE"`,
				},
			},
		},
	}

	notificationConfig, err := client.CreateNotificationConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("Failed to create notification config: %w", err)
	}
	fmt.Fprintln(w, "New NotificationConfig created: ", notificationConfig)

	return nil
}

Java


package vtwo.notifications;

import com.google.cloud.securitycenter.v2.LocationName;
import com.google.cloud.securitycenter.v2.NotificationConfig;
import com.google.cloud.securitycenter.v2.SecurityCenterClient;
import java.io.IOException;

public class CreateNotification {

  public static void main(String[] args) throws IOException {
    // parentId: must be in one of the following formats:
    //    "organizations/{organization_id}"
    //    "projects/{project_id}"
    //    "folders/{folder_id}"
    String parentId = "{parent-id}";
    String topicName = "{your-topic}";
    String notificationConfigId = "{your-notification-id}";
    // Specify the location of the notification config.
    String location = "global";

    createNotificationConfig(parentId, location, topicName, notificationConfigId);
  }

  // Crete a notification config.
  // Ensure the ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
  public static NotificationConfig createNotificationConfig(
      String parentId, String location, String topicName, String notificationConfigId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SecurityCenterClient client = SecurityCenterClient.create()) {

      String pubsubTopic = String.format("projects/%s/topics/%s", parentId, topicName);

      NotificationConfig notificationConfig = NotificationConfig.newBuilder()
          .setDescription("Java notification config")
          .setPubsubTopic(pubsubTopic)
          .setStreamingConfig(
              NotificationConfig.StreamingConfig.newBuilder().setFilter("state = \"ACTIVE\"")
                  .build())
          .build();

      NotificationConfig response = client.createNotificationConfig(
          LocationName.of(parentId, location), notificationConfig, notificationConfigId);

      System.out.printf("Notification config was created: %s%n", response);
      return response;
    }
  }
}

Node.js

// npm install '@google-cloud/security-center'
const {SecurityCenterClient} = require('@google-cloud/security-center').v2;
const uuidv1 = require('uuid').v1;

const client = new SecurityCenterClient();
/*
 *  Required. Resource name of the new notification config's parent. Its format
 *  is "organizations/[organization_id]/locations/[location_id]",
 *  "folders/[folder_id]/locations/[location_id]", or
 *  "projects/[project_id]/locations/[location_id]".
 */
const parent = `projects/${projectId}/locations/${location}`;

/**
 *  Required.
 *  Unique identifier provided by the client within the parent scope.
 *  It must be between 1 and 128 characters and contain alphanumeric
 *  characters, underscores, or hyphens only.
 */
const configId = 'notif-config-test-node-create-' + uuidv1();

// pubsubTopic = "projects/{your-project}/topics/{your-topic}";
const pubsubTopic = `projects/${projectId}/topics/${topicName}`;

/**
 *  Required. The notification config being created. The name and the service
 *  account will be ignored as they are both output only fields on this
 *  resource.
 */
const notificationConfig = {
  description: 'Sample config for node v2',
  pubsubTopic: pubsubTopic,
  streamingConfig: {filter: 'state = "ACTIVE"'},
};

// Build the request.
const createNotificationRequest = {
  parent: parent,
  configId: configId,
  notificationConfig: notificationConfig,
};

async function createNotificationConfig() {
  const [response] = await client.createNotificationConfig(
    createNotificationRequest
  );
  console.log('Notification configuration creation successful: %j', response);
}

await createNotificationConfig();

Python

def create_notification_config(
    parent_id, location_id, pubsub_topic, notification_config_id
) -> NotificationConfig:
    """
    This method is used to create the Notification Config.
    Args:
        parent_id: must be in one of the following formats:
            "organizations/{organization_id}"
            "projects/{project_id}"
            "folders/{folder_id}"
        location_id: "global"
        pubsub_topic: "projects/{your-project-id}/topics/{your-topic-id}"
        notification_config_id: "your-config-id"


    Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
    """
    from google.cloud import securitycenter_v2 as securitycenter_v2

    client = securitycenter_v2.SecurityCenterClient()
    parent_id = parent_id + "/locations/" + location_id
    response = client.create_notification_config(
        request={
            "parent": parent_id,
            "config_id": notification_config_id,
            "notification_config": {
                "description": "Notification for active findings",
                "pubsub_topic": pubsub_topic,
                "streaming_config": {"filter": 'state = "ACTIVE"'},
            },
        }
    )
    print(f"create notification config response:{response}")
    return response

ההתראות מתפרסמות עכשיו בנושא Pub/Sub שציינתם.

כדי לפרסם התראות, נוצר בשבילכם חשבון שירות בפורמט service-org-ORGANIZATION_ID@gcp-sa-scc-notification.. חשבון השירות הזה נוצר כשיוצרים את ה-NotificationConfig הראשון, והוא מקבל באופן אוטומטי את התפקיד securitycenter.notificationServiceAgent במדיניות ה-IAM של PUBSUB_TOPIC כשיוצרים את הגדרת ההתראות. התפקיד הזה של חשבון השירות נדרש כדי שההתראות יפעלו.

אחזור של NotificationConfig

כדי לקבל NotificationConfig, צריך להיות לכם תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.get.

gcloud

gcloud scc notifications describe NOTIFICATION_NAME \
  --PARENT_TYPE=PARENT_ID \
  --location=LOCATION

מחליפים את מה שכתוב בשדות הבאים:

  • ‫NOTIFICATION_NAME: השם של הגדרת ההתראה.
  • ‫PARENT_TYPE: הרמה בהיררכיית המשאבים שבה מוגדרת התצורה. אפשר להשתמש ב-organization, ב-folder או ב-project.
  • ‫PARENT_ID: המזהה המספרי של משאב ההורה.
  • ‫LOCATION: המיקום ב-Security Command Center שבו רוצים לקבל את NotificationConfig. אם מופעלת דרישה למיקום אחסון הנתונים, משתמשים ב-eu, ב-sa או ב-us. אחרת, משתמשים בערך global.

עדכון של NotificationConfig

כדי לעדכן NotificationConfig, צריך להיות לכם תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.update.

כשמעדכנים באמצעות מסכת שדות, רק השדות שציינתם מתעדכנים. אם לא משתמשים במסכת שדה, כל השדות הניתנים לשינוי ב-NotificationConfig מוחלפים בערכים החדשים. אתם יכולים להשתמש במסכת שדה כדי לעדכן את הנושא והתיאור של Pub/Sub.

כדי להשלים את הדוגמה הזו, אתם צריכים להיות מנויים לנושא החדש, ולחשבון השירות של ההתראות צריכה להיות ההרשאה pubsub.topics.setIamPolicy בנושא.

אחרי שנותנים את ההרשאות הנדרשות, מעדכנים את התיאור, את נושא ה-Pub/Sub ואת המסנן של NotificationConfig:

gcloud

gcloud scc notifications update NOTIFICATION_NAME \
  --PARENT_TYPE=PARENT_ID \
  --location=LOCATION \
  --description="NOTIFICATION_DESCRIPTION" \
  --pubsub-topic=PUBSUB_TOPIC \
  --filter="FILTER" \
  --deletion-notifications-enabled

מחליפים את מה שכתוב בשדות הבאים:

  • ‫NOTIFICATION_NAME: השם של הגדרת ההתראה.
  • ‫PARENT_TYPE הרמה בהיררכיית המשאבים שבה מוגדרת התצורה. אפשר להשתמש ב-organization, ב-folder או ב-project.
  • ‫PARENT_ID: המזהה המספרי של משאב ההורה.
  • LOCATION: המיקום של Security Command Center שבו רוצים לעדכן את NotificationConfig. אם מיקום אחסון הנתונים מופעל, משתמשים בערך eu, sa או us. אחרת, משתמשים בערך global.
  • ‫NOTIFICATION_DESCRIPTION: תיאור של ההתראה, באורך של עד 1,024 תווים.
  • ‫PUBSUB_TOPIC: נושא Pub/Sub שיקבל התראות. הפורמט שלו הוא projects/PROJECT_ID/topics/TOPIC.
  • ‫FILTER: הביטוי שאתם מגדירים כדי לבחור אילו ממצאים יישלחו ל-Pub/Sub. לדוגמה, state="ACTIVE".

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

  • ‫--deletion-notifications-enabled: הפעלת התראות על ממצאים שנמחקו בגלל מדיניות שמירת נתונים. כשהאפשרות מופעלת, ממצאים שנמחקו מיוצאים ל-Pub/Sub עם deleted_finding = true. הדגל הזה חל רק על אירועי מחיקה עתידיים. ממצאים שנמחקו לפני הפעלת הדגל הזה לא מיוצאים באופן רטרואקטיבי.

  • ‫--no-deletion-notifications-enabled: השבתת ההתראות על ממצאים שנמחקו.

מחיקת NotificationConfig

כדי למחוק NotificationConfig, צריך להיות לכם תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.delete.

כשמוחקים NotificationConfig, התפקיד securitycenter.notificationServiceAgent נשאר בנושא Pub/Sub. אם אתם לא משתמשים בנושא Pub/Sub באף NotificationConfig אחר, הסירו את התפקיד מהנושא. למידע נוסף, קראו על בקרת גישה.

gcloud

gcloud scc notifications delete NOTIFICATION_NAME \
  --PARENT_TYPE=PARENT_ID \
  --location=LOCATION

מחליפים את מה שכתוב בשדות הבאים:

  • ‫NOTIFICATION_NAME: השם של הגדרת ההתראה.
  • ‫PARENT_TYPE הרמה בהיררכיית המשאבים שבה מוגדרת התצורה. אפשר להשתמש ב-organization, ב-folder או ב-project.
  • ‫PARENT_ID: המזהה המספרי של משאב ההורה.
  • ‫LOCATION: המיקום ב-Security Command Center שבו רוצים למחוק את NotificationConfig. אם מופעלת דרישה למיקום אחסון הנתונים, משתמשים ב-eu, ב-sa או ב-us. אחרת, משתמשים בערך global.

הצגת רשימה של NotificationConfigs

כדי להציג את NotificationConfigs, צריך תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.list.

כל הרשימות של Security Command Center API מחולקות לדפים. כל תשובה מחזירה דף של תוצאות ואסימון להחזרת הדף הבא. ערך ברירת המחדל של pageSize הוא 10. אפשר להגדיר את גודל הדף למינימום של 1 ולמקסימום של 1, 000.

gcloud

gcloud scc notifications list PARENT_TYPE/PARENT_ID \
  --location=LOCATION

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PARENT_TYPE הרמה בהיררכיית המשאבים שבה מוגדרת התצורה. אפשר להשתמש ב-organizations, ב-folders או ב-projects.
  • ‫PARENT_ID: המזהה המספרי של משאב ההורה.
  • ‫LOCATION: המיקום ב-Security Command Center שבו רוצים להציג את המשאבים של NotificationConfig. אם מופעלת דרישה למיקום אחסון הנתונים, משתמשים בערך eu,‏ sa או us. אחרת, משתמשים בערך global.

קבלת התראות Pub/Sub

בקטע הזה מופיעים הודעת התראה לדוגמה ודוגמאות שמראות איך להמיר הודעת Pub/Sub ל-NotificationMessage שמכיל ממצא.

ההתראות מתפרסמות ב-Pub/Sub בפורמט JSON. דוגמה להודעה:

{
   "notificationConfigName": "organizations/ORGANIZATION_ID/notificationConfigs/CONFIG_ID",
   "finding": {
     "name": "organizations/ORGANIZATION_ID/sources/SOURCE_ID/findings/FINDING_ID",
     "parent": "organizations/ORGANIZATION_ID/sources/SOURCE_ID",
     "state": "ACTIVE",
     "category": "TEST-CATEGORY",
     "securityMarks": {
       "name": "organizations/ORGANIZATION_ID/sources/SOURCE_ID/findings/FINDING_ID/securityMarks"
     },
     "eventTime": "2019-07-26T07:32:37Z",
     "createTime": "2019-07-29T18:45:27.243Z"
   },
   "deletedFinding": true
 }

הממצאים נמחקים מ-Security Command Center מדי פעם, בהתאם למדיניות שמירת הנתונים. אתם יכולים להגדיר אם Security Command Center ייצא ל-Pub/Sub תמונת מצב של ממצאים שנמחקו.

כדי להפעיל התראות על מחיקה, צריך ליצור או לעדכן הגדרת ייצוא. כשההתראות על מחיקה מופעלות בהגדרות הייצוא, Security Command Center שולח ל-Pub/Sub תמונת מצב של הממצאים שנמחקו. השדה "deletedFinding": true מוגדר במטען הייעודי (payload) של ההתראה. המצב של הממצא לפני המחיקה (לדוגמה, "state": "ACTIVE") נשמר במטען הייעודי (payload), והשדה eventTime מוגדר לזמן שבו הממצא נמחק ב-Security Command Center.

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

המרת הודעת Pub/Sub ל-NotificationMessage באמצעות השפה שבחרתם:

gcloud

ב-CLI של gcloud אין תמיכה בהמרה של הודעת Pub/Sub ל-NotificationMessage. אתם יכולים להשתמש ב-CLI של gcloud כדי לקבל NotificationMessage ולהדפיס את JSON ישירות בטרמינל:

  # The subscription used to receive published messages from a topic
  PUBSUB_SUBSCRIPTION="projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID"

  gcloud pubsub subscriptions pull $PUBSUB_SUBSCRIPTION

מחליפים את מה שכתוב בשדות הבאים:

  • ‫PROJECT_ID במזהה הפרויקט.
  • ‫SUBSCRIPTION_ID במזהה המינוי שלכם.

המשך

import (
	"bytes"
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
	"cloud.google.com/go/securitycenter/apiv2/securitycenterpb"
	"github.com/golang/protobuf/jsonpb"
)

func receiveMessages(w io.Writer, projectID string, subscriptionName string) error {
	// projectID := "your-project-id"
	// subsriptionName := "your-subscription-name"

	ctx := context.Background()

	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	sub := client.Subscription(subscriptionName)
	cctx, cancel := context.WithCancel(ctx)
	err = sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
		var notificationMessage = new(securitycenterpb.NotificationMessage)
		jsonpb.Unmarshal(bytes.NewReader(msg.Data), notificationMessage)

		fmt.Fprintln(w, "Got finding: ", notificationMessage.GetFinding())
		msg.Ack()
		cancel()
	})
	if err != nil {
		return fmt.Errorf("Receive: %w", err)
	}

	return nil
}

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