Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Clean up Docker source logging for per-source debug (#5494)
Kashif Khan020634ef8ce1
diff --git a/pkg/sources/docker/README.md b/pkg/sources/docker/README.mdindex 79845ae22..aaf4a9c33 100644--- a/pkg/sources/docker/README.md+++ b/pkg/sources/docker/README.md@@ -291,6 +291,18 @@ docker login my-registry.iotrufflehog docker --image my-registry.io/private-app:v1.0.0```+## Debug Logs++With debug on for this source (`debug: true` in the config), the scan logs:++- `V(1)`: `Docker source initialized` with the config choices (the credential type only, never the credentials), and the start and end of a namespace listing with its image count.+- `V(2)`: `Scanning image` with its layer and history entry counts, and `Finished scanning image` with its duration.+- `V(3)`: `Scanning image history entry` for each history entry, and the start and end of each layer, with how many files it held, how many were skipped, and its duration.+- `V(4)`: `Skipping file` with a `reason` (too large, or matches an exclude pattern), `Listed registry page` for each page of a namespace listing, `Registry request failed` for any registry response of 400 or above or any network error (with the status, host, path and `Retry-After` header), and `Retrying registry API request` for each namespace listing retry.+- `V(5)`: `Loading image` with where it comes from (remote, daemon or tarball), and `Scanning file` for each file.++Lines carry `image`, `tag`, `layer` and `file` where they apply. A `401` on `/v2/` is the normal auth challenge a registry sends before a token request, not an error on its own.+## Troubleshooting### Common Issuesdiff --git a/pkg/sources/docker/docker.go b/pkg/sources/docker/docker.goindex ea376610a..1e9e2adff 100644--- a/pkg/sources/docker/docker.go+++ b/pkg/sources/docker/docker.go@@ -92,9 +92,33 @@ func (s *Source) Init(ctx context.Context, name string, jobId sources.JobID, sou}}+ ctx.Logger().V(1).Info("Docker source initialized",+ "auth_method", authMethod(&s.conn),+ "image_count", len(s.conn.GetImages()),+ "namespace", s.conn.GetNamespace(),+ "exclude_paths", s.conn.GetExcludePaths(),+ "concurrency", s.concurrency,+ )+return nil}+// authMethod names the configured credential type without its values.+func authMethod(conn *sourcespb.Docker) string {+ switch conn.GetCredential().(type) {+ case *sourcespb.Docker_Unauthenticated:+ return "unauthenticated"+ case *sourcespb.Docker_BasicAuth:+ return "basic_auth"+ case *sourcespb.Docker_BearerToken:+ return "bearer_token"+ case *sourcespb.Docker_DockerKeychain:+ return "docker_keychain"+ default:+ return "none"+ }+}+// imageInfo holds information about a Docker image being processedtype imageInfo struct {image v1.Image // The image object from go-containerregistry@@ -120,7 +144,6 @@ type layerInfo struct {// Chunks emits data over a channel that is decoded and scanned for secrets.func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ ...sources.ChunkingTarget) error {- ctx = context.WithValues(ctx, "source_type", s.Type(), "source_name", s.name)jobIDStr := fmt.Sprint(s.jobId)workers := new(errgroup.Group)@@ -151,10 +174,9 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .continue}+ imageStart := time.Now()imageCtx := context.WithValues(ctx, "image", imgInfo.base, "tag", imgInfo.tag)- imageCtx.Logger().V(2).Info("scanning image history")-layers, err := imgInfo.image.Layers()if err != nil {imageCtx.Logger().Error(err, "error getting image layers")@@ -170,6 +192,8 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .}dockerHistoryEntriesEnumerated.WithLabelValues(s.name, jobIDStr).Add(float64(len(historyEntries)))+ imageCtx.Logger().V(2).Info("Scanning image", "layers", len(layers), "history_entries", len(historyEntries))+// Scan each history entry for secrets in build commandsfor _, historyEntry := range historyEntries {if err := s.processHistoryEntry(imageCtx, historyEntry, chunksChan); err != nil {@@ -179,13 +203,14 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .dockerHistoryEntriesScanned.WithLabelValues(s.name, jobIDStr).Inc()}- imageCtx.Logger().V(2).Info("scanning image layers")-// Process each layer concurrentlyfor _, layer := range layers {workers.Go(func() error {if err := s.processLayer(imageCtx, layer, imgInfo, chunksChan); err != nil {- imageCtx.Logger().Error(err, "error processing layer")+ // a cancelled scan fails every layer left, which is not a layer error+ if imageCtx.Err() == nil {+ imageCtx.Logger().Error(err, "error processing layer")+ }return nil}dockerLayersScanned.WithLabelValues(s.name, jobIDStr).Inc()@@ -200,6 +225,7 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .}dockerImagesScanned.WithLabelValues(s.name, jobIDStr).Inc()+ imageCtx.Logger().V(2).Info("Finished scanning image", "duration", time.Since(imageStart))}return nil@@ -208,14 +234,13 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .// processImage processes an individual image and prepares it for further processing.// It handles three image source types: remote registry, local daemon, and tarball file.func (s *Source) processImage(ctx context.Context, image string) (imageInfo, error) {- ctx.Logger().V(5).Info("Processing individual Image")var (imgInfo imageInfoimageName name.Referenceerr error)- remoteOpts, err := s.remoteOpts()+ remoteOpts, err := s.remoteOpts(ctx)if err != nil {return imgInfo, err}@@ -225,6 +250,7 @@ func (s *Source) processImage(ctx context.Context, image string) (imageInfo, err// Handle tarball file imagesif image, ok := strings.CutPrefix(image, filePrefix); ok {+ ctx.Logger().V(5).Info("Loading image", "image", image, "image_source", "tarball")imgInfo.base = imageimgInfo.image, err = tarball.ImageFromPath(image, nil)if err != nil {@@ -232,16 +258,18 @@ func (s *Source) processImage(ctx context.Context, image string) (imageInfo, err}// Handle local Docker daemon images} else if image, ok := strings.CutPrefix(image, dockerPrefix); ok {+ ctx.Logger().V(5).Info("Loading image", "image", image, "image_source", "daemon")imgInfo, imageName, err = s.extractImageNameTagDigest(image)if err != nil {return imgInfo, err}- imgInfo.image, err = daemon.Image(imageName)+ imgInfo.image, err = daemon.Image(imageName, daemon.WithContext(ctx))if err != nil {return imgInfo, err}// Handle remote registry images (default)} else {+ ctx.Logger().V(5).Info("Loading image", "image", image, "image_source", "remote")imgInfo, imageName, err = s.extractImageNameTagDigest(image)if err != nil {return imgInfo, err@@ -252,8 +280,6 @@ func (s *Source) processImage(ctx context.Context, image string) (imageInfo, err}}- ctx.Logger().WithValues("image", imgInfo.base, "tag", imgInfo.tag).V(2).Info("scanning image")-return imgInfo, nil}@@ -316,7 +342,7 @@ func getHistoryEntries(ctx context.Context, imgInfo imageInfo, layers []v1.Layer"layerIndex", layerIndex, "historyIndex", historyIndex)}} else {- ctx.Logger().V(2).Info("cannot associate layer with history entry: no correlated layer exists at this index",+ ctx.Logger().V(4).Info("cannot associate layer with history entry: no correlated layer exists at this index","layerIndex", layerIndex, "historyIndex", historyIndex)}@@ -332,7 +358,6 @@ func getHistoryEntries(ctx context.Context, imgInfo imageInfo, layers []v1.Layer// processHistoryEntry processes a history entry from the image configuration metadata.// It scans the CreatedBy field which contains the command used to create that layer.func (s *Source) processHistoryEntry(ctx context.Context, historyInfo historyEntryInfo, chunksChan chan *sources.Chunk) error {- ctx.Logger().V(5).Info("Processing history entries")// Create a descriptive identifier for this history entry// There's no file name here, so we use a synthetic pathentryPath := fmt.Sprintf("image-metadata:history:%d:created-by", historyInfo.index)@@ -355,7 +380,7 @@ func (s *Source) processHistoryEntry(ctx context.Context, historyInfo historyEntData: []byte(historyInfo.entry.CreatedBy),}- ctx.Logger().V(2).Info("scanning image history entry", "index", historyInfo.index, "layer", historyInfo.layerDigest)+ ctx.Logger().V(3).Info("Scanning image history entry", "history_index", historyInfo.index, "layer", historyInfo.layerDigest)return common.CancellableWrite(ctx, chunksChan, chunk)}@@ -363,8 +388,7 @@ func (s *Source) processHistoryEntry(ctx context.Context, historyInfo historyEnt// processLayer processes an individual layer of an image.// It decompresses the layer and extracts all files for scanning.func (s *Source) processLayer(ctx context.Context, layer v1.Layer, imgInfo imageInfo, chunksChan chan *sources.Chunk) error {- ctx.Logger().V(5).Info("Processing layer")-+ start := time.Now()layerInfo := layerInfo{base: imgInfo.base,tag: imgInfo.tag,@@ -376,7 +400,8 @@ func (s *Source) processLayer(ctx context.Context, layer v1.Layer, imgInfo imagereturn err}- ctx.Logger().WithValues("layer", layerInfo.digest.String()).V(2).Info("scanning layer")+ ctx = context.WithValues(ctx, "layer", layerInfo.digest.String())+ ctx.Logger().V(3).Info("Scanning layer")rc, err := layer.Compressed()if err != nil {@@ -398,6 +423,7 @@ func (s *Source) processLayer(ctx context.Context, layer v1.Layer, imgInfo image// Layers are tar archives, so we read them as tar filestarReader := tar.NewReader(gzipReader)+ var files, skipped intfor {header, err := tarReader.Next()if errors.Is(err, io.EOF) {@@ -408,11 +434,17 @@ func (s *Source) processLayer(ctx context.Context, layer v1.Layer, imgInfo image}info := chunkProcessingInfo{size: header.Size, name: header.Name, reader: tarReader, layer: layerInfo}- if err := s.processChunk(ctx, info, chunksChan); err != nil {+ scanned, err := s.processChunk(ctx, info, chunksChan)+ if err != nil {return err}+ files+++ if !scanned {+ skipped+++ }}+ ctx.Logger().V(3).Info("Finished scanning layer", "files", files, "skipped", skipped, "duration", time.Since(start))return nil}@@ -425,28 +457,31 @@ type chunkProcessingInfo struct {}// processChunk processes an individual chunk of a layer.-// It applies file size limits and exclusion patterns before scanning.-func (s *Source) processChunk(ctx context.Context, info chunkProcessingInfo, chunksChan chan *sources.Chunk) error {+// It applies file size limits and exclusion patterns before scanning, and+// reports whether the file was scanned.+func (s *Source) processChunk(ctx context.Context, info chunkProcessingInfo, chunksChan chan *sources.Chunk) (bool, error) {// Skip files that are too large to avoid memory issuesconst filesizeLimitBytes int64 = 50 * 1024 * 1024 // 50MBif info.size > filesizeLimitBytes {- ctx.Logger().V(2).Info("skipping file: size exceeds max allowed", "file", info.name, "size", info.size, "limit", filesizeLimitBytes)- return nil+ ctx.Logger().V(4).Info("Skipping file", "file", info.name, "reason", "too large", "size", info.size, "limit", filesizeLimitBytes)+ return false, nil}// Check if the file matches any exclude patternsfilePath := "/" + info.nameif s.isExcluded(ctx, filePath) {- return nil+ return false, nil}+ ctx.Logger().V(5).Info("Scanning file", "file", filePath, "size", info.size)+// Read the file in chunks to handle large files efficientlychunkReader := sources.NewChunkReader(sources.WithFileSize(int(info.size)))chunkResChan := chunkReader(ctx, info.reader)for data := range chunkResChan {if err := data.Error(); err != nil {- ctx.Logger().Error(err, "error reading chunk.")+ ctx.Logger().Error(err, "error reading chunk", "file", filePath)continue}@@ -469,11 +504,11 @@ func (s *Source) processChunk(ctx context.Context, info chunkProcessingInfo, chuchunk.Data = data.Bytes()if err := common.CancellableWrite(ctx, chunksChan, chunk); err != nil {- return err+ return true, err}}- return nil+ return true, nil}// isExcluded checks if a given filePath should be excluded based on the configured glob patterns.@@ -487,14 +522,14 @@ func (s *Source) isExcluded(ctx context.Context, filePath string) bool {isIncluded := s.globFilter.ShouldInclude(filePath)if !isIncluded {- ctx.Logger().V(2).Info("skipping file: matches an exclude pattern", "file", filePath, "configured_exclude_paths", s.conn.GetExcludePaths())+ ctx.Logger().V(4).Info("Skipping file", "file", filePath, "reason", "matches exclude pattern")}return !isIncluded}// remoteOpts configures the options for fetching images from remote registries.// It sets up HTTP transport and authentication based on the connection configuration.-func (s *Source) remoteOpts() ([]remote.Option, error) {+func (s *Source) remoteOpts(ctx context.Context) ([]remote.Option, error) {// Configure HTTP transport with reasonable timeouts and connection poolingdefaultTransport := &http.Transport{Proxy: http.ProxyFromEnvironment,@@ -510,13 +545,19 @@ func (s *Source) remoteOpts() ([]remote.Option, error) {MaxIdleConnsPerHost: s.concurrency * 2,}- var opts []remote.Option- opts = append(opts, remote.WithTransport(common.NewInstrumentedTransport(common.NewCustomTransport(defaultTransport))))+ // The context lets a cancelled scan stop a slow pull, and lets the+ // registry log lines carry the source fields.+ opts := []remote.Option{+ remote.WithContext(ctx),+ remote.WithTransport(®istryLogTransport{+ T: common.NewInstrumentedTransport(common.NewCustomTransport(defaultTransport)),+ }),+ }// Configure authentication based on credential typeswitch s.conn.GetCredential().(type) {case *sourcespb.Docker_Unauthenticated:- return nil, nil+ // no auth option, but keep the transport and contextcase *sourcespb.Docker_BasicAuth:opts = append(opts, remote.WithAuth(&authn.Basic{Username: s.conn.GetBasicAuth().GetUsername(),@@ -537,8 +578,7 @@ func (s *Source) remoteOpts() ([]remote.Option, error) {}func GetNamespaceImages(ctx context.Context, namespace, registryToken string) ([]string, error) {- ctx.Logger().V(5).Info("Getting namespace images")-+ start := time.Now()registry := MakeRegistryFromNamespace(namespace)// attach the registry authentication token, if one is available.@@ -546,14 +586,19 @@ func GetNamespaceImages(ctx context.Context, namespace, registryToken string) ([registry.WithRegistryToken(registryToken)}- ctx.Logger().Info(fmt.Sprintf("using registry: %s", registry.Name()))+ ctx.Logger().V(1).Info("Listing namespace images", "registry", registry.Name(), "namespace", namespace)namespaceImages, err := registry.ListImages(ctx, namespace)if err != nil {return nil, fmt.Errorf("failed to list namespace images: %w", err)}- ctx.Logger().Info(fmt.Sprintf("namespace: %s has %d images", namespace, len(namespaceImages)))+ ctx.Logger().V(1).Info("Listed namespace images",+ "registry", registry.Name(),+ "namespace", namespace,+ "count", len(namespaceImages),+ "duration", time.Since(start),+ )return namespaceImages, nil}diff --git a/pkg/sources/docker/docker_test.go b/pkg/sources/docker/docker_test.goindex bd8b026a5..6372d98b7 100644--- a/pkg/sources/docker/docker_test.go+++ b/pkg/sources/docker/docker_test.go@@ -1,16 +1,37 @@package dockerimport (+ "archive/tar"+ "bytes"+ "fmt""io"+ stdlog "log"+ "net/http"+ "net/http/httptest""strings""sync"+ "sync/atomic""testing"+ "github.com/go-logr/zapr"+ "github.com/google/go-containerregistry/pkg/name"+ "github.com/google/go-containerregistry/pkg/registry"+ v1 "github.com/google/go-containerregistry/pkg/v1"+ "github.com/google/go-containerregistry/pkg/v1/empty"+ "github.com/google/go-containerregistry/pkg/v1/mutate"+ "github.com/google/go-containerregistry/pkg/v1/remote"+ "github.com/google/go-containerregistry/pkg/v1/tarball"dockerClient "github.com/moby/moby/client""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/source_metadatapb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"@@ -427,3 +448,168 @@ func TestDockerScanWithExclusions(t *testing.T) {assert.False(t, foundExcludedPath, "Found a chunk that should have been excluded")}++func TestSource_DebugLogging(t *testing.T) {+ const testSecret = "dockerdebuglogtestsecret"++ // newFakeRegistry pushes an image with one layer holding a secret file and an+ // excluded file. After the push, the first manifest GET fails with a 503, so+ // the scan has to retry it.+ newFakeRegistry := func(t *testing.T) string {+ var tarBuf bytes.Buffer+ tw := tar.NewWriter(&tarBuf)+ for name, content := range map[string]string{+ "secret.txt": "token=" + testSecret,+ "skip/me.txt": "nothing to see",+ } {+ require.NoError(t, tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(content))}))+ _, err := tw.Write([]byte(content))+ require.NoError(t, err)+ }+ require.NoError(t, tw.Close())++ layer, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) {+ return io.NopCloser(bytes.NewReader(tarBuf.Bytes())), nil+ })+ require.NoError(t, err)+ img, err := mutate.Append(empty.Image, mutate.Addendum{+ Layer: layer,+ History: v1.History{CreatedBy: "COPY . /"},+ })+ require.NoError(t, err)++ var armed, failed atomic.Bool+ reg := registry.New(registry.Logger(stdlog.New(io.Discard, "", 0)))+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if armed.Load() && r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/manifests/") && !failed.Swap(true) {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ reg.ServeHTTP(w, r)+ }))+ t.Cleanup(srv.Close)++ ref := strings.TrimPrefix(srv.URL, "http://") + "/test/image:v1"+ tag, err := name.NewTag(ref)+ require.NoError(t, err)+ require.NoError(t, remote.Write(tag, img))+ armed.Store(true)+ return ref+ }++ runSource := func(t *testing.T, ctx context.Context) {+ conn, err := anypb.New(&sourcespb.Docker{+ Credential: &sourcespb.Docker_Unauthenticated{+ Unauthenticated: &credentialspb.Unauthenticated{},+ },+ Images: []string{newFakeRegistry(t)},+ ExcludePaths: []string{"/skip/*"},+ })+ require.NoError(t, err)++ s := &Source{}+ require.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))++ chunksChan := make(chan *sources.Chunk, 8)+ require.NoError(t, s.Chunks(ctx, chunksChan))+ close(chunksChan)++ var files []string+ for chunk := range chunksChan {+ files = append(files, chunk.SourceMetadata.GetDocker().GetFile())+ }+ assert.ElementsMatch(t, []string{"image-metadata:history:0:created-by", "/secret.txt"}, files)+ }++ 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{+ "Docker source initialized", // V(1)+ "Scanning image", // V(2)+ "Finished scanning image", // V(2)+ "Scanning image history entry", // V(3)+ "Scanning layer", // V(3)+ "Finished scanning layer", // V(3)+ "Skipping file", // V(4)+ "Registry request failed", // V(4)+ "Loading image", // V(5)+ "Scanning file", // V(5)+ } {+ assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)+ }++ // the skip says why, and carries the layer+ skips := logs.FilterMessage("Skipping file").All()+ require.Len(t, skips, 1)+ assert.Equal(t, "/skip/me.txt", skips[0].ContextMap()["file"])+ assert.Equal(t, "matches exclude pattern", skips[0].ContextMap()["reason"])+ assert.Contains(t, skips[0].ContextMap(), "layer")++ layerDone := logs.FilterMessage("Finished scanning layer").All()+ require.Len(t, layerDone, 1)+ assert.EqualValues(t, 2, layerDone[0].ContextMap()["files"])+ assert.EqualValues(t, 1, layerDone[0].ContextMap()["skipped"])++ // the failed manifest request says what failed+ var manifestFailed bool+ for _, entry := range logs.FilterMessage("Registry request failed").All() {+ if entry.ContextMap()["status"] == int64(http.StatusServiceUnavailable) {+ manifestFailed = true+ assert.Equal(t, "/v2/test/image/manifests/v1", entry.ContextMap()["path"])+ }+ }+ assert.True(t, manifestFailed, "missing 503 registry 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.Len(), "unexpected lines: %v", logs.All())+ })+}++func TestDockerHub_ListImagesDebugLogging(t *testing.T) {+ ctx, logs := logtest.DebugContext()++ hub := &DockerHub{Client: &http.Client{Transport: common.FakeTransport{+ CreateResponse: func(req *http.Request) (*http.Response, error) {+ body := `{"next": "/v2/namespaces/acme/repositories?page=2", "results": [{"name": "one"}, {"name": "two"}]}`+ if req.URL.Query().Get("page") == "2" {+ body = `{"results": [{"name": "three"}]}`+ }+ return &http.Response{+ Request: req,+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(body)),+ }, nil+ },+ }}}++ images, err := hub.ListImages(ctx, "acme")+ require.NoError(t, err)+ assert.Equal(t, []string{"acme/one", "acme/two", "acme/three"}, images)++ pages := logs.FilterMessage("Listed registry page").All()+ require.Len(t, pages, 2)+ for i, want := range []int{2, 1} {+ assert.EqualValues(t, i+1, pages[i].ContextMap()["page"])+ assert.EqualValues(t, want, pages[i].ContextMap()["images"])+ assert.Equal(t, "Dockerhub", pages[i].ContextMap()["registry"])+ }+}diff --git a/pkg/sources/docker/registries.go b/pkg/sources/docker/registries.goindex b4402c508..1dbbd57a5 100644--- a/pkg/sources/docker/registries.go+++ b/pkg/sources/docker/registries.go@@ -11,12 +11,13 @@ import ("strings""github.com/trufflesecurity/trufflehog/v3/pkg/common"+ logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context""golang.org/x/time/rate")// defaultHTTPClient defines a shared HTTP client with timeout for all registry requests.-var defaultHTTPClient = common.RetryableHTTPClientTimeout(10)+var defaultHTTPClient = common.RetryableHTTPClientTimeout(10, withRegistryLogHooks())// registryRateLimiter limits how quickly we make registry API calls across all registries.// We allow roughly 1 event every 1.5s, with a burst of 2 as a simple safeguard against overloading upstream APIs.@@ -100,7 +101,7 @@ func (d *DockerHub) ListImages(ctx context.Context, namespace string) ([]string,allImages := []string{}nextURL := baseURL.String()- for {+ for pageNum := 1; ; pageNum++ {if err := registryRateLimiter.Wait(ctx); err != nil {return nil, err}@@ -141,6 +142,7 @@ func (d *DockerHub) ListImages(ctx context.Context, namespace string) ([]string,for _, image := range page.Results {allImages = append(allImages, fmt.Sprintf("%s/%s", namespace, image.Name)) // <namespace>/<image_name>}+ logRegistryPage(ctx, d.Name(), pageNum, len(page.Results))if page.Next == "" {break@@ -203,7 +205,7 @@ func (q *Quay) ListImages(ctx context.Context, namespace string) ([]string, erroallImages := []string{}nextPageToken := ""- for {+ for pageNum := 1; ; pageNum++ {if err := registryRateLimiter.Wait(ctx); err != nil {return nil, err}@@ -256,6 +258,7 @@ func (q *Quay) ListImages(ctx context.Context, namespace string) ([]string, errofor _, image := range page.Repositories {allImages = append(allImages, fmt.Sprintf("%s/%s", namespace, image.Name)) // quay.io/<namespace>/<image_name>}+ logRegistryPage(ctx, q.Name(), pageNum, len(page.Repositories))if !page.HasAdditional || page.NextPage == "" {break@@ -352,7 +355,7 @@ func (g *GHCR) ListImages(ctx context.Context, namespace string) ([]string, erroreturn u.String()}()- for nextURL != "" {+ for pageNum := 1; nextURL != ""; pageNum++ {if err := registryRateLimiter.Wait(ctx); err != nil {return nil, err}@@ -398,6 +401,7 @@ func (g *GHCR) ListImages(ctx context.Context, namespace string) ([]string, errofor _, image := range page {allImages = append(allImages, fmt.Sprintf("%s/%s", namespace, image.Name)) // ghcr.io/<namespace>/<image_name>}+ logRegistryPage(ctx, g.Name(), pageNum, len(page))// Determine if there's another page via the Link header.nextURL = parseNextLinkURL(resp.Header.Get("Link"))@@ -406,6 +410,15 @@ func (g *GHCR) ListImages(ctx context.Context, namespace string) ([]string, erroreturn allImages, nil}+// logRegistryPage logs one page of a namespace listing.+func logRegistryPage(ctx context.Context, registry string, page, images int) {+ logContext.AddLogger(ctx).Logger().V(4).Info("Listed registry page",+ "registry", registry,+ "page", page,+ "images", images,+ )+}+// Function to discard response bodyfunc discardBody(resp *http.Response) {if resp != nil && resp.Body != nil {diff --git a/pkg/sources/docker/registrylog.go b/pkg/sources/docker/registrylog.gonew file mode 100644index 000000000..e23b9a50b--- /dev/null+++ b/pkg/sources/docker/registrylog.go@@ -0,0 +1,77 @@+package docker++import (+ "net/http"++ "github.com/hashicorp/go-retryablehttp"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"+)++// registryLogTransport logs failed requests to an image registry. go-containerregistry+// only reports its own retries through a global logger, so this is where support can+// see registry errors and rate limits. It logs through the request's context, so+// image fetches must pass remote.WithContext(ctx) for the line to carry the source+// fields and follow per-source debug.+type registryLogTransport struct {+ T http.RoundTripper+}++func (t *registryLogTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ resp, err := t.T.RoundTrip(req)+ if err != nil {+ context.AddLogger(req.Context()).Logger().V(4).Info("Registry request failed",+ "method", req.Method,+ "host", req.URL.Host,+ "path", req.URL.Path,+ "error", err.Error(),+ )+ return resp, err+ }+ // a 401 on /v2/ is the normal auth challenge before a token request, so a+ // failed line there alone is not an error+ if resp.StatusCode >= 400 {+ logRegistryResponse(resp)+ }+ return resp, nil+}++// withRegistryLogHooks adds the retry and response hooks to the client the registry+// listers use.+func withRegistryLogHooks() common.ClientOption {+ return func(c *retryablehttp.Client) {+ c.RequestLogHook = logRegistryRetry+ c.ResponseLogHook = func(_ retryablehttp.Logger, resp *http.Response) {+ if resp.StatusCode >= 400 {+ logRegistryResponse(resp)+ }+ }+ }+}++// logRegistryRetry is a retryablehttp.RequestLogHook. It runs before every attempt+// and logs the ones that are retries.+func logRegistryRetry(_ retryablehttp.Logger, req *http.Request, attempt int) {+ if attempt == 0 {+ return+ }+ context.AddLogger(req.Context()).Logger().V(4).Info("Retrying registry API request",+ "method", req.Method,+ "host", req.URL.Host,+ "path", req.URL.Path,+ "attempt", attempt,+ )+}++// logRegistryResponse logs a failed registry response. Only the path is logged,+// not the query, since token requests carry the scope there.+func logRegistryResponse(resp *http.Response) {+ context.AddLogger(resp.Request.Context()).Logger().V(4).Info("Registry request failed",+ "method", resp.Request.Method,+ "host", resp.Request.URL.Host,+ "path", resp.Request.URL.Path,+ "status", resp.StatusCode,+ "retry_after", resp.Header.Get("Retry-After"),+ )+}