diff --git a/pkg/action/scan.go b/pkg/action/scan.go index 096e3ffa0..9aab19ab4 100644 --- a/pkg/action/scan.go +++ b/pkg/action/scan.go @@ -497,6 +497,14 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi if err != nil { return nil, fmt.Errorf("extract to temp: %w", err) } + // Ensure that tmpRoot is removed before returning if created successfully + if tmpRoot != "" { + defer func() { + if err := os.RemoveAll(tmpRoot); err != nil { + logger.Errorf("remove %s: %v", tmpRoot, err) + } + }() + } // macOS will prefix temporary directories with `/private` // update tmpRoot with this prefix to allow strings.TrimPrefix to work if runtime.GOOS == "darwin" { @@ -515,13 +523,10 @@ func processArchive(ctx context.Context, c malcontent.Config, rfs []fs.FS, archi } if fr != nil { // Store a clean reprepsentation of the archive's scanned file to match single file scanning behavior - extractedFilePath = strings.TrimPrefix(extractedFilePath, tmpRoot) - frs.Store(extractedFilePath, fr) + clean := strings.TrimPrefix(extractedFilePath, tmpRoot) + frs.Store(clean, fr) } } - if err := os.RemoveAll(tmpRoot); err != nil { - logger.Errorf("remove %s: %v", tmpRoot, err) - } return &frs, nil }