Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
[INS-206] Store Gitlab Project ID in secret location metadata (#4601)
Mustansira633174c3b22
diff --git a/pkg/sources/gitlab/gitlab.go b/pkg/sources/gitlab/gitlab.goindex 741e58115..b2ed4ce68 100644--- a/pkg/sources/gitlab/gitlab.go+++ b/pkg/sources/gitlab/gitlab.go@@ -77,6 +77,9 @@ type Source struct {printLegacyJSON boolprojectsPerPage int++ // cache of repo URL to project info, used when generating metadata for chunks+ repoToProjCache repoToProjectCache}// WithCustomContentWriter sets the useCustomContentWriter flag on the source.@@ -227,18 +230,26 @@ func (s *Source) Init(ctx context.Context, name string, jobId sources.JobID, souSkipArchives: conn.GetSkipArchives(),Concurrency: concurrency,SourceMetadataFunc: func(file, email, commit, timestamp, repository, repositoryLocalPath string, line int64) *source_metadatapb.MetaData {+ gitlabMetadata := &source_metadatapb.Gitlab{+ Commit: sanitizer.UTF8(commit),+ File: sanitizer.UTF8(file),+ Email: sanitizer.UTF8(email),+ Repository: sanitizer.UTF8(repository),+ RepositoryLocalPath: sanitizer.UTF8(repositoryLocalPath),+ Link: giturl.GenerateLink(repository, commit, file, line),+ Timestamp: sanitizer.UTF8(timestamp),+ Line: line,+ }+ proj, ok := s.repoToProjCache.get(repository)+ if ok {+ gitlabMetadata.ProjectId = int64(proj.id)+ gitlabMetadata.ProjectName = proj.name+ gitlabMetadata.ProjectOwner = proj.owner+ }+return &source_metadatapb.MetaData{Data: &source_metadatapb.MetaData_Gitlab{- Gitlab: &source_metadatapb.Gitlab{- Commit: sanitizer.UTF8(commit),- File: sanitizer.UTF8(file),- Email: sanitizer.UTF8(email),- Repository: sanitizer.UTF8(repository),- RepositoryLocalPath: sanitizer.UTF8(repositoryLocalPath),- Link: giturl.GenerateLink(repository, commit, file, line),- Timestamp: sanitizer.UTF8(timestamp),- Line: line,- },+ Gitlab: gitlabMetadata,},}},@@ -247,6 +258,10 @@ func (s *Source) Init(ctx context.Context, name string, jobId sources.JobID, sou}s.git = git.NewGit(cfg)+ s.repoToProjCache = repoToProjectCache{+ cache: make(map[string]*project),+ }+return nil}@@ -297,6 +312,11 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, tar} else {gitlabReposEnumerated.WithLabelValues(s.name).Set(float64(len(repos)))+ // ensure project details for specified repos are cached+ // this is required to populate metadata during chunking+ for _, repo := range repos {+ s.ensureProjectInCache(ctx, repo)+ }}s.repos = repos@@ -548,6 +568,7 @@ func (s *Source) getAllProjectRepos(}// Report the unit.ctx.Logger().V(3).Info("accepting project")+ s.cacheGitlabProject(proj)unit := git.SourceUnit{Kind: git.UnitRepo, ID: proj.HTTPURLToRepo}gitlabReposEnumerated.WithLabelValues(s.name).Inc()projectsWithNamespace = append(projectsWithNamespace, proj.NameWithNamespace)@@ -740,6 +761,7 @@ func (s *Source) getAllProjectReposV2(// report the unit.projCtx.Logger().V(3).Info("accepting project")+ s.cacheGitlabProject(project)unit := git.SourceUnit{Kind: git.UnitRepo, ID: project.HTTPURLToRepo}gitlabReposEnumerated.WithLabelValues(s.name).Inc()@@ -842,6 +864,7 @@ func (s *Source) getAllProjectReposInGroups(// report the unit.projCtx.Logger().V(3).Info("accepting project")+ s.cacheGitlabProject(proj)unit := git.SourceUnit{Kind: git.UnitRepo, ID: proj.HTTPURLToRepo}gitlabReposEnumerated.WithLabelValues(s.name).Inc()projectsWithNamespace = append(projectsWithNamespace, proj.NameWithNamespace)@@ -1126,5 +1149,62 @@ func (s *Source) ChunkUnit(ctx context.Context, unit sources.SourceUnit, reporte}}+ // ensure project details are cached+ // this is required to populate metadata during chunking+ s.ensureProjectInCache(ctx, repoURL)+return s.git.ScanRepo(ctx, repo, path, s.scanOptions, reporter)}++// ensureProjectInCache checks if the project for the given repo URL is in the cache,+// and if not, queries the GitLab API to fetch the project and adds it to the cache.+func (s *Source) ensureProjectInCache(ctx context.Context, repoUrl string) {+ // check if project is already in cache+ if _, ok := s.repoToProjCache.get(repoUrl); ok {+ return+ }++ // query project+ proj, err := s.getGitlabProject(ctx, repoUrl)+ if err != nil {+ ctx.Logger().Error(err, "could not fetch project for repo", "repo", repoUrl)+ return+ }++ // add to cache+ s.cacheGitlabProject(proj)+}++func (s *Source) getGitlabProject(ctx context.Context, repoUrl string) (*gitlab.Project, error) {+ apiClient, err := s.newClient()+ if err != nil {+ return nil, fmt.Errorf("could not create api client: %w", err)+ }+ // extract project path from repo URL+ // https://gitlab.com/testermctestface/testy.git => testermctestface/testy+ url, err := url.Parse(repoUrl)+ if err != nil {+ return nil, fmt.Errorf("could not parse repo URL: %w", err)+ }+ repoPath := strings.TrimPrefix(strings.TrimSuffix(url.Path, ".git"), "/")++ proj, _, err := apiClient.Projects.GetProject(repoPath, nil, gitlab.WithContext(ctx))+ if err != nil {+ return nil, fmt.Errorf("could not query project metadata: %w", err)+ }+ return proj, nil+}++func (s *Source) cacheGitlabProject(gitlabProj *gitlab.Project) {+ proj := &project{+ id: gitlabProj.ID,+ name: gitlabProj.NameWithNamespace,+ }+ if gitlabProj.Owner != nil {+ proj.owner = gitlabProj.Owner.Email+ if proj.owner == "" {+ proj.owner = gitlabProj.Owner.Username+ }+ }+ s.repoToProjCache.set(gitlabProj.HTTPURLToRepo, proj)+}diff --git a/pkg/sources/gitlab/gitlab_integration_test.go b/pkg/sources/gitlab/gitlab_integration_test.goindex b2da21603..933897b82 100644--- a/pkg/sources/gitlab/gitlab_integration_test.go+++ b/pkg/sources/gitlab/gitlab_integration_test.go@@ -20,6 +20,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/source_metadatapb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"+ "github.com/trufflesecurity/trufflehog/v3/pkg/sourcestest")func TestSource_Scan(t *testing.T) {@@ -680,3 +681,135 @@ func TestSource_InclusionGlobbing(t *testing.T) {})}}++func TestSource_Chunks_ProjectDetailsInChunkMetadata(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)+ defer cancel()++ secret, err := common.GetTestSecret(ctx)+ if err != nil {+ t.Fatal(fmt.Errorf("failed to access secret: %v", err))+ }++ token := secret.MustGetField("GITLAB_TOKEN")++ tests := []struct {+ name string+ connection *sourcespb.GitLab+ }{+ {+ name: "project details in chunk metadata - No repos configured",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ },+ },+ {+ name: "project details in chunk metadata - Repo configured",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ Repositories: []string{"https://gitlab.com/testermctestface/testy.git"},+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {++ s := Source{}++ conn, err := anypb.New(tt.connection)+ if err != nil {+ t.Fatal(err)+ }++ err = s.Init(ctx, tt.name, 0, 0, false, conn, 10)+ if err != nil {+ t.Errorf("Source.Init() error = %v", err)+ return+ }+ chunksCh := make(chan *sources.Chunk, 1)+ go func() {+ defer close(chunksCh)+ err = s.Chunks(context.Background(), chunksCh)+ if err != nil {+ t.Errorf("Source.Chunks() error = %v", err)+ return+ }+ }()+ gotChunks := false+ for gotChunk := range chunksCh {+ gotChunks = true+ metadata := gotChunk.SourceMetadata.Data.(*source_metadatapb.MetaData_Gitlab)+ if metadata.Gitlab.ProjectId == 0 || metadata.Gitlab.ProjectName == "" {+ t.Errorf("Source.Chunks() missing project details in chunk metadata: %+v", metadata.Gitlab)+ }+ }+ if !gotChunks {+ t.Errorf("0 chunks scanned.")+ }+ })+ }+}++func TestSource_Enumerate_ProjectDetailsInChunkMetadata(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)+ defer cancel()++ secret, err := common.GetTestSecret(ctx)+ if err != nil {+ t.Fatal(fmt.Errorf("failed to access secret: %v", err))+ }++ token := secret.MustGetField("GITLAB_TOKEN")++ s := Source{}++ conn, err := anypb.New(&sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ })+ if err != nil {+ t.Fatal(err)+ }++ err = s.Init(ctx, "project details in chunkmetadata", 0, 0, false, conn, 10)+ if err != nil {+ t.Errorf("Source.Init() error = %v", err)+ return+ }+ testReporter := sourcestest.TestReporter{}+ err = s.Enumerate(ctx, &testReporter)+ if err != nil {+ t.Errorf("Source.Chunks() error = %v", err)+ return+ }+ chunksCh := make(chan *sources.Chunk, 1)+ chanReporter := sources.ChanReporter{Ch: chunksCh}+ // Clear cache to force querying project details+ clear(s.repoToProjCache.cache)+ go func() {+ defer close(chunksCh)+ for _, unit := range testReporter.Units {+ err := s.ChunkUnit(context.Background(), unit, chanReporter)+ if err != nil {+ t.Errorf("Source.ChunkUnit() error = %v", err)+ }+ }+ }()+ gotChunks := false+ for gotChunk := range chunksCh {+ gotChunks = true+ metadata := gotChunk.SourceMetadata.Data.(*source_metadatapb.MetaData_Gitlab)+ if metadata.Gitlab.ProjectId == 0 || metadata.Gitlab.ProjectName == "" {+ t.Errorf("Source.Chunks() missing project details in chunk metadata: %+v", metadata.Gitlab)+ }+ }+ if !gotChunks {+ t.Errorf("0 chunks scanned.")+ }+}diff --git a/pkg/sources/gitlab/project_cache.go b/pkg/sources/gitlab/project_cache.gonew file mode 100644index 000000000..15ebb0f0c--- /dev/null+++ b/pkg/sources/gitlab/project_cache.go@@ -0,0 +1,29 @@+package gitlab++import "sync"++type project struct {+ id int+ name string+ owner string+}++type repoToProjectCache struct {+ sync.RWMutex++ cache map[string]*project+}++func (r *repoToProjectCache) get(repo string) (*project, bool) {+ r.RLock()+ defer r.RUnlock()+ proj, ok := r.cache[repo]+ return proj, ok+}++func (r *repoToProjectCache) set(repo string, proj *project) {+ r.Lock()+ defer r.Unlock()++ r.cache[repo] = proj+}