Skip to content

Find, verify, and analyze leaked credentials

Clean up S3 source logging for per-source debug (#5481)

Kashif Khance76ea8f5488
diff --git a/pkg/sources/s3/README.md b/pkg/sources/s3/README.md
index bf0e6531a..a1d8cc15a 100644
--- a/pkg/sources/s3/README.md
+++ b/pkg/sources/s3/README.md
@@ -67,6 +67,18 @@ If a filter excludes every object in a bucket, the scan logs `Scanned no objects
- Extensions in the shared deny list in `pkg/common/vars.go`, which already covers images, audio, and video
- Keys ending in `/`, which are directory markers
+## Debug logs
+
+With debug on for this source (`debug: true` in the config), the scan logs:
+
+- `V(1)`: `S3 source initialized` with the config choices (the endpoint's host only, never credentials), and `Found buckets to scan` for each role.
+- `V(2)`: `Scanning bucket` and `Finished scanning bucket`, with the objects scanned, pages and duration.
+- `V(3)`: `Scanning object` for each object downloaded.
+- `V(4)`: `Skipping bucket` and `Skipping object` with a `reason`, `Listed page` for each page, and `AWS SDK` lines for retries, including S3 throttling (`SlowDown`).
+- `V(5)`: `Finished scanning object` with its duration, and the region used for a bucket outside the default region.
+
+Lines carry `role`, `bucket`, `page_number` and `key` where they apply. An object skipped for one of the reasons above shows its reason here, so a missing finding can be traced to the object it would have come from.
+
## Custom endpoints
`--endpoint` points the scan at an S3-compatible service instead of AWS S3. Setting it changes three things:
diff --git a/pkg/sources/s3/checkpointer.go b/pkg/sources/s3/checkpointer.go
index a6df6586c..e6f6c5a85 100644
--- a/pkg/sources/s3/checkpointer.go
+++ b/pkg/sources/s3/checkpointer.go
@@ -71,8 +71,6 @@ const defaultMaxObjectsPerPage = 1000
// NewCheckpointer creates a new checkpointer for S3 scanning operations.
// The progress provides the underlying mechanism for persisting scan state.
func NewCheckpointer(ctx context.Context, progress *sources.Progress, isUnitScan bool) *Checkpointer {
- ctx.Logger().Info("Creating checkpointer")
-
return &Checkpointer{
// We are resuming if we have completed objects from a previous scan.
completedObjects: make([]bool, defaultMaxObjectsPerPage),
@@ -119,7 +117,7 @@ func (p *Checkpointer) ResumePoint(ctx context.Context) (ResumeInfo, error) {
}
if resumeInfo.CurrentBucket == "" {
- ctx.Logger().V(2).Info("resume info is missing current bucket, resuming from the beginning")
+ ctx.Logger().V(4).Info("resume info is missing current bucket, resuming from the beginning")
return resume, nil
}
diff --git a/pkg/sources/s3/progress.go b/pkg/sources/s3/progress.go
index aa2d11a32..cefb03d9d 100644
--- a/pkg/sources/s3/progress.go
+++ b/pkg/sources/s3/progress.go
@@ -127,7 +127,7 @@ func (s *Source) countBucket(
if err != nil {
// A cancelled count means the unit has finished, and finish settles the totals.
if ctx.Err() == nil {
- ctx.Logger().V(2).Info("could not count objects for progress", "bucket", bucket, "err", err)
+ ctx.Logger().V(4).Info("could not count objects for progress", "error", err)
progress.setState(sources.UnitProgressUnavailable)
}
return
diff --git a/pkg/sources/s3/s3.go b/pkg/sources/s3/s3.go
index 9c8a821da..eda6e6d00 100644
--- a/pkg/sources/s3/s3.go
+++ b/pkg/sources/s3/s3.go
@@ -134,6 +134,21 @@ func (s *Source) Init(
"exclude_extensions", filter.excludeExtensions)
}
+ // Only the endpoint's host, since a user-entered endpoint can carry credentials.
+ var endpointHost string
+ if endpoint != nil {
+ endpointHost = endpoint.Host
+ }
+ ctx.Logger().V(1).Info("S3 source initialized",
+ "bucket_count", len(conn.GetBuckets()),
+ "ignore_bucket_count", len(conn.GetIgnoreBuckets()),
+ "role_count", len(conn.GetRoles()),
+ "region", s.defaultRegion(),
+ "endpoint_host", endpointHost,
+ "max_object_size", s.maxObjectSize,
+ // a nil credential means the AWS SDK's default credential chain
+ "credential_type", fmt.Sprintf("%T", conn.GetCredential()))
+
return nil
}
@@ -252,6 +267,9 @@ func (s *Source) newClient(ctx context.Context, region, roleArn string) (*s3.Cli
return s3.NewFromConfig(cfg, func(options *s3.Options) {
options.DisableLogOutputChecksumValidationSkipped = true
+ // Retries are otherwise invisible, including S3 throttling with SlowDown.
+ options.Logger = sdkLogger{}
+ options.ClientLogMode = aws.LogRetries
if s.endpoint != nil {
options.BaseEndpoint = aws.String(s.endpoint.String())
// S3-compatible services rarely publish the wildcard DNS that
@@ -287,9 +305,11 @@ func (s *Source) getBucketsToScan(ctx context.Context, client *s3.Client) ([]str
var bucketsToScan []string
for _, bucket := range res.Buckets {
name := *bucket.Name
- if _, ignored := ignore[name]; !ignored {
- bucketsToScan = append(bucketsToScan, name)
+ if _, ignored := ignore[name]; ignored {
+ ctx.Logger().V(4).Info("Skipping bucket", "bucket", name, "reason", "in ignore list")
+ continue
}
+ bucketsToScan = append(bucketsToScan, name)
}
slices.Sort(bucketsToScan)
@@ -375,28 +395,24 @@ func (s *Source) scanBuckets(
chunksChan chan *sources.Chunk,
totalObjectCount *uint64,
) {
- if role != "" {
- ctx = context.WithValue(ctx, "role", role)
- }
-
checkpointer := NewCheckpointer(ctx, &s.Progress, false)
pos := determineResumePosition(ctx, checkpointer, bucketsToScan)
switch {
case pos.isNewScan:
- ctx.Logger().Info("Starting new scan from beginning")
+ ctx.Logger().V(1).Info("Starting new scan from beginning")
case !pos.exactMatch:
ctx.Logger().Info(
"Resume bucket no longer available, starting from closest position",
"original_bucket", pos.bucket,
"position", pos.index,
- "role", pos.role,
+ "previous_role", pos.role,
)
default:
ctx.Logger().Info(
"Resuming scan from previous scan's bucket",
"bucket", pos.bucket,
"position", pos.index,
- "role", pos.role,
+ "previous_role", pos.role,
)
}
@@ -447,12 +463,15 @@ func (s *Source) scanBucket(
ctx = context.WithValue(ctx, "bucket", bucket)
+ // scanBuckets calls this for every remaining bucket after a cancel, so this
+ // is not an error, or a cancelled scan would log one per bucket
if common.IsDone(ctx) {
- ctx.Logger().Error(ctx.Err(), "context done, while scanning bucket")
+ ctx.Logger().V(4).Info("Skipping bucket", "reason", "scan cancelled")
return 0
}
- ctx.Logger().V(3).Info("Scanning bucket")
+ ctx.Logger().V(2).Info("Scanning bucket")
+ start := time.Now()
regionalClient, err := s.getRegionalClientForBucket(ctx, client, role, bucket)
if err != nil {
@@ -486,7 +505,7 @@ func (s *Source) scanBucket(
// often cause this to happen a lot (because in that case the scanner tries to scan every bucket in the
// account, but the role probably doesn't have access to all of them). This makes it expected behavior
// and therefore not an error.
- ctx.Logger().V(3).Info("could not list objects in bucket", "err", err)
+ ctx.Logger().V(4).Info("Skipping bucket", "reason", "role cannot list objects", "error", err)
} else {
// This can also be a failure to assume the role itself: role credentials
// are resolved lazily, so the first request that needs them surfaces the
@@ -497,6 +516,7 @@ func (s *Source) scanBucket(
listFailed = true
break
}
+ ctx.Logger().V(4).Info("Listed page", "page_number", pageNumber, "object_count", len(output.Contents))
pageMetadata := pageMetadata{
bucket: bucket,
role: role,
@@ -516,6 +536,10 @@ func (s *Source) scanBucket(
pageNumber++
}
scannedWholeBucket = startAfter == nil && !listFailed && ctx.Err() == nil
+ ctx.Logger().V(2).Info("Finished scanning bucket",
+ "objects_scanned", objectCount,
+ "pages", pageNumber-1,
+ "duration", time.Since(start))
// A filter that excludes everything otherwise looks exactly like a clean scan
// of an empty bucket, so say so rather than finishing silently.
@@ -572,6 +596,7 @@ func (s *Source) getRegionalClientForBucket(
if region == s.defaultRegion() {
return defaultRegionClient, nil
}
+ ctx.Logger().V(5).Info("Using regional client for bucket", "region", region)
regionalClient, err := s.newClient(ctx, region, role)
if err != nil {
@@ -632,7 +657,7 @@ func (s *Source) pageChunker(
if reason == skipReasonObjectFilter {
atomic.AddUint64(state.filteredCount, 1)
}
- octx.Logger().V(5).Info("Skipping object", "reason", reason)
+ octx.Logger().V(4).Info("Skipping object", "reason", reason)
s.metricsCollector.RecordObjectSkipped(metadata.bucket, reason, float64(*obj.Size))
if err := checkpointer.UpdateObjectCompletion(octx, objIdx, metadata.bucket, metadata.role, metadata.page.Contents); err != nil {
octx.Logger().Error(err, "could not update progress for skipped object", "reason", reason)
@@ -648,7 +673,7 @@ func (s *Source) pageChunker(
defer state.progress.objectDone(*obj.Size)
if strings.HasSuffix(*obj.Key, "/") {
- octx.Logger().V(5).Info("Skipping directory")
+ octx.Logger().V(4).Info("Skipping object", "reason", "directory")
s.metricsCollector.RecordObjectSkipped(metadata.bucket, "directory", float64(*obj.Size))
return nil
}
@@ -661,9 +686,11 @@ func (s *Source) pageChunker(
nErr = 0
}
if nErr.(int) > 3 {
- octx.Logger().V(2).Info("Skipped due to excessive errors")
+ octx.Logger().V(4).Info("Skipping object", "reason", "too many errors under prefix")
return nil
}
+ octx.Logger().V(3).Info("Scanning object")
+ start := time.Now()
// Make sure we use a separate context for the GetObjectWithContext call.
// This ensures that the timeout is isolated and does not affect any downstream operations. (e.g. HandleFile)
const getObjectTimeout = 30 * time.Second
@@ -695,14 +722,13 @@ func (s *Source) pageChunker(
nErr = 0
}
if nErr.(int) > 3 {
- octx.Logger().V(3).Info("Skipped due to excessive errors")
return nil
}
nErr = nErr.(int) + 1
state.errorCount.Store(prefix, nErr)
// too many consecutive errors on this page
if nErr.(int) > 3 {
- octx.Logger().V(2).Info("Too many consecutive errors, excluding prefix", "prefix", prefix)
+ octx.Logger().V(4).Info("Too many consecutive errors, excluding prefix", "prefix", prefix)
}
return nil
}
@@ -737,8 +763,8 @@ func (s *Source) pageChunker(
s.metricsCollector.RecordObjectError(metadata.bucket)
return nil
}
- atomic.AddUint64(state.objectCount, 1)
- octx.Logger().V(5).Info("S3 object scanned.", "object_count", state.objectCount)
+ objectCount := atomic.AddUint64(state.objectCount, 1)
+ octx.Logger().V(5).Info("Finished scanning object", "object_count", objectCount, "duration", time.Since(start))
nErr, ok = state.errorCount.Load(prefix)
if !ok {
nErr = 0
@@ -813,17 +839,23 @@ func (s *Source) visitRoles(
for _, role := range roles {
s.metricsCollector.RecordRoleScanned(role)
- client, err := s.newClient(ctx, s.defaultRegion(), role)
+ roleCtx := ctx
+ if role != "" {
+ roleCtx = context.WithValue(ctx, "role", role)
+ }
+
+ client, err := s.newClient(roleCtx, s.defaultRegion(), role)
if err != nil {
return fmt.Errorf("could not create s3 client: %w", err)
}
- bucketsToScan, err := s.getBucketsToScan(ctx, client)
+ bucketsToScan, err := s.getBucketsToScan(roleCtx, client)
if err != nil {
return fmt.Errorf("role %q could not list any s3 buckets for scanning: %w", role, err)
}
+ roleCtx.Logger().V(1).Info("Found buckets to scan", "bucket_count", len(bucketsToScan))
- if err := f(ctx, client, role, bucketsToScan); err != nil {
+ if err := f(roleCtx, client, role, bucketsToScan); err != nil {
return err
}
}
@@ -854,8 +886,8 @@ func (s *Source) objectLink(bucket, region, key string) string {
func (s *Source) Enumerate(ctx context.Context, reporter sources.UnitReporter) error {
visitor := func(c context.Context, defaultRegionClient *s3.Client, roleArn string, buckets []string) error {
for _, bucket := range buckets {
- if common.IsDone(ctx) {
- return ctx.Err()
+ if common.IsDone(c) {
+ return c.Err()
}
unit := S3SourceUnit{
@@ -863,7 +895,7 @@ func (s *Source) Enumerate(ctx context.Context, reporter sources.UnitReporter) e
Role: roleArn,
}
- if err := reporter.UnitOk(ctx, unit); err != nil {
+ if err := reporter.UnitOk(c, unit); err != nil {
return err
}
}
@@ -882,6 +914,9 @@ func (s *Source) ChunkUnit(ctx context.Context, unit sources.SourceUnit, reporte
if !ok {
return fmt.Errorf("expected *S3SourceUnit, got %T", unit)
}
+ if s3unit.Role != "" {
+ ctx = context.WithValue(ctx, "role", s3unit.Role)
+ }
// unitID is a combination of bucket name and role ARN
unitID, _ := s3unit.SourceUnitID()
defaultClient, err := s.newClient(ctx, s.defaultRegion(), s3unit.Role)
@@ -894,10 +929,10 @@ func (s *Source) ChunkUnit(ctx context.Context, unit sources.SourceUnit, reporte
var startAfterPtr *string
startAfter := s.GetEncodedResumeInfoFor(unitID)
if startAfter != "" {
- ctx.Logger().V(3).Info(
+ ctx.Logger().V(2).Info(
"Resuming unit scan",
"start_after", startAfter,
- "unitID", unitID,
+ "unit_id", unitID,
)
startAfterPtr = &startAfter
}
diff --git a/pkg/sources/s3/s3_test.go b/pkg/sources/s3/s3_test.go
index 5f5ecb640..e4b3192b0 100644
--- a/pkg/sources/s3/s3_test.go
+++ b/pkg/sources/s3/s3_test.go
@@ -4,24 +4,34 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
+ "net/http"
+ "net/http/httptest"
"os"
+ "strings"
"sync"
+ "sync/atomic"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/go-logr/zapr"
"github.com/kylelemons/godebug/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "go.uber.org/zap"
+ "go.uber.org/zap/zapcore"
+ "go.uber.org/zap/zaptest/observer"
"google.golang.org/protobuf/types/known/anypb"
"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/log/logtest"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/credentialspb"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"
"github.com/trufflesecurity/trufflehog/v3/pkg/sources"
+ "github.com/trufflesecurity/trufflehog/v3/pkg/sourcestest"
)
func TestSource_Init_IncludeAndIgnoreBucketsError(t *testing.T) {
@@ -648,3 +658,121 @@ func TestSource_SkipReason(t *testing.T) {
})
}
}
+
+// slowDownOnce answers the first GET of key with S3's throttling error, so the client retries it.
+type slowDownOnce struct {
+ next http.Handler
+ key string
+ done atomic.Bool
+}
+
+func (h *slowDownOnce) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/"+h.key) && h.done.CompareAndSwap(false, true) {
+ w.Header().Set("Content-Type", "application/xml")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ _, _ = w.Write([]byte(`<Error><Code>SlowDown</Code><Message>Please reduce your request rate.</Message></Error>`))
+ return
+ }
+ h.next.ServeHTTP(w, r)
+}
+
+func TestSource_DebugLogging(t *testing.T) {
+ const testSecret = "TESTSECRET-do-not-log-1234567890"
+
+ // One object of each kind the source logs about: scanned, empty, excluded by the filter, and a directory.
+ fake := &fakeS3{buckets: map[string]fakeBucket{"bucket": {objects: map[string]string{
+ "config.txt": "aws_secret = " + testSecret,
+ "empty.txt": "",
+ "archive/old.txt": "aws_secret = " + testSecret,
+ "dir/": "x",
+ }}}}
+
+ // run the source with both Chunks and ChunkUnit, draining chunks the way the engine does
+ runSource := func(t *testing.T, ctx context.Context) {
+ server := httptest.NewServer(&slowDownOnce{next: fake, key: "config.txt"})
+ t.Cleanup(server.Close)
+ conn, err := anypb.New(&sourcespb.S3{
+ Credential: &sourcespb.S3_Unauthenticated{},
+ Endpoint: server.URL,
+ Buckets: []string{"bucket"},
+ ExcludePrefixes: []string{"archive/"},
+ })
+ require.NoError(t, err)
+
+ s := Source{}
+ require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))
+
+ chunksCh := make(chan *sources.Chunk, 64)
+ go func() {
+ for range chunksCh {
+ }
+ }()
+ require.NoError(t, s.Chunks(ctx, chunksCh))
+ close(chunksCh)
+
+ reporter := sourcestest.TestReporter{}
+ require.NoError(t, s.ChunkUnit(ctx, S3SourceUnit{Bucket: "bucket"}, &reporter))
+ require.Empty(t, reporter.ChunkErrs)
+ require.NotEmpty(t, reporter.Chunks)
+ }
+
+ t.Run("debug on", func(t *testing.T) {
+ ctx, logs := logtest.DebugContext()
+ ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)
+ runSource(t, ctx)
+
+ // lines from each level show up
+ for _, msg := range []string{
+ "S3 source initialized", // V(1)
+ "Found buckets to scan", // V(1)
+ "Scanning bucket", // V(2)
+ "Finished scanning bucket", // V(2)
+ "Scanning object", // V(3)
+ "Listed page", // V(4)
+ "Finished scanning object", // V(5)
+ } {
+ assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)
+ }
+
+ // every skip says why, at V(4)
+ var reasons []string
+ for _, entry := range logs.FilterMessage("Skipping object").All() {
+ reasons = append(reasons, fmt.Sprint(entry.ContextMap()["reason"]))
+ }
+ assert.Contains(t, reasons, skipReasonEmptyFile)
+ assert.Contains(t, reasons, skipReasonObjectFilter)
+ assert.Contains(t, reasons, "directory")
+
+ // the throttled GET was retried, and the retry was logged through the request's context
+ var retried bool
+ for _, entry := range logs.FilterMessage("AWS SDK").All() {
+ fields := entry.ContextMap()
+ if strings.Contains(fmt.Sprint(fields["detail"]), "retrying request") {
+ retried = true
+ assert.Equal(t, "config.txt", fields["key"])
+ }
+ }
+ assert.True(t, retried, "missing retry log line")
+
+ // every line came from the context logger, so it carries the source fields,
+ // and none of them contain the secret
+ for _, entry := range logs.All() {
+ fields := entry.ContextMap()
+ assert.Contains(t, fields, "source_name", "line %q", entry.Message)
+ assert.Contains(t, fields, "job_id", "line %q", entry.Message)
+ assert.NotContains(t, entry.Message, testSecret)
+ assert.NotContains(t, fmt.Sprint(fields), testSecret)
+ }
+ })
+
+ t.Run("debug off", func(t *testing.T) {
+ core, logs := observer.New(zapcore.InfoLevel)
+ ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))
+ runSource(t, ctx)
+
+ assert.Zero(t, logs.FilterMessage("Scanning object").Len())
+ assert.Zero(t, logs.FilterMessage("Skipping object").Len())
+ assert.Zero(t, logs.FilterMessage("Finished scanning object").Len())
+ assert.Zero(t, logs.FilterMessage("AWS SDK").Len())
+ })
+}
diff --git a/pkg/sources/s3/sdklog.go b/pkg/sources/s3/sdklog.go
new file mode 100644
index 000000000..66e986f7d
--- /dev/null
+++ b/pkg/sources/s3/sdklog.go
@@ -0,0 +1,34 @@
+package s3
+
+import (
+ stdctx "context"
+ "fmt"
+
+ "github.com/aws/smithy-go/logging"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+// sdkLogger passes the AWS SDK's retry logs to the logger of the request's
+// context, so they carry that request's fields and follow per-source debug.
+// The zero value is what the client holds. It drops anything logged without a
+// request context, since there is no logger to send it to.
+type sdkLogger struct {
+ ctx stdctx.Context
+}
+
+var _ logging.ContextLogger = sdkLogger{}
+
+func (l sdkLogger) WithContext(ctx stdctx.Context) logging.Logger {
+ return sdkLogger{ctx: ctx}
+}
+
+func (l sdkLogger) Logf(_ logging.Classification, format string, v ...any) {
+ if l.ctx == nil {
+ return
+ }
+ logger := context.AddLogger(l.ctx).Logger().V(4)
+ if logger.Enabled() {
+ logger.Info("AWS SDK", "detail", fmt.Sprintf(format, v...))
+ }
+}