Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkg/images/enricher/testing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ type fakeSigFetcher struct {
}

func (f *fakeSigFetcher) FetchSignatures(_ context.Context, _ *storage.Image, _ string,
_ types.Registry) ([]*storage.Signature, error) {
_ types.Registry, _ ...retry.OptionsModifier) ([]*storage.Signature, error) {
if f.fail {
err := errors.New("some error")
if f.retryable {
Expand Down
157 changes: 157 additions & 0 deletions pkg/signatures/cosign_payload_fetcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package signatures

import (
"context"
"fmt"
"net/http"
"strings"

"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/sigstore/cosign/v3/pkg/cosign"
"github.com/sigstore/cosign/v3/pkg/oci"
ociremote "github.com/sigstore/cosign/v3/pkg/oci/remote"
)

const (
bundleSigArtifactTypePrefix = "application/vnd.dev.sigstore.bundle"

// maxReferrerManifests limits the number of referrer signature manifests processed per image
// to bound latency and prevent pathological cases from consuming the caller's timeout budget.
maxReferrerManifests = 50
)

// signaturePayload is the internal representation of a fetched cosign signature before
// it is persisted into the CosignSignature proto. Two formats are supported:
//
// - SimpleSigning: the legacy cosign format. The signature, payload, certificate, and
// rekor bundle are stored as individual fields in cosign.SignedPayload.
// - Sigstore bundle: the OCI 1.1 bundle format. The raw bundle JSON is stored as-is
// in sigstoreBundle and verified directly via sigstore-go at verification time.
//
// The format is determined by sigstoreBundle: non-empty means sigstore bundle,
// empty means SimpleSigning.
type signaturePayload struct {
cosign.SignedPayload
sigstoreBundle []byte
}

var _ oci.SignedEntity = (*tagSignedEntity)(nil)

// tagSignedEntity adapts an image reference for tag-based signature discovery.
// Signatures() constructs the cosign tag reference (<algo>-<hex>.sig) and fetches
// the signature manifest from the registry. Digest() returns the image digest so
// cosign can build the tag. Only these two methods are called by cosign.FetchSignatures.
// Attestations and Attachment return safe defaults to prevent panics if cosign evolves.
type tagSignedEntity struct {
opts []ociremote.Option
imgRef name.Reference
imgSHA string
}

func newTagSignedEntity(imgSHA string, imgRef name.Reference, opts ...ociremote.Option) *tagSignedEntity {
return &tagSignedEntity{
opts: opts,
imgRef: imgRef,
imgSHA: imgSHA,
}
}

func (s *tagSignedEntity) Digest() (v1.Hash, error) {
return v1.NewHash(s.imgSHA)
}

func (s *tagSignedEntity) Signatures() (oci.Signatures, error) {
h, err := s.Digest()
if err != nil {
return nil, err
}
// Cosign ref: https://github.com/sigstore/cosign/blob/main/pkg/oci/remote/remote.go
return ociremote.Signatures(s.imgRef.Context().Tag(fmt.Sprint(h.Algorithm, "-", h.Hex, ".sig")), s.opts...)
}

func (s *tagSignedEntity) Attestations() (oci.Signatures, error) { return nil, nil }

func (s *tagSignedEntity) Attachment(_ string) (oci.File, error) { return nil, nil }

// fetchSignaturesByTag discovers SimpleSigning signatures via the cosign tag-based method.
// Discovery: looks up the tag <algo>-<hex>.sig in the same repository as the image.
// Format: always SimpleSigning (signature and payload stored in OCI layer annotations).
func fetchSignaturesByTag(imgSHA string, imgRef name.Reference, opts []ociremote.Option) ([]signaturePayload, error) {
se := newTagSignedEntity(imgSHA, imgRef, opts...)
payloads, err := cosign.FetchSignatures(se)
if err != nil && (isMissingSignatureError(err) || isUnknownMimeTypeError(err)) {
return nil, nil
}
wrapped := make([]signaturePayload, len(payloads))
for i, p := range payloads {
wrapped[i] = signaturePayload{SignedPayload: p}
}
return wrapped, err
}

// fetchSignaturesByReferrer discovers sigstore bundle signatures via the OCI 1.1 Referrers API.
// Discovery: queries the referrers index for the image digest and filters for sigstore
// bundle artifact types. Only the sigstore bundle format is supported for referrer-based
// discovery — cosign v3 exclusively produces bundles for this path.
func fetchSignaturesByReferrer(ctx context.Context, digestRef name.Digest, repo name.Repository,
opts []ociremote.Option,
) ([]signaturePayload, error) {
index, err := ociremote.Referrers(digestRef, "", opts...)
if err != nil {
// Registries that do not implement the OCI 1.1 Referrers API return 404.
if checkIfErrorContainsCode(err, http.StatusNotFound) {
Comment thread
guzalv marked this conversation as resolved.
log.Warnf("OCI referrers API not supported for %s (404)", digestRef.String())
return nil, nil
}
return nil, err
}
if index == nil {
return nil, nil
}

// Filter for sigstore bundle artifact types first, then clamp so the budget is
// consumed only by manifests we are willing to process.
var bundleDescs []v1.Descriptor
for _, desc := range index.Manifests {
if strings.HasPrefix(desc.ArtifactType, bundleSigArtifactTypePrefix) {
bundleDescs = append(bundleDescs, desc)
}
}
if len(bundleDescs) > maxReferrerManifests {
log.Warnf("Image %s has %d sigstore bundle referrers, processing only first %d",
digestRef.String(), len(bundleDescs), maxReferrerManifests)
bundleDescs = bundleDescs[:maxReferrerManifests]
}

var payloads []signaturePayload
for _, desc := range bundleDescs {
if ctx.Err() != nil {
Comment thread
guzalv marked this conversation as resolved.
return payloads, ctx.Err()
}
p, err := fetchSigstoreBundle(repo.Digest(desc.Digest.String()), opts)
if err != nil {
return payloads, fmt.Errorf("fetching sigstore bundle from referrer %s: %w", desc.Digest, err)
}
payloads = append(payloads, p)
}
return payloads, nil
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

// fetchSigstoreBundle fetches a sigstore bundle referrer and stores the raw JSON.
// Format: sigstore bundle (DSSE envelope + verification material + tlog entries in one blob).
// Storage: the raw bundle JSON is stored in SigstoreBundle; no decomposition into individual
// fields. Verification is deferred to verifySigstoreBundle which uses sigstore-go directly.
func fetchSigstoreBundle(bundleRef name.Reference, opts []ociremote.Option) (signaturePayload, error) {
b, err := ociremote.Bundle(bundleRef, opts...)
if err != nil {
return signaturePayload{}, err
}

bundleJSON, err := b.MarshalJSON()
if err != nil {
return signaturePayload{}, fmt.Errorf("marshalling sigstore bundle: %w", err)
}

return signaturePayload{sigstoreBundle: bundleJSON}, nil
}
101 changes: 101 additions & 0 deletions pkg/signatures/cosign_payload_fetcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package signatures

import (
"context"
"encoding/base64"
"fmt"
"testing"

"github.com/google/go-containerregistry/pkg/name"
"github.com/sigstore/cosign/v3/pkg/oci/mutate"
ociremote "github.com/sigstore/cosign/v3/pkg/oci/remote"
"github.com/sigstore/cosign/v3/pkg/oci/static"
"github.com/stackrox/rox/pkg/images/types"
imgUtils "github.com/stackrox/rox/pkg/images/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// uploadSignatureAsReferrer stores a cosign signature as an OCI 1.1 referrer for the given image.
func uploadSignatureAsReferrer(imgRef string, b64Sig string, sigPayload, certPEM, chainPEM []byte) error {
sigOpts := []static.Option{static.WithCertChain(certPEM, chainPEM)}

sig, err := static.NewSignature(sigPayload, b64Sig, sigOpts...)
if err != nil {
return err
}

ref, err := name.ParseReference(imgRef)
if err != nil {
return err
}
d, ok := ref.(name.Digest)
if !ok {
return fmt.Errorf("could not cast reference %q to name.Digest", ref.String())
}

se, err := ociremote.SignedEntity(ref)
if err != nil {
return err
}

newSE, err := mutate.AttachSignatureToEntity(se, sig)
if err != nil {
return err
}

return ociremote.WriteSignaturesExperimentalOCI(d, newSE)
}

func TestFetchTagPayloads_WithSignatures(t *testing.T) {
registryServer, imgRef, err := registryServerWithImage("nginx")
require.NoError(t, err, "setting up registry")
defer registryServer.Close()

sigPayload, err := base64.StdEncoding.DecodeString(payload1)
require.NoError(t, err)

require.NoError(t, uploadSignatureForImage(imgRef, sig1, sigPayload, nil, nil, nil),
"uploading tag-based signature")

ref, err := name.ParseReference(imgRef)
require.NoError(t, err)
img, err := imgUtils.GenerateImageFromString(imgRef)
require.NoError(t, err)

payloads, err := fetchSignaturesByTag(imgUtils.GetSHA(types.ToImage(img)), ref, nil)
require.NoError(t, err)
assert.Len(t, payloads, 1)
assert.Equal(t, sigPayload, payloads[0].Payload)
assert.Equal(t, sig1, payloads[0].Base64Signature)
}

func TestFetchTagPayloads_NoSignatures(t *testing.T) {
registryServer, imgRef, err := registryServerWithImage("nginx")
require.NoError(t, err, "setting up registry")
defer registryServer.Close()

ref, err := name.ParseReference(imgRef)
require.NoError(t, err)
img, err := imgUtils.GenerateImageFromString(imgRef)
require.NoError(t, err)

payloads, err := fetchSignaturesByTag(imgUtils.GetSHA(types.ToImage(img)), ref, nil)
require.NoError(t, err)
assert.Empty(t, payloads)
}

func TestFetchReferrerPayloads_NoSignatures(t *testing.T) {
registryServer, imgRef, err := registryServerWithImage("nginx")
require.NoError(t, err, "setting up registry")
defer registryServer.Close()

ref, err := name.ParseReference(imgRef)
require.NoError(t, err)
d, ok := ref.(name.Digest)
require.True(t, ok)

payloads, err := fetchSignaturesByReferrer(context.Background(), d, ref.Context(), nil)
require.NoError(t, err)
assert.Empty(t, payloads)
}
Loading
Loading