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
139 changes: 139 additions & 0 deletions pkg/sourcetool/push.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// SPDX-FileCopyrightText: Copyright 2025 The SLSA Authors
// SPDX-License-Identifier: Apache-2.0

package sourcetool

import (
"context"
"errors"
"fmt"
"slices"
"time"

"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/policylabs/attestation"
"github.com/policylabs/collector"
"github.com/policylabs/collector/repository"

"github.com/slsa-framework/source-tool/pkg/attest"
)

// maxStoreAttempts is how many times the attestations are sent to a store
// before giving up.
const maxStoreAttempts = 3

// storeRetryDelay is waited before the second attempt and doubled before each
// one after it. A variable so tests do not wait.
var storeRetryDelay = 2 * time.Second

// pushAttestations publishes the envelopes to every store configured in the
// agent. Each store is retried on its own: a store that already has the
// attestations is never written again because another one failed, which would
// duplicate them.
func pushAttestations(ctx context.Context, agent *collector.Agent, envelopes []attestation.Envelope) error {
storers := []attestation.Storer{}
for _, repo := range agent.Repositories {
if s, ok := repo.(attestation.Storer); ok {
storers = append(storers, s)
}
}
if len(storers) == 0 {
return errors.New("no storer repositories configured")
}

envelopes = orderForPush(envelopes)

errs := []error{}
for _, s := range storers {
if err := storeWithRetry(ctx, s, agent.Options.Store, envelopes); err != nil {
errs = append(errs, fmt.Errorf("storing attestations: %w", err))
}
}
return errors.Join(errs...)
}

// orderForPush returns the envelopes with the VSAs first. The provenance of a
// revision states that its VSA exists. Stores that take one envelope at a time
// can fail between the two, publishing the VSA first means such a failure
// never leaves a provenance pointing to a VSA that was not published.
func orderForPush(envelopes []attestation.Envelope) []attestation.Envelope {
ordered := slices.Clone(envelopes)
slices.SortStableFunc(ordered, func(a, b attestation.Envelope) int {
switch av, bv := isVSA(a), isVSA(b); {
case av && !bv:
return -1
case !av && bv:
return 1
default:
return 0
}
})
return ordered
}

func isVSA(env attestation.Envelope) bool {
if env == nil || env.GetStatement() == nil {
return false
}
return env.GetStatement().GetPredicateType() == attestation.PredicateType(attest.VsaPredicateType)
}

// storeWithRetry sends the envelopes to a store, trying again when it fails.
// When the store reports which envelopes it could not take, only those are
// sent again.
func storeWithRetry(
ctx context.Context, storer attestation.Storer, opts attestation.StoreOptions, envelopes []attestation.Envelope,
) error {
pending := envelopes
delay := storeRetryDelay
for attempt := 1; ; attempt++ {
err := storer.Store(ctx, opts, pending)
if err == nil {
return nil
}
if attempt >= maxStoreAttempts || !retryableStore(ctx, err) {
return err
}

// Keep only the envelopes the store did not take
var serr *repository.StoreError
if errors.As(err, &serr) {
failed := make([]attestation.Envelope, 0, len(serr.Failed))
for i, env := range pending {
if _, ok := serr.Failed[i]; ok {
failed = append(failed, env)
}
}
if len(failed) > 0 {
pending = failed
}
}

select {
case <-ctx.Done():
return fmt.Errorf("%w (last error: %w)", ctx.Err(), err)
case <-time.After(delay):
}
delay *= 2
}
}

// retryableStore reports whether a failed store is worth another attempt.
// Failures for lack of access will fail again, as will any under a context
// that is done.
func retryableStore(ctx context.Context, err error) bool {
if ctx.Err() != nil {
return false
}
for _, permanent := range []error{
transport.ErrAuthenticationRequired,
transport.ErrAuthorizationFailed,
transport.ErrRepositoryNotFound,
transport.ErrInvalidAuthMethod,
} {
if errors.Is(err, permanent) {
return false
}
}
return true
}
137 changes: 137 additions & 0 deletions pkg/sourcetool/push_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// SPDX-FileCopyrightText: Copyright 2025 The SLSA Authors
// SPDX-License-Identifier: Apache-2.0

package sourcetool

import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"

"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/policylabs/attestation"
"github.com/policylabs/collector"
"github.com/policylabs/collector/envelope"
"github.com/policylabs/collector/repository"
"github.com/stretchr/testify/require"

"github.com/slsa-framework/source-tool/pkg/attest"
"github.com/slsa-framework/source-tool/pkg/provenance"
)

// fakeStorer records the predicate types it gets on each call and fails
// with the errors it is loaded with, one per call.
type fakeStorer struct {
errs []error
calls [][]string
}

func (f *fakeStorer) Store(_ context.Context, _ attestation.StoreOptions, envs []attestation.Envelope) error {
types := make([]string, 0, len(envs))
for _, env := range envs {
types = append(types, string(env.GetStatement().GetPredicateType()))
}
f.calls = append(f.calls, types)
if len(f.calls) <= len(f.errs) {
return f.errs[len(f.calls)-1]
}
return nil
}

