Providing metadata for images

Metadata providers are the companies that provide metadata for their customers' container images. Providers can use Container Analysis to store and retrieve metadata for their customers' images. For example, a company that provide security management for their customers' Docker containers can use Container Analysis to store and retrieve security-related metadata for the images.

This page explains how to provide vulnerability details for your customer's images using the Container Analysis API. You can use the same instructions to store and retrieve any kind of metadata that Container Analysis supports.

Before you begin

  1. Enable the Container Scanning API. This enables vulnerability scanning as well as the Container Analysis API. You can enable the API for an existing project, or create a new project and then enable the API. You can manually disable vulnerability scanning at a later time.

    Enable the Container Scanning API

    Enable the Container Scanning API

  2. Read Container Analysis Overview.

Creating vulnerability notes and occurrences for projects

This section explains how third-party vulnerability providers can create notes and occurrences for their user's projects.

As a provider, you will create a note in your project for each vulnerability kind, and you will create an occurrence in your customer's project for an occurrence of that vulnerability.

Creating notes

IAM permissions:

To perform this task, you must have the following IAM permissions on the provider's project (which is the project where the notes are created):

  • containeranalysis.notes.create

Alternately, you can grant the following predefined IAM role, which will automatically provide all the necessary permissions:

  • Container Analysis Notes Editor role on your project.

To create a note:

API

  1. Create a file named note.json with vulnerability description and details. The following code shows an example note.json file:

    {
        "shortDescription": "A brief Description of the note",
        "longDescription": "A longer description of the note",
        "kind": "PACKAGE_VULNERABILITY",
        "vulnerabilityType": {
            "details": [
            {
                "package": "libexempi3",
                "cpeUri": "cpe:/o:debian:debian_linux:7",
                "minAffectedVersion": { "name": "2.5.7", "revision": "1"},
                "maxAffectedVersion": { "name": "2.5.9", "revision": "1"},
            },
            {
                "cpeUri": "something else"
            }
            ]
        }
    }
    
  2. Run the following curl command to create a note where [PROVIDER_PROJECT_ID] is your project ID:

    curl -X POST -H "Content-Type: application/json" -H \
        "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://containeranalysis.googleapis.com/v1beta1/projects/[PROVIDER_PROJECT_ID]/notes?note_id=[NOTE_ID] -d @note.json
    

Java

To learn how to install and use the client library for Container Registry, see the Container Registry Client Libraries . For more information, see the Container Registry Java API reference documentation .

import com.google.cloud.devtools.containeranalysis.v1beta1.GrafeasV1Beta1Client;
import com.google.containeranalysis.v1beta1.ProjectName;
import io.grafeas.v1beta1.Note;
import io.grafeas.v1beta1.vulnerability.Severity;
import io.grafeas.v1beta1.vulnerability.Vulnerability;
import io.grafeas.v1beta1.vulnerability.Vulnerability.Detail;
import java.io.IOException;
import java.lang.InterruptedException;


public class CreateNote {

  // Creates and returns a new Note
  public static Note createNote(String noteId, String projectId)
      throws IOException, InterruptedException {
    // String noteId = "my-note";
    // String projectId = "my-project-id";
    final String projectName = ProjectName.format(projectId);

    Note.Builder noteBuilder = Note.newBuilder();
    // Associate the Note with the metadata type
    // https://cloud.google.com/container-registry/docs/container-analysis#supported_metadata_types
    // Here, we use the type "vulnerability"
    Vulnerability.Builder vulBuilder = Vulnerability.newBuilder();
    noteBuilder.setVulnerability(vulBuilder);
    // Set additional information specific to your new vulnerability note
    Detail.Builder detailsBuilder = Detail.newBuilder();
    detailsBuilder.setDescription("my new vulnerability note");
    vulBuilder.setSeverity(Severity.LOW);
    vulBuilder.addDetails(detailsBuilder);
    // Build the Note object
    Note newNote = noteBuilder.build();

    // Initialize client that will be used to send requests. After completing all of your requests,
    // call the "close" method on the client to safely clean up any remaining background resources.
    GrafeasV1Beta1Client client = GrafeasV1Beta1Client.create();
    Note result = client.createNote(projectName, noteId, newNote);
    return result;
  }
}

Go

To learn how to install and use the client library for Container Registry, see the Container Registry Client Libraries . For more information, see the Container Registry Go API reference documentation .

import (
	"context"
	"fmt"

	containeranalysis "cloud.google.com/go/containeranalysis/apiv1beta1"
	grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas"
	"google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/vulnerability"
)

