fix(install): hide credentials in submodule URLs shown to the user

.gitmodules may hold an authenticated URL; drop userinfo, query and fragment before it reaches warnings, errors or API responses.
This commit is contained in:
Willie
2026-10-07 02:03:26 +08:00
parent b7265d6496
commit e4b72cb554
2 changed files with 26 additions and 1 deletions
+14 -1
View File
@@ -3,6 +3,7 @@ package install
import (
"context"
"fmt"
"net/url"
"path/filepath"
"strings"
)
@@ -18,11 +19,23 @@ type gitlink struct {
func (l gitlink) String() string {
s := fmt.Sprintf("'%s' (pinned at %s", l.Path, shortHash(l.Commit))
if l.URL != "" {
s += " from " + l.URL
s += " from " + displayURL(l.URL)
}
return s + ")"
}
// displayURL drops userinfo, query and fragment from a .gitmodules URL, which
// may carry a token, before it reaches terminal output or an API error.
// url.Redacted is not enough: a token is often the username alone.
func displayURL(raw string) string {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return raw // scp-style or relative URL: no userinfo to strip
}
u.User, u.RawQuery, u.Fragment = nil, "", ""
return u.String()
}
// repoGitlinks lists the submodules recorded in HEAD of repoPath. extraEnv
// authenticates the lazy .gitmodules fetch in a partial clone. Any git failure
// returns nil: callers only use the result to explain an empty directory.
+12
View File
@@ -87,6 +87,18 @@ func TestInstall_RefusesSubmoduleSubdir(t *testing.T) {
}
}
func TestGitlinkString_HidesURLCredentials(t *testing.T) {
for _, raw := range []string{
"https://user:s3cret@example.com/org/up.git",
"https://s3cret@example.com/org/up.git?token=s3cret",
} {
got := gitlink{Path: "vendor/up", Commit: "abc", URL: raw}.String()
if strings.Contains(got, "s3cret") || !strings.Contains(got, "https://example.com/org/up.git") {
t.Errorf("String() = %q, want the URL without credentials", got)
}
}
}
func TestDiscoverFromGit_WarnsSkippedSubmodule(t *testing.T) {
hubURL, upURL := newHubWithSubmodule(t)