func testEnvelope(t *testing.T, predicateType string) attestation.Envelope {
t.Helper()
data := fmt.Sprintf(
`{"_type":"https://in-toto.io/Statement/v1","subject":[{"digest":{"gitCommit":"2fa9ea0072ad0090e0234d1e7f2b3e9c8b8a5b8d"}}],"predicateType":%q,"predicate":{}}`,
predicateType,
)
envs, err := envelope.Parsers.Parse(strings.NewReader(data))
require.NoError(t, err)
require.Len(t, envs, 1)
return envs[0]
}

func testAgent(t *testing.T, storers ...*fakeStorer) *collector.Agent {
t.Helper()
agent, err := collector.New()
require.NoError(t, err)
for _, s := range storers {
require.NoError(t, agent.AddRepository(s))
}
return agent
}

// The tests swap the package-level retry delay, so they cannot run in parallel.
func TestPushAttestations(t *testing.T) { //nolint:paralleltest
storeRetryDelay = time.Millisecond

provType := provenance.SourceProvPredicateType
vsaType := attest.VsaPredicateType
transient := errors.New("connection reset")

newEnvelopes := func(t *testing.T) []attestation.Envelope {
t.Helper()
return []attestation.Envelope{testEnvelope(t, provType), testEnvelope(t, vsaType)}
}

t.Run("vsa-goes-first", func(t *testing.T) { //nolint:paralleltest
s := &fakeStorer{}
envs := newEnvelopes(t)
require.NoError(t, pushAttestations(t.Context(), testAgent(t, s), envs))
require.Equal(t, [][]string{{vsaType, provType}}, s.calls)
// The caller's slice is left as it was
require.Equal(t, provType, string(envs[0].GetStatement().GetPredicateType()))
})

t.Run("retries-transient-failure", func(t *testing.T) { //nolint:paralleltest
s := &fakeStorer{errs: []error{transient, transient}}
require.NoError(t, pushAttestations(t.Context(), testAgent(t, s), newEnvelopes(t)))
require.Len(t, s.calls, 3)
})

t.Run("gives-up-after-max-attempts", func(t *testing.T) { //nolint:paralleltest
s := &fakeStorer{errs: []error{transient, transient, transient, transient}}
err := pushAttestations(t.Context(), testAgent(t, s), newEnvelopes(t))
require.ErrorIs(t, err, transient)
require.Len(t, s.calls, maxStoreAttempts)
})

t.Run("resends-only-failed-envelopes", func(t *testing.T) { //nolint:paralleltest
// The store took the VSA (#0) but not the provenance (#1)
partial := &repository.StoreError{Stored: 1, Failed: map[int]error{1: transient}}
s := &fakeStorer{errs: []error{partial}}
require.NoError(t, pushAttestations(t.Context(), testAgent(t, s), newEnvelopes(t)))
require.Equal(t, [][]string{{vsaType, provType}, {provType}}, s.calls)
})

t.Run("does-not-retry-access-errors", func(t *testing.T) { //nolint:paralleltest
denied := fmt.Errorf("pushing notes: %w", transport.ErrAuthorizationFailed)
s := &fakeStorer{errs: []error{denied, denied}}
err := pushAttestations(t.Context(), testAgent(t, s), newEnvelopes(t))
require.ErrorIs(t, err, transport.ErrAuthorizationFailed)
require.Len(t, s.calls, 1)
})

t.Run("does-not-retry-when-context-is-done", func(t *testing.T) { //nolint:paralleltest
ctx, cancel := context.WithCancel(t.Context())
cancel()
s := &fakeStorer{errs: []error{transient, transient}}
require.Error(t, pushAttestations(ctx, testAgent(t, s), newEnvelopes(t)))
require.Len(t, s.calls, 1)
})

t.Run("stores-are-retried-independently", func(t *testing.T) { //nolint:paralleltest
good := &fakeStorer{}
flaky := &fakeStorer{errs: []error{transient}}
require.NoError(t, pushAttestations(t.Context(), testAgent(t, good, flaky), newEnvelopes(t)))
// The store that worked is written once
require.Len(t, good.calls, 1)
require.Len(t, flaky.calls, 2)
})

t.Run("no-storers", func(t *testing.T) { //nolint:paralleltest
require.Error(t, pushAttestations(t.Context(), testAgent(t), newEnvelopes(t)))
})
}
2 changes: 1 addition & 1 deletion pkg/sourcetool/tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ func (t *Tool) AttestRevision(
envelopes = append(envelopes, parsed...)
}

if err := agent.Store(ctx, envelopes); err != nil {
if err := pushAttestations(ctx, agent, envelopes); err != nil {
return nil, fmt.Errorf("pushing attestations: %w", err)
}
}
Expand Down
Loading