Skip to content

Find, verify, and analyze leaked credentials

Add Interrupt and UserActionable errors (#5491)

Miccah882901ad61d0
diff --git a/pkg/sources/job_progress.go b/pkg/sources/job_progress.go
index 88d6f3a1d..cf60080c8 100644
--- a/pkg/sources/job_progress.go
+++ b/pkg/sources/job_progress.go
@@ -113,13 +113,39 @@ func (r *JobProgressRef) CancelRun(cause error) {
}
// Fatal is a wrapper around error to differentiate non-fatal errors from fatal
-// ones. A fatal error is typically from a finished context or any error
-// returned from a source's Init, Chunks, Enumerate, or ChunkUnit methods.
+// ones. A fatal error is one that leads to a complete failure of job,
+// typically indicated by an error from a source's Init, Chunks, Enumerate, or
+// ChunkUnit methods.
type Fatal struct{ error }
func (f Fatal) Error() string { return fmt.Sprintf("fatal: %s", f.error.Error()) }
func (f Fatal) Unwrap() error { return f.error }
+// Interrupt is a wrapper around error to indicate a job ended early without
+// failing, typically because its context was cancelled, such as by CancelRun.
+type Interrupt struct{ error }
+
+func (i Interrupt) Error() string { return fmt.Sprintf("interrupted: %s", i.error.Error()) }
+func (i Interrupt) Unwrap() error { return i.error }
+
+// UserActionable is a wrapper around error to indicate a user can resolve it,
+// for example by fixing credentials or granting access. It does not determine
+// whether the error is fatal: a source can return it to fail the job, or
+// report it and continue scanning.
+type UserActionable struct{ error }
+
+// NewUserActionableError wraps err to mark it as resolvable by a user. It returns
+// nil if err is nil.
+func NewUserActionableError(err error) error {
+ if err == nil {
+ return nil
+ }
+ return UserActionable{err}
+}
+
+func (u UserActionable) Error() string { return u.error.Error() }
+func (u UserActionable) Unwrap() error { return u.error }
+
// ChunkError is a custom error type for errors encountered during chunking of
// a specific unit.
type ChunkError struct {
@@ -422,6 +448,17 @@ func (m JobProgressMetrics) FatalErrors() error {
return errors.Join(aggregate...)
}
+// InterruptError returns the first Interrupt error, if any, encountered in the
+// scan.
+func (m JobProgressMetrics) InterruptError() error {
+ for _, err := range m.Errors {
+ if interruptErr, found := errors.AsType[Interrupt](err); found {
+ return interruptErr
+ }
+ }
+ return nil
+}
+
func (m JobProgressMetrics) PercentComplete() int {
num := m.FinishedUnits
den := m.TotalUnits
diff --git a/pkg/sources/source_manager.go b/pkg/sources/source_manager.go
index edfff48a9..91d4df5b9 100644
--- a/pkg/sources/source_manager.go
+++ b/pkg/sources/source_manager.go
@@ -1,6 +1,7 @@
package sources
import (
+ "errors"
"fmt"
"io"
"runtime"
@@ -145,10 +146,10 @@ func (s *SourceManager) EnumerateAndScan(ctx context.Context, sourceName string,
progress := NewJobProgress(jobID, sourceID, sourceName, WithHooks(s.hooks...), WithCancel(cancel))
if err := sem.Acquire(ctx, 1); err != nil {
// Context cancelled.
- fatalErr := Fatal{err}
- progress.ReportError(fatalErr)
- progress.finishWithCause(fatalErr)
- return progress.Ref(), fatalErr
+ interruptErr := Interrupt{err}
+ progress.ReportError(interruptErr)
+ progress.finishWithCause(interruptErr)
+ return progress.Ref(), interruptErr
}
s.wg.Add(1)
go func() {
@@ -217,7 +218,7 @@ func (s *SourceManager) Enumerate(ctx context.Context, sourceName string, source
case s.firstErr <- err:
default:
}
- progress.ReportError(Fatal{err})
+ progress.ReportError(jobErr(ctx, err))
}
}()
return progress.Ref(), nil
@@ -241,10 +242,10 @@ func (s *SourceManager) Scan(ctx context.Context, sourceName string, source Sour
progress := NewJobProgress(jobID, sourceID, sourceName, WithHooks(s.hooks...), WithCancel(cancel))
if err := s.sem.Acquire(ctx, 1); err != nil {
// Context cancelled.
- fatalErr := Fatal{err}
- progress.ReportError(fatalErr)
- progress.finishWithCause(fatalErr)
- return progress.Ref(), fatalErr
+ interruptErr := Interrupt{err}
+ progress.ReportError(interruptErr)
+ progress.finishWithCause(interruptErr)
+ return progress.Ref(), interruptErr
}
s.wg.Add(1)
go func() {
@@ -264,7 +265,7 @@ func (s *SourceManager) Scan(ctx context.Context, sourceName string, source Sour
case s.firstErr <- err:
default:
}
- progress.ReportError(Fatal{err})
+ progress.ReportError(jobErr(ctx, err))
}
}()
return progress.Ref(), nil
@@ -346,16 +347,34 @@ func (s *SourceManager) preflightChecks(ctx context.Context) error {
return ctx.Err()
}
+// jobErr classifies an error that ended a job, or part of one. It is an
+// Interrupt if the job's context is done and err came from that, for example a
+// source returning ctx.Err() after CancelRun. Otherwise it is Fatal. An error
+// that is already an Interrupt or Fatal is returned unchanged.
+func jobErr(ctx context.Context, err error) error {
+ if _, ok := errors.AsType[Interrupt](err); ok {
+ return err
+ }
+ if _, ok := errors.AsType[Fatal](err); ok {
+ return err
+ }
+ if ctxErr := ctx.Err(); ctxErr != nil && (errors.Is(err, ctxErr) || errors.Is(err, context.Cause(ctx))) {
+ return Interrupt{err}
+ }
+ return Fatal{err}
+}
+
// run is a helper method to synchronously run the source. It does not check for
-// acquired resources. An error is returned if there was a fatal error during
-// the run. This information is also recorded in the JobProgress.
+// acquired resources. An error is returned if there was a fatal error or an
+// interruption during the run. This information is also recorded in the
+// JobProgress.
func (s *SourceManager) run(ctx context.Context, source Source, report *JobProgress, targets ...ChunkingTarget) error {
report.Start(time.Now())
defer func() { report.End(time.Now()) }()
defer func() {
if err := context.Cause(ctx); err != nil {
- report.ReportError(Fatal{err})
+ report.ReportError(Interrupt{err})
}
}()
@@ -403,7 +422,7 @@ func (s *SourceManager) enumerate(ctx context.Context, source Source, report *Jo
defer func() {
if err := context.Cause(ctx); err != nil {
- report.ReportError(Fatal{err})
+ report.ReportError(Interrupt{err})
}
}()
@@ -427,7 +446,7 @@ func (s *SourceManager) scan(ctx context.Context, source Source, report *JobProg
defer func() {
if err := context.Cause(ctx); err != nil {
- report.ReportError(Fatal{err})
+ report.ReportError(Interrupt{err})
}
}()
@@ -451,10 +470,10 @@ func (s *SourceManager) scan(ctx context.Context, source Source, report *JobProg
func (s *SourceManager) enumerateWithUnits(ctx context.Context, source SourceUnitEnumerator, report *JobProgress, reporter UnitReporter) error {
// Create a function that will save the first error encountered (if
// any) and discard the rest.
- fatalErr := make(chan error, 1)
- catchFirstFatal := func(err error) {
+ firstErr := make(chan error, 1)
+ catchFirstError := func(err error) {
select {
- case fatalErr <- err:
+ case firstErr <- err:
default:
}
}
@@ -466,16 +485,16 @@ func (s *SourceManager) enumerateWithUnits(ctx context.Context, source SourceUni
ctx.Logger().V(2).Info("enumerating source with units")
defer common.RecoverWithHandler(ctx, func(err error) {
report.ReportError(Fatal{err})
- catchFirstFatal(Fatal{err})
+ catchFirstError(Fatal{err})
})
if err := source.Enumerate(ctx, reporter); err != nil {
- report.ReportError(Fatal{err})
- catchFirstFatal(Fatal{err})
+ report.ReportError(jobErr(ctx, err))
+ catchFirstError(jobErr(ctx, err))
}
}()
select {
- case err := <-fatalErr:
+ case err := <-firstErr:
return err
default:
return nil
@@ -506,8 +525,9 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, source Source, repo
defer wg.Wait()
defer close(ch)
if err := source.Chunks(ctx, ch, targets...); err != nil {
- report.ReportError(Fatal{err})
- return Fatal{err}
+ err = jobErr(ctx, err)
+ report.ReportError(err)
+ return err
}
return nil
}
@@ -522,10 +542,10 @@ func (s *SourceManager) runWithUnits(ctx context.Context, source SourceUnitEnumC
}
// Create a function that will save the first error encountered (if
// any) and discard the rest.
- fatalErr := make(chan error, 1)
- catchFirstFatal := func(err error) {
+ firstErr := make(chan error, 1)
+ catchFirstError := func(err error) {
select {
- case fatalErr <- err:
+ case firstErr <- err:
default:
}
}
@@ -538,11 +558,11 @@ func (s *SourceManager) runWithUnits(ctx context.Context, source SourceUnitEnumC
ctx.Logger().V(2).Info("enumerating source")
defer common.RecoverWithHandler(ctx, func(err error) {
report.ReportError(Fatal{err})
- catchFirstFatal(Fatal{err})
+ catchFirstError(Fatal{err})
})
if err := source.Enumerate(ctx, unitReporter); err != nil {
- report.ReportError(Fatal{err})
- catchFirstFatal(Fatal{err})
+ report.ReportError(jobErr(ctx, err))
+ catchFirstError(jobErr(ctx, err))
}
}()
var wg sync.WaitGroup
@@ -567,11 +587,11 @@ func (s *SourceManager) runWithUnits(ctx context.Context, source SourceUnitEnumC
ctx.Logger().V(3).Info("chunking unit")
defer common.RecoverWithHandler(ctx, func(err error) {
report.ReportError(Fatal{ChunkError{Unit: unit, Err: err}})
- catchFirstFatal(Fatal{err})
+ catchFirstError(Fatal{err})
})
if err := source.ChunkUnit(ctx, unit, chunkReporter); err != nil {
- report.ReportError(Fatal{ChunkError{Unit: unit, Err: err}})
- catchFirstFatal(Fatal{err})
+ report.ReportError(jobErr(ctx, ChunkError{Unit: unit, Err: err}))
+ catchFirstError(jobErr(ctx, err))
}
return nil
})
@@ -590,7 +610,7 @@ func (s *SourceManager) runWithUnits(ctx context.Context, source SourceUnitEnumC
}
wg.Wait()
select {
- case err := <-fatalErr:
+ case err := <-firstErr:
return err
default:
return nil
@@ -619,8 +639,8 @@ func (s *SourceManager) scanWithUnit(ctx context.Context, source SourceUnitChunk
chunkErr = Fatal{err}
})
if err := source.ChunkUnit(ctx, unit, chunkReporter); err != nil {
- report.ReportError(Fatal{ChunkError{Unit: unit, Err: err}})
- chunkErr = Fatal{err}
+ report.ReportError(jobErr(ctx, ChunkError{Unit: unit, Err: err}))
+ chunkErr = jobErr(ctx, err)
}
}()
// Consume chunks and export chunks.
diff --git a/pkg/sources/source_manager_test.go b/pkg/sources/source_manager_test.go
index 7503ee197..f28087542 100644
--- a/pkg/sources/source_manager_test.go
+++ b/pkg/sources/source_manager_test.go
@@ -1,6 +1,8 @@
package sources
import (
+ stdctx "context"
+ "errors"
"fmt"
"sort"
"sync"
@@ -320,7 +322,8 @@ func TestSourceManagerContextCancelled(t *testing.T) {
cancel()
<-ref.Done()
report := ref.Snapshot()
- assert.Error(t, report.FatalError())
+ assert.NoError(t, report.FatalError())
+ assert.ErrorIs(t, report.InterruptError(), stdctx.Canceled)
}
type DummyAPI struct {
@@ -364,12 +367,110 @@ func TestSourceManagerCancelRun(t *testing.T) {
cancelErr := fmt.Errorf("abort! abort!")
ref.CancelRun(cancelErr)
<-ref.Done()
- assert.Error(t, ref.Snapshot().FatalError())
- assert.ErrorIs(t, ref.Snapshot().FatalError(), returnedErr)
- assert.ErrorIs(t, ref.Snapshot().FatalErrors(), cancelErr)
+ assert.NoError(t, ref.Snapshot().FatalError())
+ assert.ErrorIs(t, ref.Snapshot().InterruptError(), returnedErr)
+ assert.ErrorIs(t, errors.Join(ref.Snapshot().Errors...), cancelErr)
assert.ErrorIs(t, ref.Err(), cancelErr)
}
+// blockingUnitChunker blocks in each method until its context is cancelled,
+// then returns the context's error.
+type blockingUnitChunker struct{}
+
+func (blockingUnitChunker) Chunks(ctx context.Context, _ chan *Chunk, _ ...ChunkingTarget) error {
+ <-ctx.Done()
+ return ctx.Err()
+}
+
+func (blockingUnitChunker) Enumerate(ctx context.Context, rep UnitReporter) error {
+ if err := rep.UnitOk(ctx, CommonSourceUnit{ID: "one"}); err != nil {
+ return err
+ }
+ <-ctx.Done()
+ return fmt.Errorf("enumerating: %w", ctx.Err())
+}
+
+func (blockingUnitChunker) ChunkUnit(ctx context.Context, _ SourceUnit, _ ChunkReporter) error {
+ <-ctx.Done()
+ return fmt.Errorf("chunking: %w", ctx.Err())
+}
+
+func TestSourceManagerCancelRunWithUnits(t *testing.T) {
+ noopReporter := visitorUnitReporter{
+ ok: func(context.Context, SourceUnit) error { return nil },
+ err: func(context.Context, error) error { return nil },
+ }
+ tests := []struct {
+ name string
+ start func(*SourceManager, Source) (JobProgressRef, error)
+ }{
+ {"EnumerateAndScan", func(mgr *SourceManager, source Source) (JobProgressRef, error) {
+ return mgr.EnumerateAndScan(context.Background(), "dummy", source)
+ }},
+ {"Enumerate", func(mgr *SourceManager, source Source) (JobProgressRef, error) {
+ return mgr.Enumerate(context.Background(), "dummy", source, noopReporter)
+ }},
+ {"Scan", func(mgr *SourceManager, source Source) (JobProgressRef, error) {
+ return mgr.Scan(context.Background(), "dummy", source, CommonSourceUnit{ID: "one"})
+ }},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ mgr := NewManager(WithBufferedOutput(8), WithSourceUnits())
+ source, err := buildDummy(blockingUnitChunker{})
+ assert.NoError(t, err)
+
+ ref, err := tt.start(mgr, source)
+ assert.NoError(t, err)
+
+ cancelErr := fmt.Errorf("abort! abort!")
+ ref.CancelRun(cancelErr)
+ <-ref.Done()
+ assert.NoError(t, ref.Snapshot().FatalError())
+ assert.ErrorIs(t, ref.Snapshot().InterruptError(), stdctx.Canceled)
+ assert.ErrorIs(t, errors.Join(ref.Snapshot().Errors...), cancelErr)
+ assert.ErrorIs(t, ref.Err(), cancelErr)
+ })
+ }
+}
+
+// TestSourceManagerCancelRunUnrelatedError tests that an error a source returns
+// after being cancelled is still Fatal if it did not come from the cancellation.
+func TestSourceManagerCancelRunUnrelatedError(t *testing.T) {
+ mgr := NewManager(WithBufferedOutput(8))
+ unrelatedErr := fmt.Errorf("connection reset")
+ source, err := buildDummy(callbackChunker{func(ctx context.Context, _ chan *Chunk) error {
+ <-ctx.Done()
+ return unrelatedErr
+ }})
+ assert.NoError(t, err)
+
+ ref, err := mgr.EnumerateAndScan(context.Background(), "dummy", source)
+ assert.NoError(t, err)
+
+ cancelErr := fmt.Errorf("abort! abort!")
+ ref.CancelRun(cancelErr)
+ <-ref.Done()
+ assert.ErrorIs(t, ref.Snapshot().FatalError(), unrelatedErr)
+ assert.ErrorIs(t, ref.Snapshot().InterruptError(), cancelErr)
+}
+
+func TestSourceManagerUserActionableError(t *testing.T) {
+ mgr := NewManager()
+ actionableErr := NewUserActionableError(fmt.Errorf("bad credentials"))
+ source, err := buildDummy(errorChunker{func() error { return actionableErr }})
+ assert.NoError(t, err)
+ ref, err := mgr.EnumerateAndScan(context.Background(), "dummy", source)
+ assert.NoError(t, err)
+ <-ref.Done()
+
+ fatalErr := ref.Snapshot().FatalError()
+ assert.ErrorIs(t, fatalErr, actionableErr)
+ _, ok := errors.AsType[UserActionable](fatalErr)
+ assert.True(t, ok)
+ assert.NoError(t, NewUserActionableError(nil))
+}
+
func TestSourceManagerAvailableCapacity(t *testing.T) {
mgr := NewManager(WithConcurrentSources(1337))
start, end := make(chan struct{}), make(chan struct{})
@@ -552,7 +653,7 @@ func TestUnitHookCloseConcurrentWithFinish(t *testing.T) {
func TestSourceManagerSemaphoreAcquireError(t *testing.T) {
assertFinishedAfterAcquireError := func(t *testing.T, ref JobProgressRef, err error) {
t.Helper()
- assert.IsType(t, Fatal{}, err)
+ assert.IsType(t, Interrupt{}, err)
// The acquire should fail, so the job should be finished
select {