Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Implement Gitlab source validation (#1765)
Cody Rose1155ee273629
diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.goindex 5050474c6..305eafbe8 100644--- a/pkg/sources/git/git.go+++ b/pkg/sources/git/git.go@@ -372,6 +372,32 @@ func CloneRepo(ctx context.Context, userInfo *url.Userinfo, gitUrl string, argsreturn clonePath, repo, nil}+// PingRepoUsingToken executes git ls-remote on a repo and returns any error that occurs. It can be used to validate+// that a repo actually exists and is reachable.+//+// Pinging using other authentication methods is only unimplemented because there's been no pressing need for it yet.+func PingRepoUsingToken(ctx context.Context, token, gitUrl, user string) error {+ if err := GitCmdCheck(); err != nil {+ return err+ }+ lsUrl, err := GitURLParse(gitUrl)+ if err != nil {+ return err+ }+ if lsUrl.User == nil {+ lsUrl.User = url.UserPassword(user, token)+ }++ // We don't actually care about any refs on the remote, we just care whether can can list them at all. So we query+ // only for a ref that we know won't exist to minimize the search time on the remote. (By default, ls-remote exits+ // with 0 even if it doesn't find any matching refs.)+ fakeRef := "TRUFFLEHOG_CHECK_GIT_REMOTE_URL_REACHABILITY"+ gitArgs := []string{"ls-remote", lsUrl.String(), "--quiet", fakeRef}+ cmd := exec.Command("git", gitArgs...)+ _, err = cmd.CombinedOutput()+ return err+}+// CloneRepoUsingToken clones a repo using a provided token.func CloneRepoUsingToken(ctx context.Context, token, gitUrl, user string, args ...string) (string, *git.Repository, error) {userInfo := url.UserPassword(user, token)diff --git a/pkg/sources/gitlab/gitlab.go b/pkg/sources/gitlab/gitlab.goindex 856885bf5..4ba20158f 100644--- a/pkg/sources/gitlab/gitlab.go+++ b/pkg/sources/gitlab/gitlab.go@@ -55,6 +55,7 @@ type Source struct {// Ensure the Source satisfies the interfaces at compile time.var _ sources.Source = (*Source)(nil)var _ sources.SourceUnitUnmarshaller = (*Source)(nil)+var _ sources.Validator = (*Source)(nil)// Type returns the type of source.// It is used for matching source types in configuration and job input.@@ -148,9 +149,9 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .return errors.New(err)}// Get repo within target.- repos, errs := s.getRepos()+ repos, errs := normalizeRepos(s.repos)for _, repoErr := range errs {- ctx.Logger().Info("error getting repo", "error", repoErr)+ ctx.Logger().Info("error normalizing repo", "error", repoErr)}// End early if we had errors getting specified repos but none were validated.@@ -160,26 +161,14 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .// Get all repos if not specified.if len(repos) == 0 {- projects, err := s.getAllProjects(ctx, apiClient)- if err != nil {- return fmt.Errorf("error getting all projects: %v", err)- }- // Turn projects into URLs for Git cloner.- for _, prj := range projects {- if s.ignoreRepo(ctx, prj.PathWithNamespace) {- continue- }-- // Ensure the urls are valid before adding them to the repo list.- _, err := url.Parse(prj.HTTPURLToRepo)- if err != nil {- fmt.Printf("could not parse url given by project: %s", prj.HTTPURLToRepo)- }- repos = append(repos, prj.HTTPURLToRepo)- }- if len(repos) == 0 {- return errors.Errorf("unable to discover any repos")+ ignoreRepo := buildIgnorer(s.ignoreRepos, func(err error, pattern string) {+ ctx.Logger().Error(err, "could not compile ignore repo glob", "glob", pattern)+ })+ gitlabRepos, err2, done := s.getReposFromGitlab(ctx, apiClient, ignoreRepo)+ if done {+ return err2}+ repos = gitlabRepos}s.repos = repos@@ -189,6 +178,69 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk, _ .return s.scanRepos(ctx, chunksChan)}+func (s *Source) Validate(ctx context.Context) []error {+ // The client is only used to query Gitlab for a repo list - it's not used to actually clone anything. Thus, we+ // don't use it if there is a list of explicitly configured repos. However, constructing it validates that the+ // configured authentication method is sensible, so we'll do it here.+ apiClient, err := s.newClient()+ if err != nil {+ return []error{err}+ }++ _, _, err = apiClient.Users.CurrentUser()+ if err != nil {+ msg := fmt.Sprintf("gitlab authentication failed using method %v", s.authMethod)+ return []error{errors.WrapPrefix(err, msg, 0)}+ }++ explicitlyConfiguredRepos, errs := normalizeRepos(s.repos)++ if len(explicitlyConfiguredRepos) > 0 {+ user := s.user+ if user == "" {+ user = "placeholder"+ }++ // We only check reachability for explicitly configured repositories. The purpose of source validation is to+ // help users validate their configuration files, and Gitlab telling us about repositories that it won't let us+ // access isn't a local configuration issue.+ for _, r := range explicitlyConfiguredRepos {+ if err := git.PingRepoUsingToken(ctx, s.token, r, user); err != nil {+ msg := fmt.Sprintf("could not reach git repository %q", r)+ err = errors.WrapPrefix(err, msg, 0)+ errs = append(errs, err)+ }+ }++ if len(s.ignoreRepos) > 0 {+ errs = append(errs, fmt.Errorf("both repositories and ignore patterns were explicitly configured; ignore patterns will not be used"))+ }+ }++ if len(explicitlyConfiguredRepos) > 0 || len(errs) > 0 {+ return errs+ }++ ignoreProject := buildIgnorer(s.ignoreRepos, func(err error, pattern string) {+ msg := fmt.Sprintf("could not compile ignore repo pattern %q", pattern)+ errs = append(errs, errors.WrapPrefix(err, msg, 0))+ })++ projects, err := s.getAllProjects(ctx, apiClient)+ if err != nil {+ errs = append(errs, err)+ return errs+ }++ for _, p := range projects {+ if !ignoreProject(p.PathWithNamespace) {+ return errs+ }+ }++ return append(errs, fmt.Errorf("ignore patterns excluded all projects"))+}+func (s *Source) newClient() (*gitlab.Client, error) {// Initialize a new api instance.switch s.authMethod {@@ -324,23 +376,30 @@ func (s *Source) getAllProjects(ctx context.Context, apiClient *gitlab.Client) (return projectList, nil}-func (s *Source) getRepos() ([]string, []error) {- if len(s.repos) == 0 {- return nil, nil+func (s *Source) getReposFromGitlab(ctx context.Context, apiClient *gitlab.Client, ignoreRepo func(repo string) bool) ([]string, error, bool) {+ projects, err := s.getAllProjects(ctx, apiClient)+ if err != nil {+ return nil, fmt.Errorf("error getting all projects: %v", err), true}- var validRepos []string- var errs []error- for _, prj := range s.repos {- repo, err := giturl.NormalizeGitlabRepo(prj)- if err != nil {- errs = append(errs, errors.WrapPrefix(err, fmt.Sprintf("unable to normalize gitlab repo url %s", prj), 0))+ // Turn projects into URLs for Git cloner.+ var repos []string+ for _, prj := range projects {+ if ignoreRepo(prj.PathWithNamespace) {continue}- validRepos = append(validRepos, repo)+ // Ensure the urls are valid before adding them to the repo list.+ _, err := url.Parse(prj.HTTPURLToRepo)+ if err != nil {+ fmt.Printf("could not parse url given by project: %s", prj.HTTPURLToRepo)+ }+ repos = append(repos, prj.HTTPURLToRepo)}- return validRepos, errs+ if len(repos) == 0 {+ return nil, errors.Errorf("unable to discover any repos"), true+ }+ return repos, nil, false}func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk) error {@@ -413,21 +472,6 @@ func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk)return nil}-func (s *Source) ignoreRepo(ctx context.Context, r string) bool {- for _, ignore := range s.ignoreRepos {- g, err := glob.Compile(ignore)- if err != nil {- ctx.Logger().Error(err, "could not compile ignore repo glob", "glob", ignore)- continue- }- if g.Match(r) {- ctx.Logger().V(2).Info("Ignoring repo", "repo", r)- return true- }- }- return false-}-// setProgressCompleteWithRepo calls the s.SetProgressComplete after safely setting up the encoded resume info string.func (s *Source) setProgressCompleteWithRepo(index int, offset int, repoURL string) {s.resumeInfoMutex.Lock()@@ -447,3 +491,42 @@ func (s *Source) setProgressCompleteWithRepo(index int, offset int, repoURL strifunc (s *Source) WithScanOptions(scanOptions *git.ScanOptions) {s.scanOptions = scanOptions}++func buildIgnorer(patterns []string, onCompileErr func(err error, pattern string)) func(repo string) bool {+ var globs []glob.Glob++ for _, pattern := range patterns {+ g, err := glob.Compile(pattern)+ if err != nil {+ onCompileErr(err, pattern)+ continue+ }+ globs = append(globs, g)+ }++ f := func(repo string) bool {+ for _, g := range globs {+ if g.Match(repo) {+ return true+ }+ }+ return false+ }++ return f+}++func normalizeRepos(repos []string) ([]string, []error) {+ var validRepos []string+ var errs []error+ for _, prj := range repos {+ repo, err := giturl.NormalizeGitlabRepo(prj)+ if err != nil {+ errs = append(errs, errors.WrapPrefix(err, fmt.Sprintf("unable to normalize gitlab repo url %s", prj), 0))+ continue+ }++ validRepos = append(validRepos, repo)+ }+ return validRepos, errs+}diff --git a/pkg/sources/gitlab/gitlab_test.go b/pkg/sources/gitlab/gitlab_test.goindex 68088c522..3970c89a3 100644--- a/pkg/sources/gitlab/gitlab_test.go+++ b/pkg/sources/gitlab/gitlab_test.go@@ -177,6 +177,150 @@ func TestSource_Scan(t *testing.T) {}}+func TestSource_Validate(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ 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")+ tokenWrongScope := secret.MustGetField("GITLAB_TOKEN_WRONG_SCOPE")++ tests := []struct {+ name string+ connection *sourcespb.GitLab+ wantErrCount int+ wantErrs []string+ }{+ {+ name: "basic auth did not authenticate",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_BasicAuth{+ BasicAuth: &credentialspb.BasicAuth{+ Username: "bad-user",+ Password: "bad-password",+ },+ },+ },+ wantErrCount: 1,+ },+ {+ name: "token did not authenticate",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: "bad-token",+ },+ },+ wantErrCount: 1,+ },+ {+ name: "bad repo urls",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ Repositories: []string{+ "https://gitlab.com/testermctestface/testy", // valid+ "https://gitlab.com/testermctestface/testy/", // trailing slash+ "ssh:[email protected]/testermctestface/testy", // bad protocol+ "https://gitlab.com", // no path+ "https://gitlab.com/", // no org name+ "https://gitlab.com//testy", // no org name+ "https://gitlab.com/testermctestface/", // no repo name+ },+ },+ wantErrCount: 6,+ },+ {+ name: "token does not have permission to list projects",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: tokenWrongScope,+ },+ },+ wantErrCount: 1,+ },+ {+ name: "repositories and ignore globs both configured",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ Repositories: []string{+ "https://gitlab.com/testermctestface/testy", // valid+ },+ IgnoreRepos: []string{+ "tes1188/*-gitlab",+ "[", // glob doesn't compile, but this won't be checked+ },+ },+ wantErrCount: 1,+ },+ {+ name: "could not compile ignore glob(s)",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ IgnoreRepos: []string{+ "tes1188/*-gitlab",+ "[", // glob doesn't compile+ "[a-]", // glob doesn't compile+ },+ },+ wantErrCount: 2,+ },+ {+ name: "repositories do not exist or are not accessible",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ Repositories: []string{+ "https://gitlab.com/testermctestface/testy",+ "https://gitlab.com/testermctestface/doesn't-exist",+ "https://gitlab.com/testermctestface/also-doesn't-exist",+ },+ },+ wantErrCount: 2,+ },+ {+ name: "ignore globs exclude all repos",+ connection: &sourcespb.GitLab{+ Credential: &sourcespb.GitLab_Token{+ Token: token,+ },+ IgnoreRepos: []string{+ "*",+ },+ },+ wantErrCount: 1,+ },+ }++ 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, 1)+ if err != nil {+ t.Fatalf("Source.Init() error: %v", err)+ }++ errs := s.Validate(ctx)++ assert.Equal(t, tt.wantErrCount, len(errs))+ })+ }+}+func Test_setProgressCompleteWithRepo_resumeInfo(t *testing.T) {tests := []struct {startingResumeInfoSlice []string