Skip to content

Commit

Permalink
zoekt-mirror-gerrit: handle http authentication
Browse files Browse the repository at this point in the history
issue: #763
  • Loading branch information
xavier-calland committed Apr 25, 2024
1 parent 6df0554 commit 690d1a3
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion cmd/zoekt-mirror-gerrit/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,17 @@ func main() {
log.Fatalf("GetServerInfo: %v", err)
}

gitCredentialConfig := map[string]string{}
var projectURL string
for _, s := range []string{"http", "anonymous http"} {
if schemeInfo, ok := info.Download.Schemes[s]; ok {
projectURL = schemeInfo.URL
if s == "http" && schemeInfo.IsAuthRequired {
gitCredentialConfig = configureGitCredential(rootURL, projectURL, *dest)

// remove "/a/" prefix needed for API call with basic auth but not with git command → cleaner repo name
projectURL = strings.Replace(projectURL, "/a/${project}", "/${project}", 1)
}
break
}
}
Expand Down Expand Up @@ -165,11 +172,15 @@ func main() {
config := map[string]string{
"zoekt.name": name,
"zoekt.gerrit-project": k,
"zoekt.gerrit-host": rootURL.String(),
"zoekt.gerrit-host": anonymousURL(rootURL),
"zoekt.archived": marshalBool(v.State == "READ_ONLY"),
"zoekt.public": marshalBool(v.State != "HIDDEN"),
}

for key, value := range gitCredentialConfig {
config[key] = value
}

for _, wl := range v.WebLinks {
// default gerrit gitiles config is named browse, and does not include
// root domain name in it. Cheating.
Expand Down Expand Up @@ -224,3 +235,37 @@ func marshalBool(b bool) string {
}
return "0"
}

func configureGitCredential(rootURL *url.URL, projectURL string, dest string) map[string]string {
// Abs path so that we can put it in each git repo config
gitCredentialStore, err := filepath.Abs(filepath.Join(dest, rootURL.Host, "credentials-store"))
if err != nil {
log.Fatalf("Absolute dest: %v", err)
}

// credentialValue format: scheme://login:pass@host
// XXX: call git credential helper commands
cloneURL, err := url.Parse(projectURL)
if err != nil {
log.Fatalf("url.Parse(): %v", err)
}
cloneURL.Path = ""
cloneURL.User = rootURL.User
credentialValue := cloneURL.String()

if err := os.WriteFile(gitCredentialStore, []byte(credentialValue), 0644); err != nil {
log.Fatalf("WriteFile credentials: %v", err)
}

return map[string]string{
"credential.helper": fmt.Sprintf("store --file=%s", gitCredentialStore),
}
}

func anonymousURL(URL *url.URL) string {
anonymousURL := *URL
if _, has := URL.User.Password(); has {
anonymousURL.User = nil
}
return (&anonymousURL).String()
}

0 comments on commit 690d1a3

Please sign in to comment.