Skip to content

Commit 95afbb1

Browse files
authored
feat(repo): add authentication to git HTTP operation (fanal#253)
1 parent 7d550ea commit 95afbb1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

artifact/remote/git.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"os"
88

99
git "github.com/go-git/go-git/v5"
10+
"github.com/go-git/go-git/v5/plumbing/transport/http"
1011
"golang.org/x/xerrors"
1112

1213
"github.com/aquasecurity/fanal/analyzer/config"
@@ -37,6 +38,7 @@ func NewArtifact(rawurl string, c cache.ArtifactCache, artifactOpt artifact.Opti
3738

3839
_, err = git.PlainClone(tmpDir, false, &git.CloneOptions{
3940
URL: u.String(),
41+
Auth: gitAuth(),
4042
Progress: os.Stdout,
4143
Depth: 1,
4244
})
@@ -84,3 +86,38 @@ func newURL(rawurl string) (*url.URL, error) {
8486

8587
return u, nil
8688
}
89+
90+
// Helper function to check for a GitHub/GitLab token from env vars in order to
91+
// make authenticated requests to access private repos
92+
func gitAuth() *http.BasicAuth {
93+
94+
var auth *http.BasicAuth
95+
96+
// The username can be anything for HTTPS Git operations
97+
gitUsername := "fanal-aquasecurity-scan"
98+
99+
// We first check if a GitHub token was provided
100+
githubToken := os.Getenv("GITHUB_TOKEN")
101+
if githubToken != "" {
102+
auth = &http.BasicAuth{
103+
Username: gitUsername,
104+
Password: githubToken,
105+
}
106+
return auth
107+
}
108+
109+
// Otherwise we check if a GitLab token was provided
110+
gitlabToken := os.Getenv("GITLAB_TOKEN")
111+
if gitlabToken != "" {
112+
auth = &http.BasicAuth{
113+
Username: gitUsername,
114+
Password: gitlabToken,
115+
}
116+
return auth
117+
}
118+
119+
// If no token was provided, we simply return a nil,
120+
// which will make the request to be unauthenticated
121+
return nil
122+
123+
}

0 commit comments

Comments
 (0)