Aggiorna le proprietà sorgente dei risultati

Mostra come aggiornare le proprietà sorgente per un risultato

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

Go

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

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

// updateFindingSourceProperties demonstrates how to update a security finding
// in CSCC. findingName is the full resource name of the finding to update.
func updateFindingSourceProperties(w io.Writer, findingName string) error {
	// findingName := "organizations/111122222444/sources/1234/findings/findingid"
	// 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.
	// Use now as the eventTime for the security finding.
	eventTime, err := ptypes.TimestampProto(time.Now())
	if err != nil {
		return fmt.Errorf("TimestampProto: %w", err)
	}

	req := &securitycenterpb.UpdateFindingRequest{
		Finding: &securitycenterpb.Finding{
			Name:      findingName,
			EventTime: eventTime,
			SourceProperties: map[string]*structpb.Value{
				"s_value": {
					Kind: &structpb.Value_StringValue{StringValue: "new_string_example"},
				},
			},
		},
		// Needed to only update the specific source property s_value
		// and EventTime. EventTime is a required field.
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"event_time", "source_properties.s_value"},
		},
	}

	finding, err := client.UpdateFinding(ctx, req)
	if err != nil {
		return fmt.Errorf("UpdateFinding: %w", err)
	}
	fmt.Fprintf(w, "Finding updated: %s\n", finding.Name)
	fmt.Fprintf(w, "Finding state: %v\n", finding.State)
	fmt.Fprintf(w, "Event time (Epoch Seconds): %d\n", eventTime.Seconds)
	fmt.Fprintf(w, "Source Properties:\n")
	for k, v := range finding.SourceProperties {
		fmt.Fprintf(w, "%s = %v\n", k, v)
	}
	return nil
}

Java

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

static Finding updateFinding(FindingName findingName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // FindingName findingName = FindingName.of(/*organization=*/"123234324",
    // /*source=*/"423432321", /*findingId=*/"samplefindingid2");

    // Use the current time as the finding "event time".
    Instant eventTime = Instant.now();

    // Define source properties values as protobuf "Value" objects.
    Value stringValue = Value.newBuilder().setStringValue("value").build();

    FieldMask updateMask =
        FieldMask.newBuilder()
            .addPaths("event_time")
            .addPaths("source_properties.stringKey")
            .build();

    Finding finding =
        Finding.newBuilder()
            .setName(findingName.toString())
            .setEventTime(
                Timestamp.newBuilder()
                    .setSeconds(eventTime.getEpochSecond())
                    .setNanos(eventTime.getNano()))
            .putSourceProperties("stringKey", stringValue)
            .build();

    UpdateFindingRequest.Builder request =
        UpdateFindingRequest.newBuilder().setFinding(finding).setUpdateMask(updateMask);

    // Call the API.
    Finding response = client.updateFinding(request.build());

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

Node.js

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

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

// findingName is the full resource name of the finding to update.
/*
 * TODO(developer): Uncomment the following lines
 */
// const findingName =
// "organizations/111122222444/sources/1234/findings/findingid";

// Use now as the eventTime for the security finding.
const eventTime = new Date();
console.log(findingName);
async function updateFinding() {
  const [newFinding] = await client.updateFinding({
    updateMask: {paths: ['event_time', 'source_properties.s_value']},
    finding: {
      name: findingName,
      // The time associated with discovering the issue.
      eventTime: {
        seconds: Math.floor(eventTime.getTime() / 1000),
        nanos: (eventTime.getTime() % 1000) * 1e6,
      },
      sourceProperties: {
        s_value: {stringValue: 'new_string_example'},
      },
    },
  });
  console.log('Updated Finding: %j', newFinding);
}
updateFinding();

Python

Per eseguire l'autenticazione in Security Command Center, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import datetime

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

client = securitycenter.SecurityCenterClient()
# Only update the specific source property and event_time.  event_time
# is required for updates.
field_mask = field_mask_pb2.FieldMask(
    paths=["source_properties.s_value", "event_time"]
)

# Set the update time to Now.  This must be some time greater then the
# event_time on the original finding.
event_time = datetime.datetime.now(tz=datetime.timezone.utc)

# '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"
finding_name = f"{source_name}/findings/samplefindingid2"
finding = Finding(
    name=finding_name,
    source_properties={"s_value": "new_string"},
    event_time=event_time,
)
updated_finding = client.update_finding(
    request={"finding": finding, "update_mask": field_mask}
)

print(
    "New Source properties: {}, Event Time {}".format(
        updated_finding.source_properties, updated_finding.event_time
    )
)

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.