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

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

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

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

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

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

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

  • יצירה NotificationConfig: הגדרות של התראות ממרכז האבטחה עריכה (roles/securitycenter.notificationConfigEditor)
  • קבלת רשימה של NotificationConfig: Security Center Notification Configurations Viewer (roles/securitycenter.notificationConfigViewer) או Security Center Notification Configurations Editor (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.

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

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

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

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

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

יצירת NotificationConfig

כדי ליצור NotificationConfig, אתם צריכים:

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

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

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

השדה NotificationConfig כולל את השדה filter שמגביל את ההתראות לאירועים שימושיים. בשדה הזה אפשר להזין את כל המסננים שזמינים בשיטה 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.iam.gserviceaccount.com. חשבון השירות הזה נוצר כשיוצרים את 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 בנושא.

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

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
}

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