// createNote creates and returns a new vulnerability Note.
func createNote(noteID, projectID string) (*grafeaspb.Note, error) {
	ctx := context.Background()
	client, err := containeranalysis.NewGrafeasV1Beta1Client(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewGrafeasV1Beta1Client: %v", err)
	}
	defer client.Close()

	projectName := fmt.Sprintf("projects/%s", projectID)

	req := &grafeaspb.CreateNoteRequest{
		Parent: projectName,
		NoteId: noteID,
		Note: &grafeaspb.Note{
			Type: &grafeaspb.Note_Vulnerability{
				// The 'Vulnerability' field can be modified to contain information about your vulnerability.
				Vulnerability: &vulnerability.Vulnerability{},
			},
		},
	}

	return client.CreateNote(ctx, req)
}

Creating occurrences for the notes

IAM permissions:

To perform this task, you must have the following IAM permissions:

  • containeranalysis.occurrences.create on your customer's project
  • containeranalysis.notes.attachOccurrence on your project.

Alternately, you can grant the following predefined IAM role, which will automatically provide all the necessary permissions:

  • Container Analysis Occurrences Editor role on your customer's project
  • Container Analysis Notes Attacher role on your project.

To create occurrences for a note:

API

  1. Create a file named occurrence.json with the following contents:

    {
        "resourceUrl": "<resource_url>",
        "noteName": "projects/<provider-project-id>/notes/<note_id>",
        "kind": "PACKAGE_VULNERABILITY",
        "vulnerabilityDetails": {
            "packageIssue": [{
                "affectedLocation": {
                    "cpeUri": "7",
                    "package": "a",
                    "version":  {
                        "epoch": "1"
                        "name": "namestring"
                        "revision": "r"
                    },
                },
                "fixedLocation": {
                    "cpeUri": "cpe:/o:debian:debian_linux:7",
                    "package": "a",
                    "version":  {
                        "epoch": "2"
                        "name": "namestring"
                        "revision": "1"
                    }
                }
            }]
        }
    }
    
  2. Run the following curl command where [CUSTOMER_PROJECT_ID] is your customer's project ID:

    curl -v -X POST -H "Content-Type: application/json" -H \
        "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://containeranalysis.googleapis.com/v1beta1/projects/[CUSTOMER_PROJECT_ID]/occurrences -d @occurrence.json
    

Java

To learn how to install and use the client library for Container Registry, see the Container Registry Client Libraries . For more information, see the Container Registry Java API reference documentation .

import com.google.cloud.devtools.containeranalysis.v1beta1.GrafeasV1Beta1Client;
import com.google.containeranalysis.v1beta1.NoteName;
import com.google.containeranalysis.v1beta1.ProjectName;
import io.grafeas.v1beta1.Occurrence;
import io.grafeas.v1beta1.Resource;
import io.grafeas.v1beta1.vulnerability.Details;
import java.io.IOException;
import java.lang.InterruptedException;

public class CreateOccurrence {
  // Creates and returns a new Occurrence associated with an existing Note
  public static Occurrence createOccurrence(String resourceUrl, String noteId,
      String occProjectId, String noteProjectId) throws IOException, InterruptedException {
    // String resourceUrl = "https://gcr.io/project/image@sha256:123";
    // String noteId = "my-note";
    // String occProjectId = "my-project-id";
    // String noteProjectId = "my-project-id";
    final NoteName noteName = NoteName.of(noteProjectId, noteId);
    final String occProjectName = ProjectName.format(occProjectId);

    Occurrence.Builder occBuilder = Occurrence.newBuilder();
    occBuilder.setNoteName(noteName.toString());
    // Associate the Occurrence with the metadata type (should match the parent Note's type)
    // https://cloud.google.com/container-registry/docs/container-analysis#supported_metadata_types
    // Here, we use the type "vulnerability"
    Details.Builder detailsBuilder = Details.newBuilder();
    occBuilder.setVulnerability(detailsBuilder);
    // Attach the occurrence to the associated image uri
    Resource.Builder resourceBuilder = Resource.newBuilder();
    resourceBuilder.setUri(resourceUrl);
    occBuilder.setResource(resourceBuilder);
    Occurrence newOcc = occBuilder.build();

    // Initialize client that will be used to send requests. After completing all of your requests,
    // call the "close" method on the client to safely clean up any remaining background resources.
    GrafeasV1Beta1Client client = GrafeasV1Beta1Client.create();
    Occurrence result = client.createOccurrence(occProjectName, newOcc);
    return result;
  }
}

Go

To learn how to install and use the client library for Container Registry, see the Container Registry Client Libraries . For more information, see the Container Registry Go API reference documentation .

import (
	"context"
	"fmt"

	containeranalysis "cloud.google.com/go/containeranalysis/apiv1beta1"
	grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas"
	"google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/vulnerability"
)

