diff --git a/README.md b/README.md index 5d8c6fc..0b1ef26 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,21 @@ fmt.Println(clone.Head(ctx, dst)) Pass `true` as the final argument for a full clone, including when an existing shallow checkout needs to be unshallowed. Clone and fetch errors are returned as `*clone.UnreachableError`, except when the context was canceled or reached its deadline. `errors.As` retrieves the URL and underlying Git error. `ValidateURL` accepts `https://` URLs, while `ValidateRef` rejects leading hyphens, `..`, and characters outside letters, digits, `.`, `_`, `/`, and `-`. -Use `EnsureWithOptions` to include submodules. Submodules are initialized and updated recursively with depth 1 after both a new clone and an existing checkout update. This step is best-effort because submodules may be large or refer to unavailable URLs; failures leave the parent checkout usable. Context cancellation is still returned. Recursion is bounded: submodules are fetched one nesting level at a time, at most 8 levels deep and 256 submodules in total. When fetching a repository's submodules would exceed either limit, the submodule step stops before fetching them; submodules already fetched are kept and `Submodules` reports the rest as unavailable. Submodule URLs come from the cloned repository's `.gitmodules`, so submodules are fetched with the ambient credential helper disabled. Other ambient Git credentials are not disabled: an unscoped `http.extraHeader`, `GIT_ASKPASS` or `core.askPass` can still authenticate a repository-chosen submodule URL. Callers that fetch untrusted repositories with `RecurseSubmodules` should scope those credentials to trusted URLs or remove them. Callers that need authenticated submodules can supply credentials through the environment. +Use `EnsureWithOptions` to include submodules. Submodules are initialized and updated recursively with depth 1 after both a new clone and an existing checkout update. This step is best-effort because submodules may be large or refer to unavailable URLs; failures leave the parent checkout usable. Context cancellation is still returned. Recursion is bounded: submodules are fetched one nesting level at a time, at most 8 levels deep and 256 submodules in total. When fetching a repository's submodules would exceed either limit, the submodule step stops before fetching them; submodules already fetched are kept and `Submodules` reports the rest as unavailable. Submodule URLs come from the cloned repository's `.gitmodules`, so submodules are fetched with the ambient credential helper disabled. Other ambient Git credentials are not disabled: an unscoped `http.extraHeader`, `GIT_ASKPASS` or `core.askPass` can still authenticate a repository-chosen submodule URL. Callers that fetch untrusted repositories with `RecurseSubmodules` should scope those credentials to trusted URLs or remove them. + +To fetch private submodules, list trusted URL prefixes in `SubmoduleCredentialURLs`. A submodule whose resolved URL is under one of them is fetched with the ambient credential helper; prefixes match on path segment boundaries, so `https://github.com/my-org` covers `https://github.com/my-org/lib.git` but not `https://github.com/my-org-two/lib.git`. Any repository can name a trusted URL in its `.gitmodules`, so every repository the helper can read under those prefixes may end up in a checkout of an untrusted repository. Prefixes must be `https://` with no userinfo, query, fragment or dot segments; `ValidateSubmoduleCredentialURLs` checks a list up front. The prefix is matched against the URL in `.gitmodules`, before Git applies `url..insteadOf`, so the caller's own rewrites of a trusted prefix also receive credentials. + +Set `OnSubmoduleIssue` to learn which submodules are missing. It is called once per submodule with its path relative to `dst`, its credential-free URL, a reason (`SubmoduleIssueFetchFailed`, `SubmoduleIssueDepthLimit` or `SubmoduleIssueModuleLimit`) and, for a failed fetch, Git's output with URL userinfo redacted. Submodules nested beneath a skipped one are not reported. ```go err := clone.EnsureWithOptions(ctx, clone.Retry{}, url, dst, "main", - clone.EnsureOptions{RecurseSubmodules: true}, + clone.EnsureOptions{ + RecurseSubmodules: true, + SubmoduleCredentialURLs: []string{"https://github.com/my-org"}, + OnSubmoduleIssue: func(issue clone.SubmoduleIssue) { + log.Printf("submodule %s %s: %s", issue.Path, issue.Reason, issue.Output) + }, + }, ) if err != nil { log.Fatal(err) @@ -61,7 +71,7 @@ an invalid tag or another local repository error. `CheckoutTag` does not fetch. ## Persistent cache -`Cache` stores one checkout per URL under `Root`. `Prepare` holds a per-URL lock while updating the shallow checkout, then replaces `dst` with a copy and returns its commit. The destination must be outside `Root`. Set `RecurseSubmodules` to copy best-effort shallow submodule checkouts into each destination. +`Cache` stores one checkout per URL under `Root`. `Prepare` holds a per-URL lock while updating the shallow checkout, then replaces `dst` with a copy and returns its commit. The destination must be outside `Root`. Set `RecurseSubmodules` to copy best-effort shallow submodule checkouts into each destination; `SubmoduleCredentialURLs` and `OnSubmoduleIssue` behave as in `EnsureOptions`. ```go cache := clone.Cache{ diff --git a/cache.go b/cache.go index 3e730b5..3bc6e13 100644 --- a/cache.go +++ b/cache.go @@ -17,7 +17,11 @@ type Cache struct { Root string // Parent directory for per-URL checkouts. Retry Retry // Retry policy for clone and fetch operations. RecurseSubmodules bool // Best-effort inclusion of nested shallow submodules. - mu sync.Map + // SubmoduleCredentialURLs and OnSubmoduleIssue are passed to + // EnsureWithOptions; see EnsureOptions. + SubmoduleCredentialURLs []string + OnSubmoduleIssue func(SubmoduleIssue) + mu sync.Map } // Dir returns the persistent directory for url under c.Root. @@ -45,7 +49,11 @@ func (c *Cache) Prepare(ctx context.Context, url, ref, dst string) (string, erro return "", err } cacheSrc := filepath.Join(cacheDir, "src") - options := EnsureOptions{RecurseSubmodules: c.RecurseSubmodules} + options := EnsureOptions{ + RecurseSubmodules: c.RecurseSubmodules, + SubmoduleCredentialURLs: c.SubmoduleCredentialURLs, + OnSubmoduleIssue: c.OnSubmoduleIssue, + } if err := EnsureWithOptions(ctx, c.Retry, url, cacheSrc, ref, options); err != nil { return "", err } diff --git a/ensure.go b/ensure.go index 6a03968..c7d7ddb 100644 --- a/ensure.go +++ b/ensure.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "sort" "strings" ) @@ -30,6 +31,13 @@ func (e *UnreachableError) Unwrap() error { type EnsureOptions struct { Full bool // Clone full history and unshallow an existing checkout. RecurseSubmodules bool // Initialize and update submodules recursively at depth 1. + // SubmoduleCredentialURLs lists https URL prefixes, matched on path + // segment boundaries, whose submodules are fetched with the ambient + // credential helper. All other submodules are fetched without it. + SubmoduleCredentialURLs []string + // OnSubmoduleIssue, when set, is called for each submodule left out of + // the checkout. + OnSubmoduleIssue func(SubmoduleIssue) } // Ensure clones url into dst on its first call, then fetches and resets the @@ -62,11 +70,20 @@ func ensure(ctx context.Context, retry Retry, url, dst, ref string, options Ensu if err := ValidateRef(ref); err != nil { return err } + trusted, err := parseCredentialPrefixes(options.SubmoduleCredentialURLs) + if err != nil { + return err + } + update := submoduleUpdate{ + budget: submoduleBudget{maxDepth: maxSubmoduleDepth, maxModules: maxSubmodules}, + trusted: trusted, + onIssue: options.OnSubmoduleIssue, + } if _, err := os.Stat(filepath.Join(dst, ".git")); err == nil { if err := fetchRef(ctx, retry, url, dst, ref, options.Full); err != nil { return err } - return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules) + return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules, update) } if err := os.MkdirAll(filepath.Dir(dst), dirPerm); err != nil { return err @@ -97,7 +114,7 @@ func ensure(ctx context.Context, retry Retry, url, dst, ref string, options Ensu return err } } - return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules) + return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules, update) } // Limits on recursive submodule updates, so nested or repeated gitlinks in a @@ -112,15 +129,12 @@ type submoduleBudget struct { maxModules int } -// updateSubmodules fetches dst's submodules within the default limits when enabled. -func updateSubmodules(ctx context.Context, retry Retry, dst string, enabled bool) error { +// updateSubmodules fetches dst's submodules when enabled. +func updateSubmodules(ctx context.Context, retry Retry, dst string, enabled bool, update submoduleUpdate) error { if !enabled { return nil } - return updateSubmodulesWithin(ctx, retry, dst, submoduleBudget{ - maxDepth: maxSubmoduleDepth, - maxModules: maxSubmodules, - }) + return updateSubmodulesWithin(ctx, retry, dst, update) } // updateSubmodulesWithin walks submodules breadth first, one repository's @@ -128,19 +142,15 @@ func updateSubmodules(ctx context.Context, retry Retry, dst string, enabled bool // walk stops before exceeding the budget, keeping what was already fetched. // Like git's own --recursive, it descends only into submodules checked out at // their gitlink. Only context errors are returned. -func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, budget submoduleBudget) error { - type pending struct { - dir string - depth int // depth of the submodules declared in dir - } +func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, update submoduleUpdate) error { policy := retry.Resolved() - queue := []pending{{dir: dst, depth: 1}} + queue := []pendingSubmodules{{dir: dst, depth: 1}} fetched := 0 for len(queue) > 0 { current := queue[0] queue = queue[1:] - if current.depth > budget.maxDepth { - return nil + if current.depth > update.budget.maxDepth { + return update.reportPending(ctx, policy, append([]pendingSubmodules{current}, queue...), SubmoduleIssueDepthLimit) } links, err := submoduleGitlinks(ctx, policy, current.dir) if err != nil { @@ -149,15 +159,15 @@ func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, budget if len(links) == 0 { continue } - if fetched+len(links) > budget.maxModules { - return nil + if fetched+len(links) > update.budget.maxModules { + if err := update.reportSkipped(ctx, policy, current, links, SubmoduleIssueModuleLimit); err != nil { + return err + } + return update.reportPending(ctx, policy, queue, SubmoduleIssueModuleLimit) } fetched += len(links) - paths := make([]string, len(links)) - for i, link := range links { - paths[i] = link.path - } - if err := updateSubmoduleLevel(ctx, policy, current.dir, paths); err != nil { + outputs, err := updateSubmoduleLevel(ctx, policy, current.dir, links, update.trusted) + if err != nil { return err } for _, link := range links { @@ -167,42 +177,94 @@ func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, budget return err } if ok { - queue = append(queue, pending{dir: child, depth: current.depth + 1}) + queue = append(queue, pendingSubmodules{ + dir: child, + prefix: joinSlash(current.prefix, link.path), + depth: current.depth + 1, + }) + continue } + update.reportLinks(ctx, policy, current, []gitlink{link}, SubmoduleIssueFetchFailed, outputs[link.path]) } } - return nil + // Issue URL lookups swallow their own errors, so a cancellation during + // the last report surfaces here. + return ctx.Err() } -// updateSubmoduleLevel syncs and updates exactly the given submodules of dir. -// Submodule URLs come from the cloned .gitmodules, so the ambient credential -// helper is disabled. Literal pathspecs keep a path from matching more -// submodules than were counted. -func updateSubmoduleLevel(ctx context.Context, policy Retry, dir string, paths []string) error { +// updateSubmoduleLevel syncs and updates exactly the given submodules of dir, +// returning the update output for each path. Submodule URLs come from the +// cloned .gitmodules, so the ambient credential helper is disabled except for +// URLs under a trusted prefix. Literal pathspecs keep a path from matching +// more submodules than were counted. +func updateSubmoduleLevel(ctx context.Context, policy Retry, dir string, links []gitlink, trusted []credentialPrefix) (map[string]string, error) { env := append(remoteEnv(), "GIT_LITERAL_PATHSPECS=1") - syncArgs := append([]string{"-c", "credential.helper=", "submodule", "sync", "--"}, paths...) + paths := make([]string, len(links)) + for i, link := range links { + paths[i] = link.path + } + noHelper := []string{"-c", "credential.helper="} + syncArgs := slices.Concat(noHelper, []string{"submodule", "sync", "--"}, paths) if _, err := policy.Run(ctx, dir, env, longPathArgs(syncArgs...)...); err != nil { if ctxErr := ctx.Err(); ctxErr != nil { - return ctxErr + return nil, ctxErr } } - updateArgs := append([]string{"-c", "credential.helper=", "submodule", "update", "--init", "--depth", "1", "--"}, paths...) - if _, err := policy.Do(ctx, Command{ - Label: "submodule", - Dir: dir, - Env: env, - Args: longPathArgs(updateArgs...), - }); err != nil { - if ctxErr := ctx.Err(); ctxErr != nil { - return ctxErr + + anonymous, authenticated := paths, []string(nil) + if len(trusted) > 0 { + // init resolves relative URLs into .git/config without fetching, so + // the URL matched here is the one update will fetch. + initArgs := append([]string{"submodule", "init", "--"}, paths...) + if _, err := policy.Run(ctx, dir, env, longPathArgs(initArgs...)...); err != nil { + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } + } + anonymous = nil + for _, link := range links { + if !link.ambiguous && credentialAllowed(trusted, submoduleURLConfig(ctx, policy, dir, link.name)) { + authenticated = append(authenticated, link.path) + } else { + anonymous = append(anonymous, link.path) + } } } - return nil + + outputs := make(map[string]string, len(paths)) + for _, batch := range []struct { + paths []string + config []string + }{{anonymous, noHelper}, {authenticated, nil}} { + if len(batch.paths) == 0 { + continue + } + args := slices.Concat(batch.config, []string{"submodule", "update", "--init", "--depth", "1", "--"}, batch.paths) + out, err := policy.Do(ctx, Command{ + Label: "submodule", + Dir: dir, + Env: env, + Args: longPathArgs(args...), + }) + if err != nil { + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } + } + for _, p := range batch.paths { + outputs[p] = out + } + } + return outputs, nil } type gitlink struct { + name string path string commit string + // ambiguous is set when .gitmodules gives path more than one name. Git + // registers the last, so name may not be the submodule Git fetches. + ambiguous bool } // submoduleGitlinks returns the paths that dir's .gitmodules declares and HEAD @@ -215,18 +277,26 @@ func submoduleGitlinks(ctx context.Context, policy Retry, dir string) ([]gitlink if err != nil { return nil, ctx.Err() } - declared := map[string]bool{} + declared := map[string]string{} // path to submodule name + ambiguous := map[string]bool{} var candidates []string for entry := range strings.SplitSeq(strings.TrimSuffix(out, "\x00"), "\x00") { - _, value, ok := strings.Cut(entry, "\n") + key, value, ok := strings.Cut(entry, "\n") if !ok { continue } submodulePath, ok := SanitizePath(value) - if !ok || declared[submodulePath] { + if !ok { + continue + } + name := strings.TrimSuffix(strings.TrimPrefix(key, "submodule."), ".path") + if prior, seen := declared[submodulePath]; seen { + if prior != name { + ambiguous[submodulePath] = true + } continue } - declared[submodulePath] = true + declared[submodulePath] = name candidates = append(candidates, submodulePath) } if len(candidates) == 0 { @@ -241,12 +311,16 @@ func submoduleGitlinks(ctx context.Context, policy Retry, dir string) ([]gitlink var links []gitlink for entry := range strings.SplitSeq(strings.TrimSuffix(out, "\x00"), "\x00") { metadata, treePath, ok := strings.Cut(entry, "\t") - if !ok || !declared[treePath] { + if !ok { + continue + } + name, ok := declared[treePath] + if !ok { continue } fields := strings.Fields(metadata) if len(fields) == 3 && fields[0] == "160000" && fields[1] == "commit" && ValidCommit(fields[2]) { - links = append(links, gitlink{path: treePath, commit: fields[2]}) + links = append(links, gitlink{name: name, path: treePath, commit: fields[2], ambiguous: ambiguous[treePath]}) } } sort.Slice(links, func(i, j int) bool { diff --git a/ensure_test.go b/ensure_test.go index d222241..fb97a40 100644 --- a/ensure_test.go +++ b/ensure_test.go @@ -211,15 +211,71 @@ func TestEnsureWithOptionsInitializesAndUpdatesShallowSubmodules(t *testing.T) { // must not be asked to authenticate it, or private repositories the operator // can read would be fetched into the untrusted checkout. func TestEnsureWithOptionsDoesNotUseCredentialHelperForSubmodules(t *testing.T) { + fixture, serverURL, marker, requests := newPrivateSubmoduleFixture(t) + + dst := filepath.Join(t.TempDir(), "checkout") + var issues []SubmoduleIssue + options := EnsureOptions{ + RecurseSubmodules: true, + // A prefix that shares a string prefix but not a path segment. + SubmoduleCredentialURLs: []string{serverURL + "/priv"}, + OnSubmoduleIssue: func(issue SubmoduleIssue) { issues = append(issues, issue) }, + } + if err := EnsureWithOptions(context.Background(), Retry{}, fixture.origin.url, dst, "", options); err != nil { + t.Fatalf("EnsureWithOptions: %v", err) + } + if requests.Load() == 0 { + t.Fatal("submodule update never contacted the private repository") + } + if calls, err := os.ReadFile(marker); err == nil { + t.Errorf("credential helper was invoked for submodule URL: %q", calls) + } else if !os.IsNotExist(err) { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dst, "file.txt")); err != nil { + t.Errorf("parent checkout unusable after submodule failure: %v", err) + } + if len(issues) != 1 { + t.Fatalf("issues = %+v, want one fetch failure", issues) + } + issue := issues[0] + if issue.Path != "vendor/library" || issue.Reason != SubmoduleIssueFetchFailed || + issue.URL != serverURL+"/private.git" || issue.Output == "" { + t.Errorf("issue = %+v", issue) + } +} + +func TestEnsureWithOptionsUsesCredentialHelperForTrustedSubmodules(t *testing.T) { + fixture, serverURL, marker, _ := newPrivateSubmoduleFixture(t) + + dst := filepath.Join(t.TempDir(), "checkout") + options := EnsureOptions{RecurseSubmodules: true, SubmoduleCredentialURLs: []string{serverURL + "/"}} + if err := EnsureWithOptions(context.Background(), Retry{}, fixture.origin.url, dst, "", options); err != nil { + t.Fatalf("EnsureWithOptions: %v", err) + } + calls, err := os.ReadFile(marker) + if err != nil { + t.Fatalf("credential helper was not invoked for trusted submodule URL: %v", err) + } + if !strings.Contains(string(calls), "get") { + t.Errorf("credential helper calls = %q, want get", calls) + } +} + +// newPrivateSubmoduleFixture points the fixture's submodule at a TLS server +// that always demands credentials, and installs a credential helper that +// records its invocations in marker. +func newPrivateSubmoduleFixture(t *testing.T) (submoduleOriginFixture, string, string, *atomic.Int32) { + t.Helper() fixture := newSubmoduleOriginFixture(t) - var requests atomic.Int32 + requests := &atomic.Int32{} server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { requests.Add(1) w.Header().Set("WWW-Authenticate", `Basic realm="private"`) w.WriteHeader(http.StatusUnauthorized) })) - defer server.Close() + t.Cleanup(server.Close) origin := fixture.origin.dir runGitTest(t, origin, "config", "-f", ".gitmodules", "submodule.vendor/library.url", server.URL+"/private.git") @@ -232,32 +288,214 @@ func TestEnsureWithOptionsDoesNotUseCredentialHelperForSubmodules(t *testing.T) t.Setenv("GIT_CONFIG_VALUE_2", `!f() { echo "$1" >> "$CLONE_TEST_HELPER_MARKER"; }; f`) t.Setenv("GIT_CONFIG_KEY_3", "http.sslVerify") t.Setenv("GIT_CONFIG_VALUE_3", "false") + return fixture, server.URL, marker, requests +} + +const ( + fakeGitlink = "0123456789abcdef0123456789abcdef01234567" + fakeSubmoduleURL = "https://example.invalid/org/library.git" +) +// fakeSubmoduleUpdate runs EnsureWithOptions on an existing checkout with a +// runner that fails every submodule update with output, returning the update +// argv seen. +func fakeSubmoduleUpdate(t *testing.T, options EnsureOptions, output string) [][]string { + t.Helper() dst := filepath.Join(t.TempDir(), "checkout") - options := EnsureOptions{RecurseSubmodules: true} - if err := EnsureWithOptions(context.Background(), Retry{}, fixture.origin.url, dst, "", options); err != nil { + if err := os.MkdirAll(filepath.Join(dst, ".git"), 0o755); err != nil { + t.Fatal(err) + } + var updates [][]string + retry := Retry{ + Attempts: 1, + Run: func(_ context.Context, _ string, _ []string, args ...string) (string, error) { + if out, ok := fakeSubmoduleListing(args); ok { + return out, nil + } + if subcommand(args) == "submodule" && slices.Contains(args, "update") { + updates = append(updates, append([]string(nil), args...)) + return output, errGitExit + } + return "", nil + }, + } + options.RecurseSubmodules = true + if err := EnsureWithOptions(context.Background(), retry, "https://example.invalid/repo", dst, "", options); err != nil { t.Fatalf("EnsureWithOptions: %v", err) } - if requests.Load() == 0 { - t.Fatal("submodule update never contacted the private repository") + return updates +} + +func TestEnsureWithOptionsReportsSubmoduleFetchFailure(t *testing.T) { + var issues []SubmoduleIssue + options := EnsureOptions{OnSubmoduleIssue: func(issue SubmoduleIssue) { issues = append(issues, issue) }} + fakeSubmoduleUpdate(t, options, "fatal: could not read from https://user:pa@ss@example.invalid/org/library.git\n") + + want := SubmoduleIssue{ + Path: "vendor/library", + URL: fakeSubmoduleURL, + Reason: SubmoduleIssueFetchFailed, + Output: "fatal: could not read from https://REDACTED@example.invalid/org/library.git", } - if calls, err := os.ReadFile(marker); err == nil { - t.Errorf("credential helper was invoked for submodule URL: %q", calls) - } else if !os.IsNotExist(err) { + if !slices.Equal(issues, []SubmoduleIssue{want}) { + t.Errorf("issues = %+v, want %+v", issues, want) + } +} + +func TestEnsureWithOptionsReturnsCancellationDuringIssueReport(t *testing.T) { + dst := filepath.Join(t.TempDir(), "checkout") + if err := os.MkdirAll(filepath.Join(dst, ".git"), 0o755); err != nil { t.Fatal(err) } - if _, err := os.Stat(filepath.Join(dst, "file.txt")); err != nil { - t.Errorf("parent checkout unusable after submodule failure: %v", err) + ctx, cancel := context.WithCancel(context.Background()) + retry := Retry{ + Attempts: 1, + Run: func(_ context.Context, _ string, _ []string, args ...string) (string, error) { + if subcommand(args) == "config" && slices.Contains(args, "--get") { + cancel() + return "", errGitExit + } + if out, ok := fakeSubmoduleListing(args); ok { + return out, nil + } + if subcommand(args) == "submodule" && slices.Contains(args, "update") { + return "fatal: not found", errGitExit + } + return "", nil + }, + } + options := EnsureOptions{RecurseSubmodules: true, OnSubmoduleIssue: func(SubmoduleIssue) {}} + err := EnsureWithOptions(ctx, retry, "https://example.invalid/repo", dst, "", options) + if !errors.Is(err, context.Canceled) { + t.Fatalf("error = %v, want context.Canceled", err) } } -const fakeGitlink = "0123456789abcdef0123456789abcdef01234567" +// Git registers the last name .gitmodules gives a path, so a check of the +// first name's URL would not cover the submodule Git fetches. +func TestEnsureWithOptionsWithholdsCredentialsForAmbiguousSubmodulePath(t *testing.T) { + dst := filepath.Join(t.TempDir(), "checkout") + if err := os.MkdirAll(filepath.Join(dst, ".git"), 0o755); err != nil { + t.Fatal(err) + } + var updates [][]string + retry := Retry{ + Attempts: 1, + Run: func(_ context.Context, _ string, _ []string, args ...string) (string, error) { + if subcommand(args) == "config" && slices.Contains(args, "--get-regexp") { + return "submodule.a.path\nvendor/library\x00submodule.b.path\nvendor/library\x00", nil + } + if out, ok := fakeSubmoduleListing(args); ok { + return out, nil + } + if subcommand(args) == "submodule" && slices.Contains(args, "update") { + updates = append(updates, append([]string(nil), args...)) + } + return "", nil + }, + } + options := EnsureOptions{RecurseSubmodules: true, SubmoduleCredentialURLs: []string{"https://example.invalid/org"}} + if err := EnsureWithOptions(context.Background(), retry, "https://example.invalid/repo", dst, "", options); err != nil { + t.Fatalf("EnsureWithOptions: %v", err) + } + if len(updates) != 1 || !slices.Contains(updates[0], "credential.helper=") { + t.Errorf("updates = %q, want one with the credential helper disabled", updates) + } +} + +func TestEnsureWithOptionsSplitsSubmoduleUpdatesByCredentialURL(t *testing.T) { + for _, test := range []struct { + prefixes []string + wantHelper bool + }{ + {nil, false}, + {[]string{"https://example.invalid/org"}, true}, + {[]string{"https://example.invalid/org/"}, true}, + {[]string{"https://EXAMPLE.invalid/org/library.git"}, true}, + {[]string{"https://example.invalid/or"}, false}, + {[]string{"https://example.invalid/other"}, false}, + {[]string{"https://example.invalid:8443/org"}, false}, + } { + updates := fakeSubmoduleUpdate(t, EnsureOptions{SubmoduleCredentialURLs: test.prefixes}, "") + if len(updates) != 1 { + t.Fatalf("prefixes %q: updates = %q, want one", test.prefixes, updates) + } + disabled := slices.Contains(updates[0], "credential.helper=") + if disabled == test.wantHelper { + t.Errorf("prefixes %q: update args = %q, helper enabled want %v", test.prefixes, updates[0], test.wantHelper) + } + } +} + +func TestEnsureWithOptionsRejectsInvalidCredentialURLs(t *testing.T) { + for _, prefix := range []string{ + "http://example.invalid/org", + "https://user:secret@example.invalid/org", + "https://example.invalid/org?x=1", + "https://example.invalid/org/../other", + "https://example.invalid/org//other", + "https://example.invalid/%2e%2e/other", + "https://example.invalid/org%2Fother", + "https://user:secret@example.invalid/%zz", + "https://example.invalid/org?token=secret", + } { + ran := false + retry := Retry{Run: func(context.Context, string, []string, ...string) (string, error) { + ran = true + return "", nil + }} + options := EnsureOptions{RecurseSubmodules: true, SubmoduleCredentialURLs: []string{prefix}} + err := EnsureWithOptions(context.Background(), retry, "https://example.invalid/repo", t.TempDir(), "", options) + if err == nil { + t.Errorf("prefix %q accepted", prefix) + } else if strings.Contains(err.Error(), "secret") { + t.Errorf("error leaks credential: %v", err) + } + if ran { + t.Errorf("prefix %q: Git ran before validation", prefix) + } + if ValidateSubmoduleCredentialURLs([]string{prefix}) == nil { + t.Errorf("ValidateSubmoduleCredentialURLs accepted %q", prefix) + } + } +} + +func TestCredentialAllowedRejectsAmbiguousSubmoduleURLs(t *testing.T) { + prefixes, err := parseCredentialPrefixes([]string{"https://github.com/org"}) + if err != nil { + t.Fatal(err) + } + for _, raw := range []string{ + "https://github.com/org/../evil/repo", + "https://github.com/org/%2e%2e/evil/repo", + "https://github.com/org/%252e%252e/private", + "https://github.com/org/repo%3Fother", + "https://github.com/org//evil", + "https://github.com/org-evil/repo", + "https://user@github.com/org/repo", + "https://github.com/org/repo?x", + "https://github.com\\org/repo", + "http://github.com/org/repo", + "../org/repo", + "", + } { + if credentialAllowed(prefixes, raw) { + t.Errorf("credentialAllowed(%q) = true", raw) + } + } + if !credentialAllowed(prefixes, "https://github.com/org/repo.git") { + t.Error("credentialAllowed rejected a repository under the prefix") + } +} // fakeSubmoduleListing answers the local Git queries updateSubmodulesWithin // makes before fetching, declaring one gitlink at vendor/library. func fakeSubmoduleListing(args []string) (string, bool) { switch subcommand(args) { case "config": + if slices.Contains(args, "--get") { + return fakeSubmoduleURL + "\x00", true + } return "submodule.library.path\nvendor/library\x00", true case "ls-tree": return "160000 commit " + fakeGitlink + "\tvendor/library\x00", true @@ -546,17 +784,33 @@ func TestUpdateSubmodulesWithinStopsAtDepthLimit(t *testing.T) { for _, test := range []struct { maxDepth int want map[string]bool + issues []string }{ - {1, map[string]bool{"sub/a.txt": true, "sub/sub/b.txt": false, "sub/sub/sub/c.txt": false}}, - {2, map[string]bool{"sub/a.txt": true, "sub/sub/b.txt": true, "sub/sub/sub/c.txt": false}}, - {3, map[string]bool{"sub/a.txt": true, "sub/sub/b.txt": true, "sub/sub/sub/c.txt": true}}, + {1, map[string]bool{"sub/a.txt": true, "sub/sub/b.txt": false, "sub/sub/sub/c.txt": false}, + []string{"sub/sub depth_limit " + bURL}}, + {2, map[string]bool{"sub/a.txt": true, "sub/sub/b.txt": true, "sub/sub/sub/c.txt": false}, + []string{"sub/sub/sub depth_limit " + cURL}}, + {3, map[string]bool{"sub/a.txt": true, "sub/sub/b.txt": true, "sub/sub/sub/c.txt": true}, nil}, } { dst := ensureWithoutSubmodules(t, topURL) - budget := submoduleBudget{maxDepth: test.maxDepth, maxModules: maxSubmodules} - if err := updateSubmodulesWithin(context.Background(), Retry{}, dst, budget); err != nil { + var issues []string + update := submoduleUpdate{ + budget: submoduleBudget{maxDepth: test.maxDepth, maxModules: maxSubmodules}, + onIssue: collectIssues(&issues), + } + if err := updateSubmodulesWithin(context.Background(), Retry{}, dst, update); err != nil { t.Fatalf("maxDepth %d: %v", test.maxDepth, err) } assertCheckedOut(t, dst, test.want) + if !slices.Equal(issues, test.issues) { + t.Errorf("maxDepth %d issues = %q, want %q", test.maxDepth, issues, test.issues) + } + } +} + +func collectIssues(issues *[]string) func(SubmoduleIssue) { + return func(issue SubmoduleIssue) { + *issues = append(*issues, issue.Path+" "+string(issue.Reason)+" "+issue.URL) } } @@ -582,19 +836,42 @@ func TestUpdateSubmodulesWithinStopsAtModuleLimit(t *testing.T) { for _, test := range []struct { maxModules int want map[string]bool + issues []string }{ // A level that would exceed the budget is not fetched at all. - {1, map[string]bool{"x/x.txt": false, "y/y.txt": false, "x/z/z.txt": false}}, + {1, map[string]bool{"x/x.txt": false, "y/y.txt": false, "x/z/z.txt": false}, + []string{"x module_limit " + xURL, "y module_limit " + yURL}}, // Levels already fetched are kept when a later level would exceed it. - {2, map[string]bool{"x/x.txt": true, "y/y.txt": true, "x/z/z.txt": false}}, - {3, map[string]bool{"x/x.txt": true, "y/y.txt": true, "x/z/z.txt": true}}, + {2, map[string]bool{"x/x.txt": true, "y/y.txt": true, "x/z/z.txt": false}, + []string{"x/z module_limit " + zURL}}, + {3, map[string]bool{"x/x.txt": true, "y/y.txt": true, "x/z/z.txt": true}, nil}, } { dst := ensureWithoutSubmodules(t, topURL) - budget := submoduleBudget{maxDepth: maxSubmoduleDepth, maxModules: test.maxModules} - if err := updateSubmodulesWithin(context.Background(), Retry{}, dst, budget); err != nil { + var issues []string + update := submoduleUpdate{ + budget: submoduleBudget{maxDepth: maxSubmoduleDepth, maxModules: test.maxModules}, + onIssue: collectIssues(&issues), + } + if err := updateSubmodulesWithin(context.Background(), Retry{}, dst, update); err != nil { t.Fatalf("maxModules %d: %v", test.maxModules, err) } assertCheckedOut(t, dst, test.want) + if !slices.Equal(issues, test.issues) { + t.Errorf("maxModules %d issues = %q, want %q", test.maxModules, issues, test.issues) + } + + // Submodules a previous update checked out are not reported when a + // later update stops at the budget. + if test.maxModules == 3 { + issues = nil + update.budget.maxModules = 1 + if err := updateSubmodulesWithin(context.Background(), Retry{}, dst, update); err != nil { + t.Fatalf("reused checkout: %v", err) + } + if len(issues) != 0 { + t.Errorf("reused checkout issues = %q, want none", issues) + } + } } } diff --git a/submodule_update.go b/submodule_update.go new file mode 100644 index 0000000..6d3ea80 --- /dev/null +++ b/submodule_update.go @@ -0,0 +1,199 @@ +package clone + +import ( + "context" + "fmt" + "net/url" + "regexp" + "slices" + "strings" +) + +// SubmoduleIssueReason says why a declared submodule is missing after +// EnsureWithOptions. +type SubmoduleIssueReason string + +const ( + SubmoduleIssueFetchFailed SubmoduleIssueReason = "fetch_failed" + SubmoduleIssueDepthLimit SubmoduleIssueReason = "depth_limit" + SubmoduleIssueModuleLimit SubmoduleIssueReason = "module_limit" +) + +// SubmoduleIssue describes a submodule the best-effort submodule step left +// out. Path is relative to the top-level checkout. URL omits userinfo and is +// empty when it could not be read. Output is Git's output for a failed fetch, +// with URL userinfo redacted. Submodules nested beneath a skipped submodule +// are not reported. +type SubmoduleIssue struct { + Path string + URL string + Reason SubmoduleIssueReason + Output string +} + +type credentialPrefix struct { + host string + path string +} + +// ValidateSubmoduleCredentialURLs reports the first entry EnsureOptions would +// reject in SubmoduleCredentialURLs, so callers can check configuration +// before cloning. +func ValidateSubmoduleCredentialURLs(urls []string) error { + _, err := parseCredentialPrefixes(urls) + return err +} + +func parseCredentialPrefixes(raw []string) ([]credentialPrefix, error) { + prefixes := make([]credentialPrefix, 0, len(raw)) + for i, entry := range raw { + u, ok := strictHTTPSURL(entry) + if !ok { + // The entry itself is not echoed: it may hold a credential that + // RedactURL cannot find in an unparseable URL. + return nil, fmt.Errorf("invalid submodule credential URL at index %d: must be https with no userinfo, query, fragment, percent escapes, or dot segments", i) + } + prefixes = append(prefixes, credentialPrefix{ + host: strings.ToLower(u.Host), + path: strings.TrimSuffix(u.Path, "/"), + }) + } + return prefixes, nil +} + +// strictHTTPSURL parses raw and rejects anything Git might resolve to a +// different repository than the literal path suggests. +func strictHTTPSURL(raw string) (*url.URL, bool) { + // url.Parse decodes canonical escapes without recording them, so a % + // anywhere could hide a segment the server decodes differently. + if ValidateURL(raw) != nil || strings.ContainsAny(raw, "\\ %") { + return nil, false + } + u, err := url.Parse(raw) + if err != nil || u.User != nil || u.Opaque != "" || u.RawPath != "" || + u.ForceQuery || u.RawQuery != "" || u.Fragment != "" { + return nil, false + } + segments := strings.Split(strings.TrimSuffix(u.Path, "/"), "/") + for i, segment := range segments { + if segment == "." || segment == ".." || (segment == "" && i > 0) { + return nil, false + } + } + return u, true +} + +func credentialAllowed(prefixes []credentialPrefix, raw string) bool { + u, ok := strictHTTPSURL(raw) + if !ok { + return false + } + host := strings.ToLower(u.Host) + return slices.ContainsFunc(prefixes, func(p credentialPrefix) bool { + return host == p.host && (u.Path == p.path || strings.HasPrefix(u.Path, p.path+"/")) + }) +} + +type submoduleUpdate struct { + budget submoduleBudget + trusted []credentialPrefix + onIssue func(SubmoduleIssue) +} + +type pendingSubmodules struct { + dir string + prefix string // slash path of dir relative to the top-level checkout + depth int // depth of the submodules declared in dir +} + +func (u submoduleUpdate) reportLinks(ctx context.Context, policy Retry, p pendingSubmodules, links []gitlink, reason SubmoduleIssueReason, output string) { + if u.onIssue == nil { + return + } + for _, link := range links { + u.onIssue(SubmoduleIssue{ + Path: joinSlash(p.prefix, link.path), + URL: submoduleIssueURL(ctx, policy, p.dir, link.name), + Reason: reason, + Output: redactOutput(output), + }) + } +} + +// reportSkipped reports links the budget left unfetched, except those a +// previous update already checked out at their gitlink. +func (u submoduleUpdate) reportSkipped(ctx context.Context, policy Retry, p pendingSubmodules, links []gitlink, reason SubmoduleIssueReason) error { + if u.onIssue == nil { + return nil + } + var missing []gitlink + for _, link := range links { + ok, err := checkedOutAt(ctx, policy, pathFromGit(p.dir, link.path), link.commit) + if err != nil { + return err + } + if !ok { + missing = append(missing, link) + } + } + u.reportLinks(ctx, policy, p, missing, reason, "") + return ctx.Err() +} + +// reportPending reports the submodules declared by each pending directory as +// skipped for reason. +func (u submoduleUpdate) reportPending(ctx context.Context, policy Retry, queue []pendingSubmodules, reason SubmoduleIssueReason) error { + if u.onIssue == nil { + return nil + } + for _, p := range queue { + links, err := submoduleGitlinks(ctx, policy, p.dir) + if err != nil { + return err + } + if err := u.reportSkipped(ctx, policy, p, links, reason); err != nil { + return err + } + } + return nil +} + +func submoduleURLConfig(ctx context.Context, policy Retry, dir, name string) string { + out, err := policy.Run(ctx, dir, nil, "config", "-z", "--get", "submodule."+name+".url") + if err != nil { + return "" + } + return strings.TrimSuffix(out, "\x00") +} + +func submoduleIssueURL(ctx context.Context, policy Retry, dir, name string) string { + raw := submoduleURLConfig(ctx, policy, dir, name) + if raw == "" { + out, err := policy.Run(ctx, dir, nil, "config", "-z", "--blob", gitmodulesBlob, "--get", "submodule."+name+".url") + if err != nil { + return "" + } + raw = strings.TrimSuffix(out, "\x00") + } + u, err := url.Parse(raw) + if err != nil { + return "" + } + u.User = nil + return u.String() +} + +// Greedy so a password containing @ is consumed through the last @ before +// the host. +var outputUserinfo = regexp.MustCompile(`://[^/\s]*@`) + +func redactOutput(out string) string { + return outputUserinfo.ReplaceAllString(strings.TrimSpace(out), "://REDACTED@") +} + +func joinSlash(prefix, p string) string { + if prefix == "" { + return p + } + return prefix + "/" + p +}