// createsOccurrence creates and returns a new Occurrence of a previously created vulnerability Note.
func createOccurrence(resourceURL, noteID, occProjectID, noteProjectID string) (*grafeaspb.Occurrence, error) {
	// resourceURL := fmt.Sprintf("https://gcr.io/my-project/my-image")
	// noteID := fmt.Sprintf("my-note")
	ctx := context.Background()
	client, err := containeranalysis.NewGrafeasV1Beta1Client(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewGrafeasV1Beta1Client: %v", err)
	}
	defer client.Close()

	req := &grafeaspb.CreateOccurrenceRequest{
		Parent: fmt.Sprintf("projects/%s", occProjectID),
		Occurrence: &grafeaspb.Occurrence{
			NoteName: fmt.Sprintf("projects/%s/notes/%s", noteProjectID, noteID),
			// Attach the occurrence to the associated resource uri.
			Resource: &grafeaspb.Resource{
				Uri: resourceURL,
			},
			// Details about the vulnerability instance can be added here.
			Details: &grafeaspb.Occurrence_Vulnerability{
				Vulnerability: &vulnerability.Details{},
			},
		},
	}
	return client.CreateOccurrence(ctx, req)
}

Get all occurrences for a specific note

You can view all occurrences of a specific vulnerability across your customer's projects using notes.occurrences.list().

IAM permissions:

To perform this task, you must have the following IAM permissions:

  • containeranalysis.notes.listOccurrences on your project

Alternately, you can grant the following predefined IAM role, which will automatically provide all the necessary permissions:

  • Container Analysis Occurrences Viewer role on your project

To get all occurrences for a note:

API

To list all the occurrences for a note, send a GET request as follows:

GET https://containeranalysis.googleapis.com/v1beta1/projects/PROJECT_ID/notes/NOTE_ID/occurrences

Refer to the projects.notes.occurrences.list API endpoint for complete details.

Java

To learn how to install and use the client library for Container Registry, see the Container Registry Client Libraries . For more information, see the Container Registry Java API reference documentation .

import static java.lang.Thread.sleep;

import com.google.cloud.devtools.containeranalysis.v1beta1.GrafeasV1Beta1Client;
import com.google.containeranalysis.v1beta1.NoteName;
import io.grafeas.v1beta1.ListNoteOccurrencesRequest;
import io.grafeas.v1beta1.Occurrence;
import java.io.IOException;
import java.lang.InterruptedException;

public class OccurrencesForNote {
  // Retrieves all the Occurrences associated with a specified Note
  // Here, all Occurrences are printed and counted
  public static int getOccurrencesForNote(String noteId, String projectId)
      throws IOException, InterruptedException {
    // String noteId = "my-note";
    // String projectId = "my-project-id";
    final NoteName noteName = NoteName.of(projectId, noteId);

    ListNoteOccurrencesRequest request = ListNoteOccurrencesRequest.newBuilder()
                                                                   .setName(noteName.toString())
                                                                   .build();

    // Initialize client that will be used to send requests. After completing all of your requests,
    // call the "close" method on the client to safely clean up any remaining background resources.
    GrafeasV1Beta1Client client = GrafeasV1Beta1Client.create();
    int i = 0;
    for (Occurrence o : client.listNoteOccurrences(request).iterateAll()) {
      // Write custom code to process each Occurrence here
      System.out.println(o.getName());
      i = i + 1;
    }
    return i;
  }
}

Go

To learn how to install and use the client library for Container Registry, see the Container Registry Client Libraries . For more information, see the Container Registry Go API reference documentation .

import (
	"context"
	"fmt"
	"io"

	containeranalysis "cloud.google.com/go/containeranalysis/apiv1beta1"
	"google.golang.org/api/iterator"
	grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas"
)

// getOccurrencesForNote retrieves all the Occurrences associated with a specified Note.
// Here, all Occurrences are printed and counted.
func getOccurrencesForNote(w io.Writer, noteID, projectID string) (int, error) {
	// noteID := fmt.Sprintf("my-note")
	ctx := context.Background()
	client, err := containeranalysis.NewGrafeasV1Beta1Client(ctx)
	if err != nil {
		return -1, fmt.Errorf("NewGrafeasV1Beta1Client: %v", err)
	}
	defer client.Close()

	req := &grafeaspb.ListNoteOccurrencesRequest{
		Name: fmt.Sprintf("projects/%s/notes/%s", projectID, noteID),
	}
	it := client.ListNoteOccurrences(ctx, req)
	count := 0
	for {
		occ, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return -1, fmt.Errorf("occurrence iteration error: %v", err)
		}
		// Write custom code to process each Occurrence here.
		fmt.Fprintln(w, occ)
		count = count + 1
	}
	return count, nil
}

What's next

  • For instructions on how to view, filter, and get notifications on vulnerabilities for the images in Container Registry, see Getting Image Vulnerabilities.
¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...