From 358a898636c6f5ae80850b4f0711907baeee6697 Mon Sep 17 00:00:00 2001 From: Victor M Varela Date: Fri, 30 Oct 2026 13:44:13 +0100 Subject: [PATCH 1/5] feat: replicate canonical Git LFS pointers before publishing refs --- README.md | 8 +- cache_test.go | 68 +------- entrypoint_test.go | 4 +- lfs_auxiliary.go | 286 ++++++++++++++++++++++++++++++ lfs_auxiliary_test.go | 313 +++++++++++++++++++++++++++++++++ lfs_integration_test.go | 217 +++++++++++++++++++++++ lfs_objects.go | 79 +++++++++ lfs_objects_test.go | 78 +++++++++ lfs_pointer.go | 73 ++++++++ lfs_pointer_test.go | 372 ++++++++++++++++++++++++++++++++++++++++ lfs_snapshot.go | 136 +++++++++++++++ lfs_snapshot_test.go | 305 ++++++++++++++++++++++++++++++++ lfs_transfer.go | 74 ++++++++ lfs_transfer_test.go | 29 ++++ replicate.go | 63 ++++--- safeguards.go | 141 ++++++++++++++- 16 files changed, 2155 insertions(+), 91 deletions(-) create mode 100644 lfs_auxiliary.go create mode 100644 lfs_auxiliary_test.go create mode 100644 lfs_integration_test.go create mode 100644 lfs_objects.go create mode 100644 lfs_objects_test.go create mode 100644 lfs_pointer.go create mode 100644 lfs_pointer_test.go create mode 100644 lfs_snapshot.go create mode 100644 lfs_snapshot_test.go create mode 100644 lfs_transfer.go create mode 100644 lfs_transfer_test.go diff --git a/README.md b/README.md index 4fe4fb8..3b45d0e 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Use it to keep a mirror, a staging copy or a public fork in sync with a reposito ## What it copies - Branches and tags. Matching destination refs are overwritten; destination-only refs are kept. +- Git LFS objects referenced by canonical spec-v1 pointers (see Limits). - Releases, their uploaded assets and the Latest selection. - Description, homepage and topics. - Labels. @@ -17,6 +18,7 @@ It does not touch issues, pull requests, discussions, wikis, permissions, secret - GitHub CLI installed and authenticated with `gh auth login`. - `git` 2.29 or newer in `PATH`. +- `git-lfs` 3.8.1 or newer in `PATH` — required only when the source contains Git LFS pointers. - A destination repository that already exists and that you can write to. Changing its default branch and disabling its Actions needs administration write access. - github.com only. GitHub Enterprise Server and cross-instance replication are not supported. @@ -82,7 +84,7 @@ Both flags are optional and independent; without them the active account is used - **Check the direction.** Source wins for matching refs. A dry run reports what would change; it does not guarantee that server-side protections will accept the push. - **Ref renames can be blocked.** Replacing `release` with `release/v2` fails while `release` still exists in the destination, because destination-only refs are never deleted. Delete or rename it, then rerun. -- **Git LFS content is not copied.** When `refs` is selected, the run stops before any destination change if it finds a pointer using a known LFS version, including in history; do not rely on it for formats or versions it does not recognize; without `refs` no Git history is read, so this check does not run. The check reads every blob reachable from branches and tags, so it can be slow on large histories (raise `--timeout`), and it is conservative: an ordinary file containing a known LFS version line may be reported too. +- **Git LFS support is limited to canonical spec-v1 pointers.** Objects referenced by a canonical pointer (`version https://git-lfs.github.com/spec/v1`, exactly three LF lines, no extensions, smaller than 1024 bytes) are downloaded, verified and uploaded before any ref is published, using `git-lfs` 3.8.1 or newer. Anything else that looks like LFS — older version aliases, CRLF, padding, extensions, or versions it does not recognize — stops the run before any destination change, including pointers only in history. The scan reads every blob reachable from branches and tags, so it can be slow on large histories (raise `--timeout`), and it is conservative: an ordinary file containing a known LFS version line may be reported too. - **Some assets need a second step.** A changed release asset is uploaded under a temporary name, verified, then swapped in, so its name is briefly missing. An interrupted run leaves either the previous asset or the verified replacement; a rerun finishes the work, and a leftover temporary asset may need deleting from the release. - **Invalid input stops the run before any write.** More than 20 topics, an empty release tag or a duplicated release tag, including drafts, abort the replication. Releases are matched by tag. - **Retries are bounded.** Read requests retry twice for selected transient failures and short rate limits; write requests are never replayed automatically, so rerun instead. @@ -90,9 +92,7 @@ Both flags are optional and independent; without them the active account is used ## Local cache -The source history is kept in a bare repository under your OS user cache directory (`gh-replicate/git-v1`), so later runs and other destinations only download what is missing. The cache holds repository contents, including private history, with owner-only permissions and no credentials. - -You can delete it while no replication is running; the next run downloads the history again. A per-source lock allows one run at a time: a second run fails with the lock path until the first exits. CI jobs can persist this directory between runs to avoid repeated downloads. +A per-source lock lives under your OS user cache directory (`gh-replicate/git-v1`) so a second run of the same source fails with the lock path until the first exits. Source history is no longer reused across runs: each run copies into a fresh, private, temporary repository with its own configuration, so an interrupted run leaves no partial state. You can delete the cache directory while no replication is running. ## License diff --git a/cache_test.go b/cache_test.go index 711e3af..3479ab3 100644 --- a/cache_test.go +++ b/cache_test.go @@ -66,7 +66,7 @@ func TestCacheLockReleasedAfterProcessDeath(t *testing.T) { f.Close() } -func TestSyncGitCacheLifecycle(t *testing.T) { +func TestSyncGitLifecycle(t *testing.T) { f := newGitFixture(t) seamStub(t) gitRemote = func(repo string) string { @@ -84,46 +84,22 @@ func TestSyncGitCacheLifecycle(t *testing.T) { } } sync() - root, err := os.UserCacheDir() - if err != nil { - t.Fatal(err) - } - caches, err := filepath.Glob(filepath.Join(root, "gh-replicate", "git-v1", "*.git")) - if err != nil || len(caches) != 1 { - t.Fatalf("caches %v: %v", caches, err) - } - marker := filepath.Join(caches[0], "reused") - if err := os.WriteFile(marker, []byte("keep"), 0600); err != nil { - t.Fatal(err) - } base := gitTest(t, f.source, "rev-parse", "main") gitTest(t, f.destination, "update-ref", "refs/heads/exclusive", base) gitTest(t, f.destination, "update-ref", "refs/tags/exclusive", base) gitTest(t, f.source, "update-ref", "refs/heads/new", base) sync() - if _, err := os.Stat(marker); err != nil { - t.Fatal("cache was recreated", err) - } gitTest(t, f.source, "update-ref", "-d", "refs/heads/new") gitTest(t, f.source, "update-ref", "-d", "refs/tags/v1") sync() - if refs := gitRefs(t, caches[0]); strings.Contains(refs, "refs/heads/new") || strings.Contains(refs, "refs/tags/v1") { - t.Fatal("stale source refs", refs) - } + // The destination push does not prune destination-only refs, and deleting a + // source ref must not delete it from the destination. for _, ref := range []string{"refs/heads/new", "refs/tags/v1", "refs/heads/exclusive", "refs/tags/exclusive"} { if got := gitTest(t, f.destination, "rev-parse", ref); got != base { t.Fatalf("lost destination ref %s", ref) } } - // A cached ref the source renamed into its own path must not block the - // fetch: one atomic fetch cannot delete and create these refs together. - gitTest(t, caches[0], "update-ref", "refs/heads/release", base) - gitTest(t, f.source, "update-ref", "refs/heads/release/v2", base) - sync() - if got := gitTest(t, f.destination, "rev-parse", "refs/heads/release/v2"); got != base { - t.Fatalf("renamed ref %s", got) - } - // A stale push would recreate this ref, making the assertion observable. + // A failed fetch must not change the destination and must release the lock. gitTest(t, f.destination, "update-ref", "-d", "refs/heads/main") before := gitRefs(t, f.destination) if err := os.Rename(f.source, f.source+".offline"); err != nil { @@ -286,42 +262,14 @@ func TestSyncGitNewObjectsAndSecondTarget(t *testing.T) { t.Fatal(got) } } - root, err := os.UserCacheDir() - if err != nil { - t.Fatal(err) - } - caches, err := filepath.Glob(filepath.Join(root, "gh-replicate", "git-v1", "*.git")) - if err != nil || len(caches) != 1 { - t.Fatalf("expected shared source cache: %v %v", caches, err) - } } -// A local SHA-256 default must not leak into the cache: GitHub serves SHA-1. +// A local SHA-256 default must not leak into the ephemeral bare: GitHub serves SHA-1. func TestSyncGitPinsSHA1ObjectFormat(t *testing.T) { - f := newGitFixture(t) - seamStub(t) t.Setenv("GIT_DEFAULT_HASH", "sha256") - gitRemote = func(repo string) string { - if repo == sourceRepo { - return f.source - } - return f.destination - } - s := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) { fmt.Fprint(w, `{"enabled":false}`) }), "token") - r := &replicator{source: s, target: s, ctx: context.Background(), timeout: time.Minute} - if err := r.syncGit(sourceRepo, targetRepo); err != nil { - t.Fatal(err) - } - root, err := os.UserCacheDir() - if err != nil { - t.Fatal(err) - } - caches, err := filepath.Glob(filepath.Join(root, "gh-replicate", "git-v1", "*.git")) - if err != nil || len(caches) != 1 { - t.Fatalf("caches %v: %v", caches, err) - } - if got := gitTest(t, caches[0], "rev-parse", "--show-object-format"); got != "sha1" { - t.Fatalf("cache object format %s", got) + a := newAux(t) + if got := gitTest(t, a.Dir, "--git-dir="+a.Dir, "rev-parse", "--show-object-format"); got != "sha1" { + t.Fatalf("ephemeral bare object format %s", got) } } diff --git a/entrypoint_test.go b/entrypoint_test.go index 875503d..1a733d1 100644 --- a/entrypoint_test.go +++ b/entrypoint_test.go @@ -489,8 +489,8 @@ func TestLFSSyncGitBlocksHistoricalPointerBeforeDestinationEffects(t *testing.T) for _, dry := range []bool{false, true} { r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute, dryRun: dry} err := r.syncGit(sourceRepo, targetRepo) - if err == nil || !strings.Contains(err.Error(), "Git LFS pointers detected") { - t.Fatalf("dryRun=%v error = %v, want LFS detection", dry, err) + if err == nil || !strings.Contains(err.Error(), "Git LFS blob") { + t.Fatalf("dryRun=%v error = %v, want LFS block", dry, err) } if refs := gitRefs(t, f.destination); refs != "" { t.Fatalf("dryRun=%v destination refs published: %q", dry, refs) diff --git a/lfs_auxiliary.go b/lfs_auxiliary.go new file mode 100644 index 0000000..50681a4 --- /dev/null +++ b/lfs_auxiliary.go @@ -0,0 +1,286 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "sort" + "strconv" + "strings" +) + +// lfsAux is an ephemeral bare repository owned by one side of an LFS run. +// It never copies config, HEAD, refs, templates or hooks from the cache. +type lfsAux struct { + Dir string // bare repository + root string + env []string + git string +} + +// Env is built from scratch: no inherited GIT_*, PATH, HOME or tokens. +// shortcut: no PATH, so git helpers/git-lfs are not found; add when transfers are wired. +func lfsAuxEnv(root string) []string { + env := []string{ + "HOME=" + root, "USERPROFILE=" + root, "XDG_CONFIG_HOME=" + filepath.Join(root, "xdg"), + "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=" + os.DevNull, "GIT_TERMINAL_PROMPT=0", + "GIT_ATTR_NOSYSTEM=1", "LC_ALL=C", + } + if runtime.GOOS == "windows" { + // Windows env names are case-insensitive: one spelling only. + for _, k := range []string{"SystemRoot", "ComSpec"} { + if v := os.Getenv(k); v != "" { + env = append(env, k+"="+v) + } + } + } + return env +} + +func (a *lfsAux) run(ctx context.Context, args ...string) error { + cmd := exec.CommandContext(ctx, a.git, args...) // #nosec G204 -- resolved git binary, argv only + cmd.Dir = a.root + cmd.Env = a.env + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("git %s: %w: %s", args[0], err, out) + } + return nil +} + +// newLFSAux creates a private (0700) bare repo with empty native hooks. +func newLFSAux(ctx context.Context) (*lfsAux, error) { + git, err := exec.LookPath("git") + if err != nil { + return nil, err + } + if git, err = filepath.Abs(git); err != nil { + return nil, err + } + // 0700 on Windows does not prove a private ACL; that is not verified here. + root, err := os.MkdirTemp("", "gh-replicate-lfs-") + if err != nil { + return nil, err + } + a := &lfsAux{Dir: filepath.Join(root, "repo.git"), root: root, env: lfsAuxEnv(root), git: git} + hooks := filepath.Join(root, "hooks") + empty := filepath.Join(root, "template") + for _, d := range []string{hooks, empty} { + if err = os.Mkdir(d, 0o700); err != nil { + break + } + } + if err == nil { + err = a.run(ctx, "init", "--bare", "--quiet", "--object-format=sha1", "--template="+empty, a.Dir) + } + if err == nil { + err = a.run(ctx, "--git-dir="+a.Dir, "config", "core.hooksPath", hooks) + } + if err != nil { + _ = a.Close() + return nil, err + } + return a, nil +} + +// Close removes everything; safe to call repeatedly. +func (a *lfsAux) Close() error { + if a == nil || a.root == "" { + return nil + } + err := os.RemoveAll(a.root) + if err == nil { + a.root = "" + } + return err +} + +// lfsCanonicalPointer is the exact pointer text git-lfs writes (spec v1, no extensions). +func lfsCanonicalPointer(oid string, size int64) string { + return fmt.Sprintf("version https://git-lfs.github.com/spec/v1\noid sha256:%s\nsize %d\n", oid, size) +} + +// writePointers stores one canonical pointer blob per inventory object and +// returns oid -> blob id, an unambiguous selector. fast-import streams the +// blobs over stdin (no argv limits) and, with no commit/reset commands, +// creates no refs. An empty inventory runs nothing. +func (a *lfsAux) writePointers(ctx context.Context, inv lfsInventory) (map[string]string, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + oids := make([]string, 0, len(inv)) + for oid, size := range inv { + if err := ctx.Err(); err != nil { + return nil, err + } + if !lfsBareOIDRE.MatchString(oid) { + return nil, fmt.Errorf("invalid Git LFS object id %q", oid) + } + if size <= 0 { + return nil, fmt.Errorf("invalid Git LFS size %d for object %s", size, oid) + } + oids = append(oids, oid) + } + sel := make(map[string]string, len(oids)) + if len(oids) == 0 { + return sel, nil + } + sort.Strings(oids) + var in bytes.Buffer + // shortcut: fast-import gets the whole input as one in-memory buffer (~150 B + // per object); switch to an io.Pipe writer if inventories reach millions of objects. + for i, oid := range oids { + if err := ctx.Err(); err != nil { + return nil, err + } + p := lfsCanonicalPointer(oid, inv[oid]) + fmt.Fprintf(&in, "blob\nmark :%d\ndata %d\n%s\n", i+1, len(p), p) + } + in.WriteString("done\n") + marks := filepath.Join(a.root, "marks") + defer os.Remove(marks) + cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "fast-import", "--quiet", "--done", "--export-marks="+marks) // #nosec G204 -- resolved git binary, argv only + cmd.Dir, cmd.Env, cmd.Stdin = a.root, a.env, &in + if out, err := cmd.CombinedOutput(); err != nil { + return nil, fmt.Errorf("git fast-import: %w: %s", err, out) + } + data, err := os.ReadFile(marks) + if err != nil { + return nil, err + } + return parseLFSMarks(string(data), oids) +} + +// parseLFSMarks fails closed: exactly one ":N <40 lowercase hex>" line per +// mark 1..len(oids), no duplicates, no extra fields. +func parseLFSMarks(data string, oids []string) (map[string]string, error) { + sel := make(map[string]string, len(oids)) + seen := map[string]bool{} + for _, line := range strings.Split(strings.TrimSpace(data), "\n") { + f := strings.Fields(line) + if len(f) != 2 || !strings.HasPrefix(f[0], ":") || !lfsBlobIDRE.MatchString(f[1]) { + return nil, fmt.Errorf("unexpected fast-import mark %q", line) + } + mark, err := strconv.Atoi(f[0][1:]) + if err != nil || mark < 1 || mark > len(oids) || f[0] != ":"+strconv.Itoa(mark) { + return nil, fmt.Errorf("unexpected fast-import mark %q", line) + } + if _, dup := sel[oids[mark-1]]; dup || seen[f[1]] { + return nil, fmt.Errorf("duplicate fast-import mark %q", line) + } + seen[f[1]] = true + sel[oids[mark-1]] = f[1] + } + if len(sel) != len(oids) { + return nil, fmt.Errorf("fast-import returned %d of %d pointers", len(sel), len(oids)) + } + return sel, nil +} + +var lfsBlobIDRE = regexp.MustCompile(`\A[0-9a-f]{40}\z`) + +// pointHEADAbsent sets HEAD to a ref guaranteed absent from the snapshot, so +// git-lfs cannot read a .lfsconfig committed in the replicated history. +func (a *lfsAux) pointHEADAbsent(ctx context.Context, refs []gitRef) error { + name := "refs/heads/gh-replicate-no-lfsconfig" + seen := make(map[string]bool, len(refs)) + for _, ref := range refs { + seen[ref.Name] = true + } + for seen[name] { + name += "_" + } + return a.run(ctx, "--git-dir="+a.Dir, "symbolic-ref", "HEAD", name) +} + +// lfsEndpoint is the GitHub LFS API URL for a repo's HTTPS remote. +func lfsEndpoint(ownerRepo string) string { + return gitRemote(ownerRepo) + "/info/lfs" +} + +// lfsSideEnv is the controlled environment for one side's git/git-lfs run in +// the aux bare: built from scratch with a private home/config, only the side's +// token, no inherited GIT_*, and TLS left enabled. PATH and the transport +// profile (proxy/CA) that the existing git fetch already honors are preserved +// deliberately, so users behind a proxy or custom CA keep working. +func lfsSideEnv(root, token, path string) []string { + env := []string{ + "HOME=" + root, "USERPROFILE=" + root, "XDG_CONFIG_HOME=" + filepath.Join(root, "xdg"), + "GH_CONFIG_DIR=" + filepath.Join(root, "gh"), + "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=" + os.DevNull, "GIT_TERMINAL_PROMPT=0", + "GIT_ATTR_NOSYSTEM=1", "LC_ALL=C", + } + if path != "" { + env = append(env, "PATH="+path) + } + if token != "" { + env = append(env, "GH_TOKEN="+token) + } + for _, k := range []string{"HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY", "ALL_PROXY", "GIT_SSL_CAINFO", "SSL_CERT_FILE"} { + if v := os.Getenv(k); v != "" { + env = append(env, k+"="+v) + } + } + if runtime.GOOS == "windows" { + for _, k := range []string{"SystemRoot", "ComSpec"} { + if v := os.Getenv(k); v != "" { + env = append(env, k+"="+v) + } + } + } + return env +} + +// lfsStandaloneAgent is empty in production: GitHub uses basic HTTPS transfer. +// Tests override it to "lfs-standalone-file" to exercise file:// remotes locally. +var lfsStandaloneAgent = "" + +// lfsCmd builds a git command in the aux bare for one side, with the side's +// isolated environment, its LFS endpoint pinned and the cache lock inherited. +func (r *replicator) lfsCmd(ctx context.Context, a *lfsAux, s side, ownerRepo string, args ...string) *exec.Cmd { + full := append([]string{"-c", "credential.helper=", "-c", "credential.https://github.com.helper=!gh auth git-credential", + "-c", "lfs.url=" + lfsEndpoint(ownerRepo), "-c", "lfs.pushurl=" + lfsEndpoint(ownerRepo), + "-c", "lfs.standalonetransferagent=" + lfsStandaloneAgent}, args...) + cmd := exec.CommandContext(ctx, a.git, full...) // #nosec G204 -- resolved git binary, argv only + cmd.Dir = a.Dir + cmd.Env = lfsSideEnv(a.root, s.token, os.Getenv("PATH")) + if r.cacheLock != nil { + inheritCacheLock(cmd, r.cacheLock) + } + return cmd +} + +func (r *replicator) lfsRun(ctx context.Context, a *lfsAux, s side, ownerRepo string, args ...string) error { + ctx, cancel := context.WithTimeout(ctx, r.timeout) + defer cancel() + cmd := r.lfsCmd(ctx, a, s, ownerRepo, args...) + cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr + if err := cmd.Run(); err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return fmt.Errorf("git %s timed out after %s", args[0], r.timeout) + } + return fmt.Errorf("git %s: %w", args[0], err) + } + return nil +} + +// lfsRunIn is lfsRun with refs fed over stdin, for --stdin commands. +func (r *replicator) lfsRunIn(ctx context.Context, a *lfsAux, s side, ownerRepo string, stdin string, args ...string) error { + ctx, cancel := context.WithTimeout(ctx, r.timeout) + defer cancel() + cmd := r.lfsCmd(ctx, a, s, ownerRepo, args...) + cmd.Stdin = strings.NewReader(stdin) + cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr + if err := cmd.Run(); err != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return fmt.Errorf("git %s timed out after %s", args[0], r.timeout) + } + return fmt.Errorf("git %s: %w", args[0], err) + } + return nil +} diff --git a/lfs_auxiliary_test.go b/lfs_auxiliary_test.go new file mode 100644 index 0000000..970495d --- /dev/null +++ b/lfs_auxiliary_test.go @@ -0,0 +1,313 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" +) + +func must(t *testing.T, err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } +} + +func newAux(t *testing.T) *lfsAux { + t.Helper() + a, err := newLFSAux(context.Background()) + must(t, err) + t.Cleanup(func() { _ = a.Close() }) + return a +} + +func TestLFSAuxIsolation(t *testing.T) { + tpl := t.TempDir() + must(t, os.MkdirAll(filepath.Join(tpl, "hooks"), 0o700)) + must(t, os.WriteFile(filepath.Join(tpl, "hooks", "pre-commit"), []byte("x"), 0o700)) + must(t, os.WriteFile(filepath.Join(tpl, "config"), []byte("[evil]\n\tx=1\n"), 0o600)) + gc := filepath.Join(t.TempDir(), "gc") + must(t, os.WriteFile(gc, []byte("[core]\n\tfsmonitor=evil\n[evil]\n\tg=1\n"), 0o600)) + t.Setenv("GIT_TEMPLATE_DIR", tpl) + t.Setenv("GIT_CONFIG_GLOBAL", gc) + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_CONFIG_KEY_0", "evil.env") + t.Setenv("GIT_CONFIG_VALUE_0", "1") + t.Setenv("GIT_DIR", t.TempDir()) + t.Setenv("GH_TOKEN", "secret-token") + + a := newAux(t) + b := newAux(t) + root := a.root + if b.root == root { + t.Fatal("second side must be distinct") + } + if runtime.GOOS != "windows" { + fi, err := os.Stat(root) + must(t, err) + if fi.Mode().Perm() != 0o700 { + t.Fatalf("mode %v", fi.Mode()) + } + } + for _, d := range []string{filepath.Join(root, "hooks"), filepath.Join(a.Dir, "hooks")} { + ents, err := os.ReadDir(d) + if err != nil && !os.IsNotExist(err) { // empty template: native hooks dir may not exist + t.Fatal(err) + } + if len(ents) != 0 { + t.Fatalf("%s not empty", d) + } + } + cfg, err := os.ReadFile(filepath.Join(a.Dir, "config")) + must(t, err) + if strings.Contains(string(cfg), "evil") || strings.Contains(string(cfg), "secret") { + t.Fatalf("hostile config leaked: %s", cfg) + } + for _, e := range a.env { + if strings.Contains(e, "secret-token") || strings.HasPrefix(e, "GIT_DIR=") || strings.HasPrefix(e, "GIT_TEMPLATE_DIR=") { + t.Fatalf("leaked env %s", e) + } + } + out, err := exec.Command("git", "--git-dir="+a.Dir, "rev-parse", "--is-bare-repository").Output() + must(t, err) + if strings.TrimSpace(string(out)) != "true" { + t.Fatalf("not bare: %s", out) + } + // sha1 objects have 40-hex ids. + cmd := exec.Command("git", "--git-dir="+a.Dir, "hash-object", "--stdin") + cmd.Stdin = strings.NewReader("x") + out, err = cmd.Output() + must(t, err) + if len(strings.TrimSpace(string(out))) != 40 { + t.Fatalf("not sha1: %s", out) + } + for _, x := range []*lfsAux{a, b} { + must(t, x.Close()) + must(t, x.Close()) + } + if _, err := os.Stat(root); !os.IsNotExist(err) { + t.Fatalf("not cleaned: %v", err) + } +} + +func TestLFSAuxEnvNoDuplicateWindowsNames(t *testing.T) { + seen := map[string]bool{} + for _, e := range lfsAuxEnv(t.TempDir()) { + k := strings.ToUpper(strings.SplitN(e, "=", 2)[0]) + if seen[k] { + t.Fatalf("duplicate env %s", k) + } + seen[k] = true + } +} + +func TestLFSAuxRelativePathGitIsAbsoluteOrRejected(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("relative PATH semantics differ") + } + dir := t.TempDir() + must(t, os.WriteFile(filepath.Join(dir, "git"), []byte("#!/bin/sh\nexit 1\n"), 0o700)) + t.Chdir(dir) + t.Setenv("PATH", ".") + a, err := newLFSAux(context.Background()) + if err == nil { + t.Cleanup(func() { _ = a.Close() }) + t.Fatalf("relative PATH git must not run (got %s)", a.git) + } +} + +func TestLFSAuxCleansOnFailure(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) + t.Setenv("TMP", tmp) + t.Setenv("TEMP", tmp) + if _, err := newLFSAux(ctx); err == nil { + t.Fatal("expected error") + } + ents, err := os.ReadDir(tmp) + must(t, err) + if len(ents) != 0 { + t.Fatalf("leftovers: %v", ents) + } +} + +func TestLFSAuxWritePointers(t *testing.T) { + a := newAux(t) + sel, err := a.writePointers(context.Background(), lfsInventory{}) + must(t, err) + if len(sel) != 0 { + t.Fatal("empty inventory must yield no selectors") + } + for _, bad := range []lfsInventory{ + {"xyz": 1}, + {strings.Repeat("A", 64): 1}, + {strings.Repeat("a", 64): 0}, + {strings.Repeat("a", 64): -1}, + } { + if _, err := a.writePointers(context.Background(), bad); err == nil { + t.Fatalf("accepted %v", bad) + } + } + inv := lfsInventory{} + for i := 0; i < 3000; i++ { + h := sha256.Sum256([]byte(strconv.Itoa(i))) + inv[hex.EncodeToString(h[:])] = int64(i + 1) + } + sel, err = a.writePointers(context.Background(), inv) + must(t, err) + if len(sel) != len(inv) { + t.Fatalf("%d selectors for %d objects", len(sel), len(inv)) + } + // Stream every selector through cat-file and compare bytes and blob id. + var q strings.Builder + oids := make([]string, 0, len(sel)) + for oid, id := range sel { + oids = append(oids, oid) + q.WriteString(id + "\n") + } + cmd := exec.Command(a.git, "--git-dir="+a.Dir, "cat-file", "--batch") + cmd.Env, cmd.Stdin = a.env, strings.NewReader(q.String()) + out, err := cmd.Output() + must(t, err) + r := bufio.NewReader(bytes.NewReader(out)) + seen := map[string]bool{} + for _, oid := range oids { + hdr, err := r.ReadString('\n') + must(t, err) + var id, typ string + var n int + if _, err := fmt.Sscanf(hdr, "%s %s %d", &id, &typ, &n); err != nil || typ != "blob" || id != sel[oid] || seen[id] { + t.Fatalf("bad header %q for %s", hdr, oid) + } + seen[id] = true + body := make([]byte, n+1) + _, err = io.ReadFull(r, body) + must(t, err) + if string(body[:n]) != lfsCanonicalPointer(oid, inv[oid]) { + t.Fatalf("pointer mismatch for %s: %q", oid, body[:n]) + } + if lfs, err := exec.LookPath("git-lfs"); err == nil && len(seen) <= 3 { + c := exec.Command(lfs, "pointer", "--check", "--strict", "--stdin") + c.Env, c.Stdin = a.env, bytes.NewReader(body[:n]) + if out, err := c.CombinedOutput(); err != nil { + t.Fatalf("git-lfs rejects pointer: %v %s", err, out) + } + } + } + refs := exec.Command(a.git, "--git-dir="+a.Dir, "for-each-ref") + refs.Env = a.env + out, err = refs.Output() + must(t, err) + if len(out) != 0 { + t.Fatalf("refs created: %s", out) + } + if _, err := os.Stat(filepath.Join(a.root, "marks")); !os.IsNotExist(err) { + t.Fatalf("marks left: %v", err) + } +} + +func TestLFSAuxWritePointersCanceled(t *testing.T) { + a := newAux(t) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := a.writePointers(ctx, lfsInventory{}); err == nil { + t.Fatal("canceled ctx with empty inventory must fail") + } + inv := lfsInventory{strings.Repeat("a", 64): 1} + if _, err := a.writePointers(ctx, inv); err == nil { + t.Fatal("canceled ctx must fail") + } +} + +func TestLFSParseMarks(t *testing.T) { + id1, id2 := strings.Repeat("1", 40), strings.Repeat("2", 40) + oids := []string{"a", "b"} + if sel, err := parseLFSMarks(":1 "+id1+"\n:2 "+id2+"\n", oids); err != nil || sel["b"] != id2 { + t.Fatalf("valid rejected: %v", err) + } + for _, bad := range []string{ + ":1 " + id1, // missing mark + ":1 " + id1 + "\n:1 " + id2, // duplicate mark + ":1 " + id1 + "\n:2 " + id1, // duplicate blob id + ":1 " + id1 + "\n:3 " + id2, // out of range + ":1 " + id1 + "\n:2 " + strings.Repeat("G", 40), // non-hex + ":1 " + id1 + "\n:2 " + strings.Repeat("A", 40), // uppercase + ":1 " + id1 + "\n:2 " + strings.Repeat("2", 64), // sha256-length id + ":1 " + id1 + "\n:2 " + id2 + " extra", + ":1 " + id1 + "\n:+2 " + id2, + ":1 " + id1 + "\n garbage", + } { + if _, err := parseLFSMarks(bad, oids); err == nil { + t.Fatalf("accepted %q", bad) + } + } +} + +func TestLFSSideEnvIsolation(t *testing.T) { + t.Setenv("GIT_DIR", "/evil") + t.Setenv("GH_TOKEN", "inherited-token") + t.Setenv("GITHUB_TOKEN", "also-inherited") + t.Setenv("HTTPS_PROXY", "http://proxy:3128") + root := t.TempDir() + env := lfsSideEnv(root, "side-token", "/usr/bin:/bin") + + got := map[string]string{} + for _, e := range env { + if i := strings.IndexByte(e, '='); i >= 0 { + got[e[:i]] = e[i+1:] + } + } + if got["GIT_DIR"] != "" { + t.Fatalf("GIT_DIR leaked: %q", got["GIT_DIR"]) + } + if got["GH_TOKEN"] != "side-token" { + t.Fatalf("GH_TOKEN = %q, want side-token", got["GH_TOKEN"]) + } + if got["GITHUB_TOKEN"] != "" { + t.Fatalf("GITHUB_TOKEN leaked: %q", got["GITHUB_TOKEN"]) + } + if got["PATH"] != "/usr/bin:/bin" { + t.Fatalf("PATH = %q", got["PATH"]) + } + if got["HTTPS_PROXY"] != "http://proxy:3128" { + t.Fatalf("HTTPS_PROXY = %q", got["HTTPS_PROXY"]) + } + if got["GIT_CONFIG_NOSYSTEM"] != "1" || got["GIT_CONFIG_GLOBAL"] != os.DevNull { + t.Fatalf("git config isolation missing: %q", got) + } + if got["HOME"] != root || got["GH_CONFIG_DIR"] == "" { + t.Fatalf("private home/config missing: %q", got) + } +} + +func TestLFSEndpoint(t *testing.T) { + if got := lfsEndpoint("owner/repo"); got != "https://github.com/owner/repo.git/info/lfs" { + t.Fatalf("endpoint = %q", got) + } +} + +func TestLFSAuxPointHEADAbsent(t *testing.T) { + a := newAux(t) + refs := []gitRef{{Name: "refs/heads/gh-replicate-no-lfsconfig", ID: strings.Repeat("1", 40)}} + must(t, a.pointHEADAbsent(context.Background(), refs)) + // The collision guard must pick a name not present in the snapshot. + if got := gitTest(t, a.Dir, "--git-dir="+a.Dir, "symbolic-ref", "HEAD"); got != "refs/heads/gh-replicate-no-lfsconfig_" { + t.Fatalf("HEAD = %q", got) + } + if gitTest(t, a.Dir, "--git-dir="+a.Dir, "for-each-ref", "--format=%(refname)") != "" { + t.Fatalf("absent ref was materialized") + } +} diff --git a/lfs_integration_test.go b/lfs_integration_test.go new file mode 100644 index 0000000..a885053 --- /dev/null +++ b/lfs_integration_test.go @@ -0,0 +1,217 @@ +//go:build lfsintegration + +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// lfsServer is a minimal Git LFS batch API + basic transfer over HTTP, enough +// for transferLFS to run against a real git-lfs without GitHub or credentials. +type lfsServer struct { + mu sync.Mutex + objects map[string][]byte +} + +func newLFSServer(t *testing.T) (*httptest.Server, *lfsServer) { + t.Helper() + s := &lfsServer{objects: map[string][]byte{}} + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/info/lfs/objects/batch"): + s.batch(w, r) + case strings.HasPrefix(r.URL.Path, "/objects/"): + s.object(w, r) + default: + http.Error(w, "not found", 404) + } + })) + t.Cleanup(ts.Close) + return ts, s +} + +func (s *lfsServer) batch(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", 405) + return + } + var req struct { + Operation string `json:"operation"` + Objects []struct { + OID string `json:"oid"` + Size int64 `json:"size"` + } `json:"objects"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), 400) + return + } + s.mu.Lock() + defer s.mu.Unlock() + action := map[string]bool{"download": true, "upload": true}[req.Operation] + if !action { + http.Error(w, "unsupported operation", 400) + return + } + objects := make([]map[string]any, 0, len(req.Objects)) + for _, o := range req.Objects { + if req.Operation == "download" { + if _, ok := s.objects[o.OID]; !ok { + http.Error(w, "missing object "+o.OID, 404) + return + } + } + objects = append(objects, map[string]any{ + "oid": o.OID, + "size": o.Size, + "actions": map[string]any{ + req.Operation: map[string]any{ + "href": "http://" + r.Host + "/objects/" + o.OID, + "header": map[string]string{"Authorization": "Bearer test"}, + }, + }, + }) + } + w.Header().Set("Content-Type", "application/vnd.git-lfs+json") + _ = json.NewEncoder(w).Encode(map[string]any{"transfer": "basic", "objects": objects}) +} + +func (s *lfsServer) object(w http.ResponseWriter, r *http.Request) { + oid := strings.TrimPrefix(r.URL.Path, "/objects/") + s.mu.Lock() + defer s.mu.Unlock() + switch r.Method { + case http.MethodGet: + data, ok := s.objects[oid] + if !ok { + http.Error(w, "not found", 404) + return + } + _, _ = w.Write(data) + case http.MethodPut: + data, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), 400) + return + } + s.objects[oid] = data + w.WriteHeader(200) + default: + http.Error(w, "method not allowed", 405) + } +} + +func (s *lfsServer) add(oid string, data []byte) { + s.mu.Lock() + defer s.mu.Unlock() + s.objects[oid] = data +} + +func (s *lfsServer) has(oid string) bool { + s.mu.Lock() + defer s.mu.Unlock() + _, ok := s.objects[oid] + return ok +} + +func (s *lfsServer) get(oid string) []byte { + s.mu.Lock() + defer s.mu.Unlock() + return s.objects[oid] +} + +func sha256hex(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +// TestLFSIntegrationTransfer runs the real transferLFS path over HTTP against a +// real git-lfs: a source bare with historical and tagged canonical pointers, an +// isolated source LFS server, and a fresh destination server. It requires +// git-lfs (>= 3.8.1) on PATH and fails otherwise. +func TestLFSIntegrationTransfer(t *testing.T) { + if _, err := exec.LookPath("git-lfs"); err != nil { + t.Fatalf("git-lfs is required for -tags=lfsintegration: %v", err) + } + content1 := []byte("hello lfs v1\n") + content2 := []byte("hello lfs v2 longer\n") + oid1, oid2 := sha256hex(content1), sha256hex(content2) + + src, srcStore := newLFSServer(t) + dst, dstStore := newLFSServer(t) + srcStore.add(oid1, content1) + srcStore.add(oid2, content2) + + // Source bare with a branch (two pointer versions, one historical) and a tag. + srcBare := filepath.Join(t.TempDir(), "src.git") + gitTest(t, t.TempDir(), "init", "--bare", srcBare) + work := t.TempDir() + gitTest(t, work, "init", "-b", "main") + gitTest(t, work, "config", "user.name", "Test") + gitTest(t, work, "config", "user.email", "test@example.com") + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(lfsCanonicalPointer(oid1, int64(len(content1)))), 0o644)) + gitTest(t, work, "add", ".") + gitTest(t, work, "commit", "-m", "v1") + gitTest(t, work, "tag", "v1") + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(lfsCanonicalPointer(oid2, int64(len(content2)))), 0o644)) + gitTest(t, work, "add", ".") + gitTest(t, work, "commit", "-m", "v2") + gitTest(t, work, "push", "file://"+srcBare, "refs/heads/main:refs/heads/main", "refs/tags/v1:refs/tags/v1") + + // Route the LFS endpoint seam to the synthetic servers. + prev := gitRemote + gitRemote = func(ownerRepo string) string { + if ownerRepo == "dst" { + return dst.URL + } + return src.URL + } + defer func() { gitRemote = prev }() + + a := newAux(t) + r := &replicator{ctx: context.Background(), timeout: time.Minute, source: side{}, target: side{}} + + // The target remote must exist for `git lfs push` to name it; lfs.pushurl + // (pinned to the synthetic server) drives the actual endpoint. + must(t, a.run(context.Background(), "--git-dir="+a.Dir, "config", "remote.replicate-target.url", dst.URL)) + + // Fetch source refs into the aux bare over file:// (no LFS here). + must(t, a.run(context.Background(), "--git-dir="+a.Dir, "fetch", "--prune", "--no-tags", + "file://"+srcBare, "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*")) + refs, err := r.captureRefs(a.Dir) + must(t, err) + inv, err := r.inventoryLFS(a.Dir, refs) + must(t, err) + if len(inv) != 2 { + t.Fatalf("inventory has %d objects, want 2", len(inv)) + } + must(t, a.pointHEADAbsent(context.Background(), refs)) + + must(t, r.transferLFS(context.Background(), a, "src", "dst", refs, inv)) + + for _, oid := range []string{oid1, oid2} { + if !dstStore.has(oid) { + t.Fatalf("destination missing LFS object %s", oid) + } + } + if !bytes.Equal(dstStore.get(oid1), content1) { + t.Fatalf("destination object %s bytes differ", oid1) + } + if !bytes.Equal(dstStore.get(oid2), content2) { + t.Fatalf("destination object %s bytes differ", oid2) + } +} diff --git a/lfs_objects.go b/lfs_objects.go new file mode 100644 index 0000000..c207028 --- /dev/null +++ b/lfs_objects.go @@ -0,0 +1,79 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "path/filepath" + "regexp" +) + +var lfsBareOIDRE = regexp.MustCompile(`\A[0-9a-f]{64}\z`) + +// verifyLFSObjects checks that every inventory object exists under +// root/objects/aa/bb/OID as a regular file with the expected size and SHA-256. +// It fails closed on the first problem. root must already be a controlled +// directory (parent symlinks are not checked): it does not detect concurrent mutation nor that git-lfs later +// reads this storage. +func verifyLFSObjects(ctx context.Context, root string, inv lfsInventory) error { + if err := ctx.Err(); err != nil { + return err + } + for oid, size := range inv { + if err := ctx.Err(); err != nil { + return err + } + if !lfsBareOIDRE.MatchString(oid) { + return fmt.Errorf("invalid Git LFS object id %q", oid) + } + if err := verifyLFSObject(ctx, filepath.Join(root, "objects", oid[:2], oid[2:4], oid), oid, size); err != nil { + return err + } + } + return nil +} + +func verifyLFSObject(ctx context.Context, path, oid string, size int64) error { + fi, err := os.Lstat(path) + if err != nil { + return fmt.Errorf("Git LFS object %s: %w", oid, err) + } + if !fi.Mode().IsRegular() { + return fmt.Errorf("Git LFS object %s is not a regular file", oid) + } + if fi.Size() != size { + return fmt.Errorf("Git LFS object %s has size %d, expected %d", oid, fi.Size(), size) + } + f, err := os.Open(path) + if err != nil { + return fmt.Errorf("Git LFS object %s: %w", oid, err) + } + defer f.Close() + h := sha256.New() + buf := make([]byte, 64*1024) + var n int64 + for { + if err := ctx.Err(); err != nil { + return err + } + m, rerr := f.Read(buf) + h.Write(buf[:m]) + n += int64(m) + if rerr == io.EOF { + break + } + if rerr != nil { + return fmt.Errorf("Git LFS object %s: %w", oid, rerr) + } + } + if n != size { + return fmt.Errorf("Git LFS object %s read %d bytes, expected %d", oid, n, size) + } + if got := hex.EncodeToString(h.Sum(nil)); got != oid { + return fmt.Errorf("Git LFS object %s has SHA-256 %s", oid, got) + } + return nil +} diff --git a/lfs_objects_test.go b/lfs_objects_test.go new file mode 100644 index 0000000..d2c6d2d --- /dev/null +++ b/lfs_objects_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "testing" +) + +func putLFSObject(t *testing.T, root string, data []byte) string { + t.Helper() + sum := sha256.Sum256(data) + oid := hex.EncodeToString(sum[:]) + dir := filepath.Join(root, "objects", oid[:2], oid[2:4]) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, oid), data, 0o644); err != nil { + t.Fatal(err) + } + return oid +} + +func TestLFSVerifyObjects(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + oid := putLFSObject(t, root, []byte("hello")) + oid2 := putLFSObject(t, root, []byte("world!")) + + if err := verifyLFSObjects(ctx, root, lfsInventory{oid: 5, oid2: 6}); err != nil { + t.Fatalf("good objects: %v", err) + } + if err := verifyLFSObjects(ctx, root, lfsInventory{oid: 5, oid2: 7}); err == nil { + t.Fatal("second object's wrong size accepted") + } + dirOID := sha256.Sum256([]byte("dir")) + d := hex.EncodeToString(dirOID[:]) + if err := os.MkdirAll(filepath.Join(root, "objects", d[:2], d[2:4], d), 0o755); err != nil { + t.Fatal(err) + } + if err := verifyLFSObjects(ctx, root, lfsInventory{d: 0}); err == nil { + t.Fatal("non-regular path accepted") + } + done, stop := context.WithCancel(ctx) + stop() + if err := verifyLFSObjects(done, root, lfsInventory{}); err != context.Canceled { + t.Fatalf("empty inventory, canceled ctx: got %v", err) + } + if err := verifyLFSObjects(ctx, root, lfsInventory{}); err != nil { + t.Fatalf("empty inventory: %v", err) + } + if err := verifyLFSObjects(ctx, root, lfsInventory{oid: 6}); err == nil { + t.Fatal("wrong size accepted") + } + missing := sha256.Sum256([]byte("x")) + if err := verifyLFSObjects(ctx, root, lfsInventory{hex.EncodeToString(missing[:]): 1}); err == nil { + t.Fatal("missing object accepted") + } + if err := verifyLFSObjects(ctx, root, lfsInventory{"../x": 1}); err == nil { + t.Fatal("invalid oid accepted") + } + + p := filepath.Join(root, "objects", oid[:2], oid[2:4], oid) + if err := os.WriteFile(p, []byte("HELLO"), 0o644); err != nil { + t.Fatal(err) + } + if err := verifyLFSObjects(ctx, root, lfsInventory{oid: 5}); err == nil { + t.Fatal("corrupt same-size object accepted") + } + + cctx, cancel := context.WithCancel(ctx) + cancel() + if err := verifyLFSObjects(cctx, root, lfsInventory{oid: 5}); err != context.Canceled { + t.Fatalf("want context.Canceled, got %v", err) + } +} diff --git a/lfs_pointer.go b/lfs_pointer.go new file mode 100644 index 0000000..20578fa --- /dev/null +++ b/lfs_pointer.go @@ -0,0 +1,73 @@ +package main + +import ( + "bytes" + "fmt" + "regexp" + "strconv" + "strings" +) + +// lfsPrefixSize is how much of a blob Git LFS 3.8.1 parses (one read of up to +// 1024 bytes); anything after it is ignored there, so it is ignored here too. +const lfsPrefixSize = 1024 + +// lfsPointer identifies the object a confirmed pointer refers to. +type lfsPointer struct { + OID string // lowercase hex SHA-256 + Size int64 +} + +var lfsOIDRE = regexp.MustCompile(`\Asha256:[0-9a-f]{64}\z`) + +// classifyLFSBlob inspects the first min(blobSize, 1024) bytes of a non-empty +// blob, passed as prefix. Results: +// - none: no known version alias or recognizable Git LFS version line. +// - confirmed: a complete, canonical v1 pointer with positive size. +// - blocked: a candidate outside the supported subset; callers must stop. +// +// shortcut: noncanonical pointers remain blocked until their transfer is proven; +// unknown future formats cannot be detected universally. Callers skip empty blobs. +func classifyLFSBlob(prefix []byte, blobSize int64) (p lfsPointer, found bool, blocked string) { + // Fail closed first: "none" is only valid for the complete committed prefix. + if blobSize <= 0 || int64(len(prefix)) != min(blobSize, lfsPrefixSize) { + return p, false, "prefix does not match min(blob size, 1024) bytes" + } + candidate := isLFSPointer(prefix) + for _, line := range bytes.Split(prefix, []byte("\n")) { + if bytes.HasPrefix(bytes.TrimSpace(line), []byte("version https://git-lfs.github.com/spec/")) { + candidate = true + } + } + if !candidate { + return lfsPointer{}, false, "" + } + if blobSize >= lfsPrefixSize { + return p, false, "Git LFS pointer is too large for the supported format" + } + lines := strings.Split(string(prefix), "\n") + if len(lines) != 4 || lines[0] != "version https://git-lfs.github.com/spec/v1" || lines[3] != "" { + return p, false, "unsupported or noncanonical Git LFS pointer" + } + oid, ok := strings.CutPrefix(lines[1], "oid ") + if !ok || !lfsOIDRE.MatchString(oid) { + return p, false, "invalid pointer oid" + } + sizeText, ok := strings.CutPrefix(lines[2], "size ") + size, err := strconv.ParseInt(sizeText, 10, 64) + if !ok || err != nil || size <= 0 || strconv.FormatInt(size, 10) != sizeText { + return p, false, "invalid or empty pointer size" + } + return lfsPointer{OID: strings.TrimPrefix(oid, "sha256:"), Size: size}, true, "" +} + +// lfsInventory maps each OID to its size so conflicting pointers are caught. +type lfsInventory map[string]int64 + +func (inv lfsInventory) add(p lfsPointer) error { + if old, ok := inv[p.OID]; ok && old != p.Size { + return fmt.Errorf("conflicting Git LFS sizes for object %s: %d and %d", p.OID, old, p.Size) + } + inv[p.OID] = p.Size + return nil +} diff --git a/lfs_pointer_test.go b/lfs_pointer_test.go new file mode 100644 index 0000000..43d3776 --- /dev/null +++ b/lfs_pointer_test.go @@ -0,0 +1,372 @@ +package main + +import ( + "bytes" + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +const ( + ptrOID = "sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393" + ptrHex = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393" + ptrV1 = "https://git-lfs.github.com/spec/v1" + hawser = "https://hawser.github.com/spec/v1" + media = "http://git-media.io/v/2" + ptrBody = "oid " + ptrOID + "\nsize 12345\n" +) + +func pad(s string, n int) string { return s + strings.Repeat("\n", n-len(s)) } + +type lfsCase struct { + name string + data string + blocked bool // expected blocked (alias present but not confirmed) + found bool +} + +func lfsCases() []lfsCase { + crlf := func(s string) string { return strings.ReplaceAll(s, "\n", "\r\n") } + long := "version " + ptrV1 + "\n" + ptrBody + return []lfsCase{ + {name: "lfs", data: long, found: true}, + {name: "hawser", data: "version " + hawser + "\n" + ptrBody, blocked: true}, + {name: "git-media", data: "version " + media + "\n" + ptrBody, blocked: true}, + {name: "crlf", data: crlf(long), blocked: true}, + {name: "leading whitespace", data: " \n\t" + long, blocked: true}, + {name: "no trailing newline", data: strings.TrimSuffix(long, "\n"), blocked: true}, + {name: "padded 1023", data: pad(long, 1023), blocked: true}, + {name: "padded 1024", data: pad(long, 1024), blocked: true}, + {name: "padded 1025", data: pad(long, 1025), blocked: true}, + {name: "padded 2127", data: pad(long, 2127), blocked: true}, + {name: "blank lines between", data: "version " + ptrV1 + "\n\n" + ptrBody, blocked: true}, + {name: "extension", data: "version " + ptrV1 + "\next-0-foo " + ptrOID + "\n" + ptrBody, blocked: true}, + {name: "extension before version", data: "ext-0-foo " + ptrOID + "\n" + long, blocked: true}, + {name: "swapped order", data: "version " + ptrV1 + "\nsize 12345\noid " + ptrOID + "\n", blocked: true}, + {name: "missing size", data: "version " + ptrV1 + "\noid " + ptrOID + "\n", blocked: true}, + {name: "zero size", data: "version " + ptrV1 + "\noid " + ptrOID + "\nsize 0\n", blocked: true}, + {name: "plus size", data: "version " + ptrV1 + "\noid " + ptrOID + "\nsize +5\n", blocked: true}, + {name: "leading zero size", data: "version " + ptrV1 + "\noid " + ptrOID + "\nsize 05\n", blocked: true}, + {name: "overflow size", data: "version " + ptrV1 + "\noid " + ptrOID + "\nsize 9223372036854775808\n", blocked: true}, + {name: "uppercase oid", data: "version " + ptrV1 + "\noid sha256:" + strings.ToUpper(ptrHex) + "\nsize 5\n", blocked: true}, + {name: "extra line", data: long + "extra x\n", blocked: true}, + {name: "trailing space in version", data: "version " + ptrV1 + " \n" + ptrBody, blocked: true}, + {name: "indented version line", data: "oid " + ptrOID + "\n version " + ptrV1 + "\nsize 5\n", blocked: true}, + {name: "prose", data: "see version " + ptrV1 + " for details\n"}, + {name: "plain text", data: "hello\n"}, + {name: "unknown future version", data: "version https://git-lfs.github.com/spec/v2\n" + ptrBody, blocked: true}, + } +} + +func classifyCase(data string) (lfsPointer, bool, string) { + b := []byte(data) + n := min(len(b), lfsPrefixSize) + return classifyLFSBlob(b[:n], int64(len(b))) +} + +func TestLFSClassifyBlob(t *testing.T) { + for _, c := range lfsCases() { + t.Run(c.name, func(t *testing.T) { + p, found, blocked := classifyCase(c.data) + if found != c.found || (blocked != "") != c.blocked { + t.Fatalf("found=%v blocked=%q, want found=%v blocked=%v", found, blocked, c.found, c.blocked) + } + if found && (p.OID != ptrHex || p.Size != 12345) { + t.Fatalf("pointer = %+v", p) + } + }) + } +} + +// A cut that lands inside content could change a value, so it must block. +func TestLFSClassifyBlobCutInsideContent(t *testing.T) { + head := "version " + ptrV1 + "\noid " + ptrOID + "\nsize " + data := head + strings.Repeat("1", 2000) + if _, found, blocked := classifyCase(data); found || blocked == "" { + t.Fatalf("found=%v blocked=%q", found, blocked) + } +} + +// A short prefix must block even when it holds no alias but the rest does. +func TestLFSClassifyBlobShortPrefixFailsClosed(t *testing.T) { + full := pad("hello\n", 1100) + "version " + ptrV1 + "\n" + ptrBody + for _, c := range []struct { + prefix string + size int64 + }{ + {full[:300], int64(len(full))}, // truncated below min(size, 1024) + {full, int64(len(full)) + 5}, // longer than declared + {full[:1024] + "x", 5000}, // longer than the cap + {"", 0}, // empty blob + {"version " + ptrV1 + "\n", -1}, // invalid size + } { + if _, found, blocked := classifyLFSBlob([]byte(c.prefix), c.size); found || blocked == "" { + t.Fatalf("len=%d size=%d: found=%v blocked=%q", len(c.prefix), c.size, found, blocked) + } + } +} + +func TestLFSInventoryConflicts(t *testing.T) { + inv := lfsInventory{} + if err := inv.add(lfsPointer{OID: ptrHex, Size: 1}); err != nil { + t.Fatal(err) + } + if err := inv.add(lfsPointer{OID: ptrHex, Size: 1}); err != nil { + t.Fatal(err) + } + if err := inv.add(lfsPointer{OID: ptrHex, Size: 2}); err == nil || !strings.Contains(err.Error(), "conflicting") { + t.Fatalf("error = %v", err) + } +} + +// Contrast with a real git-lfs: set GIT_LFS_TEST_BIN to run it; ordinary runs +// need no git-lfs. Soundness: confirmed implies git-lfs accepts; and anything +// git-lfs accepts is never classified as "none". +func TestLFSClassifyBlobAgainstGitLFS(t *testing.T) { + bin := os.Getenv("GIT_LFS_TEST_BIN") + if bin == "" { + t.Skip("GIT_LFS_TEST_BIN not set") + } + for _, c := range lfsCases() { + t.Run(c.name, func(t *testing.T) { + cmd := exec.Command(bin, "pointer", "--check", "--no-strict", "--stdin") + cmd.Stdin = bytes.NewReader([]byte(c.data)) + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + accepted := cmd.Run() == nil + _, found, blocked := classifyCase(c.data) + if found && !accepted { + t.Fatal("confirmed a pointer that git-lfs rejects") + } + if accepted && !found && blocked == "" { + t.Fatal("git-lfs accepts it but it was classified as none") + } + if c.found && !accepted { + t.Fatal("fixture expected valid for git-lfs") + } + }) + } +} + +func invNow(r *replicator, dir string) (lfsInventory, error) { + refs, err := r.captureRefs(dir) + if err != nil { + return nil, err + } + return r.inventoryLFS(dir, refs) +} + +func lfsPtr(c byte, size string) []byte { + return []byte("version " + ptrV1 + "\noid sha256:" + strings.Repeat(string(c), 64) + "\nsize " + size + "\n") +} + +func lfsBlob(t *testing.T, dir string, data []byte) string { + t.Helper() + cmd := exec.Command("git", "hash-object", "-w", "--stdin") + cmd.Dir, cmd.Stdin = dir, bytes.NewReader(data) + out, err := cmd.Output() + if err != nil { + t.Fatal(err) + } + return strings.TrimSpace(string(out)) +} + +func TestLFSInventoryHistoryTagsAndObsolete(t *testing.T) { + big := bytes.Repeat([]byte{0xff, 'x'}, 40000) // binary, no LF, before the pointers + dir := lfsWorkRepo(t, map[string][]byte{"big.bin": big, "a.ptr": lfsPtr('a', "10")}) + gitTest(t, dir, "rm", "-q", "a.ptr") // pointer survives only in history + gitTest(t, dir, "commit", "-m", "drop") + gitTest(t, dir, "update-ref", "refs/tags/b", lfsBlob(t, dir, lfsPtr('b', "20"))) + gitTest(t, dir, "update-ref", "refs/tags/c", lfsBlob(t, dir, lfsPtr('c', "30"))) + lfsBlob(t, dir, lfsPtr('d', "40")) // unreachable cached object + + r := &replicator{ctx: context.Background(), timeout: time.Minute} + inv, err := invNow(r, dir) + if err != nil { + t.Fatal(err) + } + want := lfsInventory{strings.Repeat("a", 64): 10, strings.Repeat("b", 64): 20, strings.Repeat("c", 64): 30} + if len(inv) != len(want) { + t.Fatalf("inventory = %v", inv) + } + for oid, size := range want { + if inv[oid] != size { + t.Fatalf("oid %s size = %d, want %d", oid, inv[oid], size) + } + } + wantLFS(t, r.checkLFS(dir)) +} + +func TestLFSInventoryFailsClosed(t *testing.T) { + r := &replicator{ctx: context.Background(), timeout: time.Minute} + conflict := lfsWorkRepo(t, map[string][]byte{"x": lfsPtr('a', "10"), "y": lfsPtr('a', "11")}) + ext := lfsWorkRepo(t, map[string][]byte{"x": []byte("version " + ptrV1 + "\next-0-foo " + ptrOID + "\n" + ptrBody)}) + for name, c := range map[string]struct{ dir, want string }{ + "conflicting sizes": {conflict, "conflicting Git LFS sizes"}, + "extension": {ext, "unsupported or noncanonical"}, + } { + t.Run(name, func(t *testing.T) { + inv, err := invNow(r, c.dir) + if err == nil || inv != nil || !strings.Contains(err.Error(), c.want) || !strings.Contains(err.Error(), "Git LFS blob ") { + t.Fatalf("inventory = %v, err = %v", inv, err) + } + wantLFS(t, r.checkLFS(c.dir)) + }) + } +} + +func TestLFSInventoryCheckBlocksAmbiguous(t *testing.T) { + dir := lfsWorkRepo(t, map[string][]byte{"x": []byte("version " + ptrV1 + "\nsize 5\noid " + ptrOID + "\n")}) + r := &replicator{ctx: context.Background(), timeout: time.Minute} + wantLFS(t, r.checkLFS(dir)) + if inv, err := invNow(r, dir); err == nil || inv != nil { + t.Fatalf("inventory = %v, err = %v", inv, err) + } +} + +func TestLFSInventoryRejectsUnsupportedHistoricalPointer(t *testing.T) { + dir := lfsWorkRepo(t, map[string][]byte{ + "valid": lfsPtr('a', "10"), + "old": []byte(pad(string(lfsPtr('b', "20")), 1024)), + }) + gitTest(t, dir, "rm", "-q", "old") + gitTest(t, dir, "commit", "-m", "remove unsupported pointer") + r := &replicator{ctx: context.Background(), timeout: time.Minute} + if inv, err := invNow(r, dir); err == nil || inv != nil { + t.Fatalf("inventory = %v, err = %v", inv, err) + } +} + +func TestLFSInventoryNoLFSAndErrors(t *testing.T) { + dir := lfsWorkRepo(t, map[string][]byte{"a.txt": []byte("hello\n")}) + r := &replicator{ctx: context.Background(), timeout: time.Minute} + if inv, err := invNow(r, dir); err != nil || inv == nil || len(inv) != 0 { + t.Fatalf("inventory = %v, err = %v", inv, err) + } + if err := r.checkLFS(dir); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + r.ctx = ctx + if _, err := invNow(r, dir); err == nil { + t.Fatal("cancelled inventory succeeded") + } + r.ctx = context.Background() + if _, err := invNow(r, filepath.Join(dir, "missing")); err == nil { + t.Fatal("missing repository succeeded") + } +} + +func TestLFSInventoryUsesCapturedRefsOnly(t *testing.T) { + dir := lfsWorkRepo(t, map[string][]byte{"a.ptr": lfsPtr('a', "10")}) + gitTest(t, dir, "update-ref", "refs/tags/blob", lfsBlob(t, dir, lfsPtr('b', "20"))) // tag to a blob + gitTest(t, dir, "-c", "user.name=T", "-c", "user.email=t@e", "tag", "-a", "-m", "x", "ann", "HEAD") // annotated + r := &replicator{ctx: context.Background(), timeout: time.Minute} + refs, err := r.captureRefs(dir) + if err != nil { + t.Fatal(err) + } + names := map[string]bool{} + for _, ref := range refs { + names[ref.Name] = true + } + if len(refs) != 3 || !names["refs/heads/main"] || !names["refs/tags/blob"] || !names["refs/tags/ann"] { + t.Fatalf("refs = %+v", refs) + } + // Mutate after the capture: delete the blob tag, advance main, add a tag. + gitTest(t, dir, "update-ref", "-d", "refs/tags/blob") + if err := os.WriteFile(filepath.Join(dir, "c.ptr"), lfsPtr('c', "30"), 0o644); err != nil { + t.Fatal(err) + } + gitTest(t, dir, "add", ".") + gitTest(t, dir, "commit", "-m", "later") + gitTest(t, dir, "update-ref", "refs/tags/later", lfsBlob(t, dir, lfsPtr('d', "40"))) + inv, err := r.inventoryLFS(dir, refs) + if err != nil { + t.Fatal(err) + } + want := lfsInventory{strings.Repeat("a", 64): 10, strings.Repeat("b", 64): 20} + if len(inv) != 2 || inv[strings.Repeat("a", 64)] != 10 || inv[strings.Repeat("b", 64)] != 20 { + t.Fatalf("inventory = %v, want %v", inv, want) + } +} + +func TestLFSInventoryEmptyCaptureIsEmpty(t *testing.T) { + dir := t.TempDir() + gitTest(t, dir, "init", "-b", "main") + r := &replicator{ctx: context.Background(), timeout: time.Minute} + refs, err := r.captureRefs(dir) + if err != nil || len(refs) != 0 { + t.Fatalf("refs = %v, err = %v", refs, err) + } + // Pointer created after the empty capture must not appear ("--all" would find it). + gitTest(t, dir, "update-ref", "refs/tags/late", lfsBlob(t, dir, lfsPtr('a', "10"))) + gitTest(t, dir, "update-ref", "refs/notes/x", lfsBlob(t, dir, lfsPtr('b', "10"))) + inv, err := r.inventoryLFS(dir, refs) + if err != nil || inv == nil || len(inv) != 0 { + t.Fatalf("inventory = %v, err = %v", inv, err) + } +} + +func TestLFSCaptureRefsErrors(t *testing.T) { + r := &replicator{ctx: context.Background(), timeout: time.Minute} + if _, err := r.captureRefs(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Fatal("missing repository succeeded") + } + dir := lfsWorkRepo(t, map[string][]byte{"a.txt": []byte("x")}) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + r.ctx = ctx + if _, err := r.captureRefs(dir); err == nil { + t.Fatal("cancelled capture succeeded") + } + // Captured tips that no longer exist make the scan fail, never pass silently. + r.ctx = context.Background() + bad := []gitRef{{Name: "refs/heads/x", ID: strings.Repeat("1", 40)}} + if inv, err := r.inventoryLFS(dir, bad); err == nil || inv != nil { + t.Fatalf("inventory = %v, err = %v", inv, err) + } +} + +func TestLFSInventoryCanceledEmptyCapture(t *testing.T) { + dir := t.TempDir() + gitTest(t, dir, "init", "--bare") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + r := &replicator{ctx: ctx, timeout: time.Minute} + if inv, err := r.inventoryLFS(dir, nil); err == nil || inv != nil { + t.Fatalf("inventory = %v, err = %v", inv, err) + } +} + +func TestLFSInventoryRejectsGraftEnv(t *testing.T) { + dir := t.TempDir() + gitTest(t, dir, "init", "--bare") + t.Setenv("GIT_GRAFT_FILE", "ignored") + r := &replicator{ctx: context.Background(), timeout: time.Minute} + if _, err := r.inventoryLFS(dir, nil); err == nil || !strings.Contains(err.Error(), "GIT_GRAFT_FILE") { + t.Fatalf("err = %v", err) + } + if err := r.checkLFS(dir); err == nil || !strings.Contains(err.Error(), "GIT_GRAFT_FILE") { + t.Fatalf("checkLFS err = %v", err) + } +} + +func TestLFSInventoryRejectsShallowFile(t *testing.T) { + dir := t.TempDir() + gitTest(t, dir, "init", "--bare") + if err := os.WriteFile(filepath.Join(dir, "shallow"), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + r := &replicator{ctx: context.Background(), timeout: time.Minute} + if inv, err := r.inventoryLFS(dir, nil); err == nil || inv != nil || !strings.Contains(err.Error(), "shallow") { + t.Fatalf("inventory = %v, err = %v", inv, err) + } + if err := r.checkLFS(dir); err == nil || !strings.Contains(err.Error(), "shallow") { + t.Fatalf("checkLFS err = %v", err) + } +} diff --git a/lfs_snapshot.go b/lfs_snapshot.go new file mode 100644 index 0000000..fe36c11 --- /dev/null +++ b/lfs_snapshot.go @@ -0,0 +1,136 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// materializeRefs makes a.Dir hold exactly refs (heads and tags, by object ID) +// with every reachable object copied into its own pack, read from the local +// bare store srcGitDir. Nothing runs inside srcGitDir: its config, hooks and +// HEAD are never read, and nothing is written there. a's HEAD is left alone. +// +// Objects are borrowed through a temporary alternates entry, packed locally +// with repack -a (which includes alternate objects), then the entry is removed +// and connectivity is checked with fsck. A missing or concurrently pruned +// object makes update-ref, repack or fsck fail: the step fails closed but this +// does not protect against a non-cooperating process deleting objects; run it +// under the cache lock. On error a is in an unspecified state: Close it. +// An empty refs still checks that the auxiliary has no visible refs. +func (a *lfsAux) materializeRefs(ctx context.Context, srcGitDir string, refs []gitRef) error { + if err := ctx.Err(); err != nil { + return err + } + var in strings.Builder + seen := make(map[string]string, len(refs)) + for _, r := range refs { + if err := ctx.Err(); err != nil { + return err + } + if !validSnapshotRefName(r.Name) { + return fmt.Errorf("invalid snapshot ref name %q", r.Name) + } + if !lfsBlobIDRE.MatchString(r.ID) { // aux is sha1-only + return fmt.Errorf("invalid object id %q for %s", r.ID, r.Name) + } + if _, exists := seen[r.Name]; exists { + return fmt.Errorf("duplicate snapshot ref %s", r.Name) + } + seen[r.Name] = r.ID + fmt.Fprintf(&in, "option no-deref\ncreate %s %s\n", r.Name, r.ID) + } + // Fail closed on any pre-existing ref (any namespace, loose or packed): + // wildcard pushes would otherwise publish refs outside the snapshot. + cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "for-each-ref", "--count=1", "--format=%(refname)") // #nosec G204 -- resolved git binary, argv only + cmd.Dir, cmd.Env = a.root, a.env + if out, err := cmd.Output(); err != nil { + return fmt.Errorf("git for-each-ref: %w", err) + } else if len(strings.TrimSpace(string(out))) != 0 { + return fmt.Errorf("auxiliary repository already has refs (%s)", strings.TrimSpace(string(out))) + } + if len(refs) == 0 { + return nil + } + src, err := filepath.Abs(filepath.Join(srcGitDir, "objects")) + if err != nil { + return err + } + if fi, err := os.Stat(src); err != nil || !fi.IsDir() { + return fmt.Errorf("snapshot source objects %s: not a directory", src) + } + if strings.ContainsAny(src, "\n\r") { + return errors.New("snapshot source path contains a newline") + } + alt := filepath.Join(a.Dir, "objects", "info", "alternates") + if err := os.WriteFile(alt, []byte(src+"\n"), 0o600); err != nil { + return err + } + defer os.Remove(alt) + // One transaction over stdin: no argv limit; "create" fails if a ref exists. + cmd = exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "update-ref", "--stdin") // #nosec G204 -- resolved git binary, argv only + cmd.Dir, cmd.Env, cmd.Stdin = a.root, a.env, strings.NewReader(in.String()) + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("git update-ref: %w: %s", err, out) + } + // Broken symbolic refs are invisible until their target exists. + cmd = exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "for-each-ref", "--format=%(refname) %(objectname)") // #nosec G204 -- resolved git binary, argv only + cmd.Dir, cmd.Env = a.root, a.env + out, err := cmd.Output() + if err != nil { + return fmt.Errorf("verify snapshot refs: %w", err) + } + remaining := len(seen) + for _, line := range strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") { + name, id, ok := strings.Cut(line, " ") + if !ok || seen[name] != id || id == "" { + return fmt.Errorf("unexpected snapshot ref %q", line) + } + delete(seen, name) + remaining-- + } + if remaining != 0 { + return errors.New("snapshot refs are incomplete") + } + if err := a.run(ctx, "--git-dir="+a.Dir, "repack", "-a", "-d", "-q"); err != nil { + return err + } + if err := os.Remove(alt); err != nil { + return err + } + return a.run(ctx, "--git-dir="+a.Dir, "fsck", "--connectivity-only", "--no-dangling", "--no-progress") +} + +// validSnapshotRefName is a conservative subset of git check-ref-format, +// limited to refs/heads/ and refs/tags/. A "@" or a component ending in "." +// is valid in Git; only the whole name may not end in ".". Spaces, control +// characters and newlines stay rejected: they would break update-ref --stdin. +func validSnapshotRefName(n string) bool { + rest, ok := strings.CutPrefix(n, "refs/heads/") + if !ok { + if rest, ok = strings.CutPrefix(n, "refs/tags/"); !ok { + return false + } + } + if rest == "" || strings.Contains(n, "..") || strings.Contains(n, "@{") { + return false + } + for _, c := range n { + if c <= ' ' || c == 0x7f || strings.ContainsRune(`~^:?*[\`, c) { + return false + } + } + if strings.HasSuffix(n, ".") { + return false + } + for _, p := range strings.Split(rest, "/") { + if p == "" || strings.HasPrefix(p, ".") || strings.HasSuffix(p, ".lock") { + return false + } + } + return true +} diff --git a/lfs_snapshot_test.go b/lfs_snapshot_test.go new file mode 100644 index 0000000..4c778b8 --- /dev/null +++ b/lfs_snapshot_test.go @@ -0,0 +1,305 @@ +package main + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func snapGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", + "GIT_AUTHOR_NAME=a", "GIT_AUTHOR_EMAIL=a@a", "GIT_COMMITTER_NAME=a", "GIT_COMMITTER_EMAIL=a@a") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } + return strings.TrimSpace(string(out)) +} + +// snapSource builds a bare store with a branch, an annotated tag and annotated +// tags to a blob and a tree; returns the dir and its captured refs. +func snapSource(t *testing.T) (string, []gitRef) { + t.Helper() + work := t.TempDir() + snapGit(t, work, "init", "-q", "-b", "main", "--object-format=sha1") + must(t, os.WriteFile(filepath.Join(work, "f"), []byte("a\n"), 0o600)) + snapGit(t, work, "add", "f") + snapGit(t, work, "commit", "-qm", "c1") + snapGit(t, work, "tag", "-a", "v1", "-m", "v1") + snapGit(t, work, "tag", "-a", "blobtag", "-m", "b", snapGit(t, work, "rev-parse", "HEAD:f")) + snapGit(t, work, "tag", "-a", "treetag", "-m", "t", snapGit(t, work, "rev-parse", "HEAD^{tree}")) + snapGit(t, work, "branch", "gone") + src := filepath.Join(t.TempDir(), "src.git") + snapGit(t, work, "clone", "-q", "--bare", "--no-local", work, src) + return src, snapRefs(t, src) +} + +func snapRefs(t *testing.T, dir string) []gitRef { + t.Helper() + var refs []gitRef + for _, l := range strings.Split(snapGit(t, dir, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads", "refs/tags"), "\n") { + if id, n, ok := strings.Cut(l, " "); ok { + refs = append(refs, gitRef{Name: n, ID: id}) + } + } + return refs +} + +func snapFmt(refs []gitRef) string { + var b strings.Builder + for _, r := range refs { + b.WriteString(r.ID + " " + r.Name + "\n") + } + return b.String() +} + +func TestLFSSnapshotMaterializesExactRefs(t *testing.T) { + src, refs := snapSource(t) + a := newAux(t) + must(t, a.materializeRefs(context.Background(), src, refs)) + if got := snapFmt(snapRefs(t, a.Dir)); got != snapFmt(refs) { + t.Fatalf("refs\n%s\nwant\n%s", got, snapFmt(refs)) + } + if _, err := os.Stat(filepath.Join(a.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { + t.Fatalf("alternates left behind: %v", err) + } + if h := snapGit(t, a.Dir, "symbolic-ref", "HEAD"); h != "refs/heads/master" && h != "refs/heads/main" { + t.Fatalf("HEAD touched: %s", h) + } + for tag, typ := range map[string]string{"v1": "commit", "blobtag": "blob", "treetag": "tree"} { + if got := snapGit(t, a.Dir, "cat-file", "-t", "refs/tags/"+tag); got != "tag" { + t.Fatalf("%s is %s, want annotated tag", tag, got) + } + if got := snapGit(t, a.Dir, "cat-file", "-t", "refs/tags/"+tag+"^{}"); got != typ { + t.Fatalf("%s peels to %s want %s", tag, got, typ) + } + } + + // Mutate and GC the source: the snapshot is self-contained and unchanged. + snapGit(t, src, "update-ref", "-d", "refs/heads/gone") + snapGit(t, src, "update-ref", "-d", "refs/tags/v1") + snapGit(t, src, "update-ref", "refs/heads/later", refs[0].ID) + snapGit(t, src, "reflog", "expire", "--expire=now", "--all") + snapGit(t, src, "gc", "-q", "--prune=now") + snapGit(t, a.Dir, "fsck", "--connectivity-only", "--no-dangling") + + dst := filepath.Join(t.TempDir(), "dst.git") + snapGit(t, t.TempDir(), "init", "-q", "--bare", dst) + snapGit(t, a.Dir, "push", "-q", dst, refs[0].ID+":refs/heads/excl") + snapGit(t, a.Dir, "push", "-q", "--atomic", "--force", dst, "refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*") + got := snapRefs(t, dst) + var mirrored []gitRef + for _, r := range got { + if r.Name == "refs/heads/excl" { + if r.ID != refs[0].ID { + t.Fatal("exclusive ref changed") + } + continue + } + mirrored = append(mirrored, r) + } + if len(mirrored) == len(got) { + t.Fatal("exclusive ref lost") + } + if snapFmt(mirrored) != snapFmt(refs) { + t.Fatalf("destination\n%s\nwant\n%s", snapFmt(mirrored), snapFmt(refs)) + } +} + +func TestLFSSnapshotAtomicReject(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell hook") + } + src, refs := snapSource(t) + var c1 string + for _, r := range refs { + if r.Name == "refs/heads/main" { + c1 = r.ID + } + } + work := t.TempDir() + snapGit(t, work, "clone", "-q", src, "w") + w := filepath.Join(work, "w") + snapGit(t, w, "commit", "-q", "--allow-empty", "-m", "c2") + c2 := snapGit(t, w, "rev-parse", "HEAD") + snapGit(t, w, "push", "-q", "origin", "HEAD:refs/heads/main") + a := newAux(t) + must(t, a.materializeRefs(context.Background(), src, []gitRef{{"refs/heads/good", c2}, {"refs/heads/reject", c2}})) + + for _, atomic := range []bool{false, true} { + dst := filepath.Join(t.TempDir(), "dst.git") + snapGit(t, t.TempDir(), "init", "-q", "--bare", dst) + snapGit(t, src, "push", "-q", dst, c1+":refs/heads/good") + must(t, os.WriteFile(filepath.Join(dst, "hooks", "update"), []byte("#!/bin/sh\n[ \"$1\" = refs/heads/reject ] && exit 1\nexit 0\n"), 0o700)) + args := []string{"push", "-q", "--force", dst, "refs/heads/*:refs/heads/*"} + if atomic { + args = append(args[:1], append([]string{"--atomic"}, args[1:]...)...) + } + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = a.Dir, append(os.Environ(), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1") + if err := cmd.Run(); err == nil { + t.Fatalf("atomic=%v: push must fail", atomic) + } + want := c2 + if atomic { + want = c1 + } + if got := snapGit(t, dst, "rev-parse", "refs/heads/good"); got != want { + t.Fatalf("atomic=%v: good=%s want %s", atomic, got, want) + } + if snapGit(t, dst, "for-each-ref", "refs/heads/reject") != "" { + t.Fatalf("atomic=%v: reject created", atomic) + } + } +} + +func TestLFSSnapshotMissingObjectFailsClosed(t *testing.T) { + src, refs := snapSource(t) + // Unknown object: update-ref refuses. + a := newAux(t) + if err := a.materializeRefs(context.Background(), src, []gitRef{{"refs/heads/x", strings.Repeat("1", 40)}}); err == nil { + t.Fatal("missing tip must fail") + } + // Tip present but a reachable blob is gone: repack/fsck refuse. + loose := t.TempDir() + snapGit(t, loose, "init", "-q", "--bare", "l.git") + l := filepath.Join(loose, "l.git") + snapGit(t, src, "push", "-q", l, "refs/heads/main") + blob := snapGit(t, l, "rev-parse", "refs/heads/main:f") + // small pushes stay loose (receive.unpackLimit=100), so the blob is a single file + must(t, os.Remove(filepath.Join(l, "objects", blob[:2], blob[2:]))) + b := newAux(t) + var main string + for _, r := range refs { + if r.Name == "refs/heads/main" { + main = r.ID + } + } + if err := b.materializeRefs(context.Background(), l, []gitRef{{"refs/heads/main", main}}); err == nil { + t.Fatal("missing reachable object must fail") + } + if _, err := os.Stat(filepath.Join(b.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { + t.Fatalf("alternates left after failure: %v", err) + } +} + +func TestLFSSnapshotRejectsBadInputAndEmpty(t *testing.T) { + a := newAux(t) + id := strings.Repeat("a", 40) + bad := []gitRef{ + {"HEAD", id}, {"refs/remotes/x", id}, {"refs/heads/", id}, {"refs/heads/a..b", id}, + {"refs/heads/a b", id}, {"refs/heads/.x", id}, {"refs/heads/x.lock", id}, {"refs/heads/x/", id}, {"refs/heads/x.", id}, {"refs/heads//x", id}, {"refs/heads/a\x7fb", id}, {"refs/heads/a\tb", id}, {"refs/heads/a\x00b", id}, + {"refs/tags/a@{1}", id}, {"refs/heads/a\nb", id}, {"refs/heads/x", strings.Repeat("a", 64)}, + {"refs/heads/x", "HEAD"}, {"refs/heads/x", strings.ToUpper(id)}, + } + for _, r := range bad { + if err := a.materializeRefs(context.Background(), "/nonexistent", []gitRef{r}); err == nil { + t.Fatalf("accepted %q", r) + } + } + if err := a.materializeRefs(context.Background(), "/nonexistent", []gitRef{{"refs/heads/x", id}, {"refs/heads/x", id}}); err == nil { + t.Fatal("accepted duplicate") + } + // Empty: no-op even with a bogus source. + must(t, a.materializeRefs(context.Background(), "/nonexistent", nil)) + if snapGit(t, a.Dir, "for-each-ref") != "" { + t.Fatal("empty snapshot created refs") + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + src, refs := snapSource(t) + if err := a.materializeRefs(ctx, src, refs); err == nil { + t.Fatal("cancelled context must fail") + } + if snapGit(t, a.Dir, "for-each-ref") != "" { + t.Fatal("cancelled snapshot created refs") + } +} + +func TestLFSSnapshotValidatorMatchesGit(t *testing.T) { + names := []string{"@", "foo./bar", "a.b", "a/b/c", "é", "-x", "a@b", "x.lock", "a/.b", "a/b.lock/c", "a..b", "a b", "x.", "a//b", "a/", "a@{b", "a~", "a^", "a:", "a?", "a*", "a[", `a\b`, "a\x7f", "a\tb", "/a"} + for _, pre := range []string{"refs/heads/", "refs/tags/"} { + for _, n := range names { + full := pre + n + err := exec.Command("git", "check-ref-format", full).Run() + if got := validSnapshotRefName(full); got != (err == nil) { + t.Errorf("%q: validator=%v git valid=%v", full, got, err == nil) + } + } + } + // Valid-but-unusual names really round-trip through update-ref --stdin. + src, refs := snapSource(t) + id := refs[0].ID + a := newAux(t) + in := []gitRef{{"refs/heads/@", id}, {"refs/heads/foo./bar", id}, {"refs/tags/@", id}, {"refs/tags/foo./bar", id}} + must(t, a.materializeRefs(context.Background(), src, in)) + got := map[string]string{} + for _, r := range snapRefs(t, a.Dir) { + got[r.Name] = r.ID + } + if len(got) != len(in) { + t.Fatalf("refs %v", got) + } + for _, r := range in { + if got[r.Name] != r.ID { + t.Fatalf("missing %s", r.Name) + } + } +} + +func TestLFSSnapshotFailsClosedOnExistingRefs(t *testing.T) { + src, refs := snapSource(t) + for _, packed := range []bool{false, true} { + for _, ref := range []string{"refs/heads/old", "refs/notes/x", "refs/foo/bar"} { + for name, mat := range map[string][]gitRef{"empty": nil, "refs": refs} { + a := newAux(t) + tree := snapGit(t, a.Dir, "mktree") // empty stdin: empty tree + c := snapGit(t, a.Dir, "commit-tree", "-m", "old", tree) + snapGit(t, a.Dir, "update-ref", ref, c) + if packed { + snapGit(t, a.Dir, "pack-refs", "--all") + } + before := snapGit(t, a.Dir, "for-each-ref") + if err := a.materializeRefs(context.Background(), src, mat); err == nil { + t.Fatalf("%s/%s packed=%v: must fail", name, ref, packed) + } + if after := snapGit(t, a.Dir, "for-each-ref"); after != before { + t.Fatalf("%s/%s: refs changed\n%s\n%s", name, ref, before, after) + } + if _, err := os.Stat(filepath.Join(a.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { + t.Fatalf("alternates left: %v", err) + } + } + } + } +} + +func TestLFSSnapshotRejectsDanglingSymbolicRefs(t *testing.T) { + src, refs := snapSource(t) + for _, ref := range []string{"refs/heads/unexpected", "refs/heads/main"} { + t.Run(ref, func(t *testing.T) { + a := newAux(t) + target := "refs/heads/main" + if ref == target { + target = "refs/heads/missing" + } + snapGit(t, a.Dir, "symbolic-ref", ref, target) + if got := snapGit(t, a.Dir, "for-each-ref"); got != "" { + t.Fatalf("dangling symbolic ref unexpectedly visible: %s", got) + } + if err := a.materializeRefs(context.Background(), src, refs); err == nil { + t.Fatal("snapshot accepted a dangling symbolic ref") + } + if _, err := os.Stat(filepath.Join(a.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { + t.Fatalf("alternates left after failure: %v", err) + } + }) + } +} diff --git a/lfs_transfer.go b/lfs_transfer.go new file mode 100644 index 0000000..7b9f243 --- /dev/null +++ b/lfs_transfer.go @@ -0,0 +1,74 @@ +package main + +import ( + "context" + "fmt" + "path/filepath" + "strconv" + "strings" +) + +// lfsMinVersion is the oldest git-lfs version this code has been tested +// against (3.8.1); older versions are rejected rather than assumed compatible. +var lfsMinVersion = [3]int{3, 8, 1} + +// parseLFSVersion reads the leading "git-lfs/X.Y.Z" token of `git lfs version`. +func parseLFSVersion(out string) ([3]int, error) { + var v [3]int + fields := strings.Fields(out) + if len(fields) == 0 || !strings.HasPrefix(fields[0], "git-lfs/") { + return v, fmt.Errorf("unexpected git-lfs version output %q", out) + } + parts := strings.Split(strings.TrimPrefix(fields[0], "git-lfs/"), ".") + if len(parts) != 3 { + return v, fmt.Errorf("unexpected git-lfs version %q", fields[0]) + } + for i, p := range parts { + n, err := strconv.Atoi(p) + if err != nil { + return v, fmt.Errorf("unexpected git-lfs version %q", fields[0]) + } + v[i] = n + } + return v, nil +} + +// requireLFS enforces the conditional dependency: only reached when LFS is +// confirmed, it fails if git-lfs is missing or older than the tested version. +func (r *replicator) requireLFS(ctx context.Context, a *lfsAux, s side, ownerRepo string) error { + ctx, cancel := context.WithTimeout(ctx, r.timeout) + defer cancel() + cmd := r.lfsCmd(ctx, a, s, ownerRepo, "lfs", "version") + out, err := cmd.Output() + if err != nil { + return fmt.Errorf("git-lfs is required to replicate a repository with LFS objects: %w", err) + } + v, err := parseLFSVersion(string(out)) + if err != nil { + return err + } + if v[0] < lfsMinVersion[0] || (v[0] == lfsMinVersion[0] && (v[1] < lfsMinVersion[1] || (v[1] == lfsMinVersion[1] && v[2] < lfsMinVersion[2]))) { + return fmt.Errorf("git-lfs %d.%d.%d is too old; %d.%d.%d or newer is required", v[0], v[1], v[2], lfsMinVersion[0], lfsMinVersion[1], lfsMinVersion[2]) + } + return nil +} + +// transferLFS downloads every inventory object from the source, verifies its +// size and SHA-256, then uploads to the destination, all before any ref push. +func (r *replicator) transferLFS(ctx context.Context, a *lfsAux, source, target string, refs []gitRef, inv lfsInventory) error { + var names strings.Builder + for _, ref := range refs { + names.WriteString(ref.Name + "\n") + } + refsIn := names.String() + if err := r.lfsRunIn(ctx, a, r.source, source, refsIn, "lfs", "fetch", "--all", "--stdin"); err != nil { + return fmt.Errorf("download Git LFS objects from source: %w", err) + } + if err := verifyLFSObjects(ctx, filepath.Join(a.Dir, "lfs"), inv); err != nil { + return fmt.Errorf("verify downloaded Git LFS objects: %w", err) + } + if err := r.lfsRunIn(ctx, a, r.target, target, refsIn, "lfs", "push", "--all", "--stdin", "replicate-target"); err != nil { + return fmt.Errorf("upload Git LFS objects to target: %w", err) + } + return nil +} diff --git a/lfs_transfer_test.go b/lfs_transfer_test.go new file mode 100644 index 0000000..1676be1 --- /dev/null +++ b/lfs_transfer_test.go @@ -0,0 +1,29 @@ +package main + +import "testing" + +func TestLFSParseVersion(t *testing.T) { + cases := map[string][3]int{ + "git-lfs/3.8.1 (GitHub; darwin arm64; go 1.27.3; git a662a6db)": {3, 8, 1}, + "git-lfs/3.8.1\n": {3, 8, 1}, + "git-lfs/2.11.0 (GitHub; linux amd64; go 1.15)": {2, 11, 0}, + } + for in, want := range cases { + got, err := parseLFSVersion(in) + if err != nil || got != want { + t.Fatalf("parseLFSVersion(%q) = %v, %v; want %v", in, got, err, want) + } + } + for _, bad := range []string{ + "", + "lfs/3.8.1", + "git-lfs/3.8", + "git-lfs/3.8.x", + "git-lfs/version", + "3.8.1", + } { + if _, err := parseLFSVersion(bad); err == nil { + t.Fatalf("parseLFSVersion(%q) accepted", bad) + } + } +} diff --git a/replicate.go b/replicate.go index 4e572fe..64d1a9f 100644 --- a/replicate.go +++ b/replicate.go @@ -419,10 +419,12 @@ func (r *replicator) syncGit(source, target string) error { if err := os.MkdirAll(dir, 0700); err != nil { return fmt.Errorf("create cache directory: %w", err) } - // Share source objects across destinations without persisting credentials. + // The lock still lives at the source-keyed path so concurrent replications of + // the same source coordinate. The incremental cache itself is no longer used: + // the transfer runs in an ephemeral bare with isolated config, so a hostile + // or stale cache cannot steer the fetch, scan or push. key := fmt.Sprintf("%x", sha256.Sum256([]byte(gitRemote(source)))) - gitDir := filepath.Join(dir, key+".git") - lock, err := lockCache(gitDir + ".lock") + lock, err := lockCache(filepath.Join(dir, key+".git.lock")) if err != nil { return err } @@ -431,38 +433,55 @@ func (r *replicator) syncGit(source, target string) error { locked.cacheLock = lock r = &locked - if err := os.MkdirAll(gitDir, 0700); err != nil { - return fmt.Errorf("create source cache: %w", err) - } - // init is idempotent, including after an interrupted first initialization. - // Pin SHA-1 like GitHub, so a local sha256 default cannot break the fetch. - if err := r.command("", r.source, "git", "init", "--bare", "--quiet", "--object-format=sha1", gitDir); err != nil { - return fmt.Errorf("initialize source cache: %w", err) - } - if err := r.command(gitDir, r.target, "git", "config", "--local", - "remote.replicate-target.url", gitRemote(target)); err != nil { - return fmt.Errorf("configure destination remote: %w", err) + initCtx, cancel := context.WithTimeout(r.ctx, r.timeout) + aux, err := newLFSAux(initCtx) + cancel() + if err != nil { + return fmt.Errorf("create ephemeral bare: %w", err) } + defer aux.Close() - fmt.Fprintf(os.Stderr, " Fetching branches and tags from %s (cache: %s)...\n", source, gitDir) - // Prune stale source refs locally so deleted source refs are never pushed - // back. The destination push does not prune destination-only refs. + fmt.Fprintf(os.Stderr, " Fetching branches and tags from %s...\n", source) // Fetch must succeed on every run; never push a stale cache after failure. - // Not --atomic: a rename like release -> release/v2 cannot delete and create - // in one transaction, and that failure would persist in the shared cache. - if err := r.command(gitDir, r.source, "git", "fetch", "--prune", "--no-tags", + if err := r.lfsRun(r.ctx, aux, r.source, source, "fetch", "--prune", "--no-tags", gitRemote(source), "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"); err != nil { return fmt.Errorf("fetch source: %w", err) } - if err := r.checkLFS(gitDir); err != nil { + if err := aux.run(r.ctx, "--git-dir="+aux.Dir, "config", "remote.replicate-target.url", gitRemote(target)); err != nil { + return fmt.Errorf("configure destination remote: %w", err) + } + + if err := r.guardLFSScan(aux.Dir); err != nil { + return err + } + refs, err := r.captureRefs(aux.Dir) + if err != nil { + return err + } + inv, err := r.inventoryLFS(aux.Dir, refs) + if err != nil { return err } + if len(inv) > 0 { + if err := r.requireLFS(r.ctx, aux, r.source, source); err != nil { + return err + } + if err := aux.pointHEADAbsent(r.ctx, refs); err != nil { + return err + } + if r.dryRun { + fmt.Fprintf(os.Stderr, " Would transfer %d Git LFS objects from %s to %s\n", len(inv), source, target) + } else if err := r.transferLFS(r.ctx, aux, source, target, refs, inv); err != nil { + return err + } + } + r.disableActions(target) fmt.Fprintf(os.Stderr, " Pushing branches and tags to %s...\n", target) - return r.pushRefs(gitDir) + return r.pushRefs(aux.Dir) } func (r *replicator) pushRefs(gitDir string) error { diff --git a/safeguards.go b/safeguards.go index bd87ab5..4d96209 100644 --- a/safeguards.go +++ b/safeguards.go @@ -10,6 +10,8 @@ import ( "net/http" "os" "os/exec" + "path/filepath" + "regexp" "strconv" "strings" "time" @@ -104,13 +106,146 @@ func isLFSPointer(data []byte) bool { return false } +var errLFSBlocked = errors.New("Git LFS pointers detected; LFS objects are not supported, so replication stopped before destination changes") + +// Git ancestry and repository-redirect overrides could make the scan read a +// truncated or different history than the refs actually reference. Rejecting +// is safer than silently stripping: a caller who needs these should get a +// clear failure, not an incomplete LFS decision. Replacements are handled +// separately with --no-replace-objects. +var gitAncestryOverrideVars = []string{ + "GIT_DIR", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_INDEX_FILE", "GIT_WORK_TREE", + "GIT_NAMESPACE", "GIT_GRAFT_FILE", "GIT_SHALLOW_FILE", "GIT_REPLACE_REF_BASE", +} + +func rejectGitAncestryOverrides() error { + for _, k := range gitAncestryOverrideVars { + if v, ok := os.LookupEnv(k); ok && v != "" { + return fmt.Errorf("refusing to scan for Git LFS with %s set in the environment", k) + } + } + return nil +} + +// verifyNoHistoryTruncation rejects cache state that could prune commit +// ancestry: a physical shallow or grafts file, or a commondir redirect. A +// stat error is an error, not proof of absence; an existing entry (even a +// symlink or empty file) means the cache is not trustworthy to scan. +func verifyNoHistoryTruncation(dir string) error { + for _, rel := range []string{"shallow", "info/grafts", "commondir"} { + p := filepath.Join(dir, rel) + if _, err := os.Lstat(p); err == nil { + return fmt.Errorf("refusing to scan for Git LFS: cache has %s, which may truncate history", rel) + } else if !os.IsNotExist(err) { + return fmt.Errorf("inspect cache %s: %w", rel, err) + } + } + return nil +} + +// guardLFSScan is the entry guard for any LFS history traversal over the cache: +// cancellation, inherited overrides and physical truncation all fail closed. +func (r *replicator) guardLFSScan(dir string) error { + if err := r.ctx.Err(); err != nil { + return err + } + if err := rejectGitAncestryOverrides(); err != nil { + return err + } + return verifyNoHistoryTruncation(dir) +} + // Detect LFS pointers reachable from the branches and tags being pushed, // including historical versions, but excluding obsolete cached objects. +// Any line naming a known version alias blocks, confirmed pointer or not. func (r *replicator) checkLFS(dir string) error { + if err := r.guardLFSScan(dir); err != nil { + return err + } + return r.scanLFSBlobs(dir, []string{"--branches", "--tags"}, nil, func(_ string, _ int64, prefix []byte) error { + if isLFSPointer(prefix) { + return errLFSBlocked + } + return nil + }) +} + +// gitRef is a captured refs/heads or refs/tags entry; ID may name a commit, an +// annotated tag, or a tag pointing at a blob or tree. +type gitRef struct{ Name, ID string } + +var gitObjectIDRE = regexp.MustCompile(`\A([0-9a-f]{40}|[0-9a-f]{64})\z`) + +// captureRefs records the names and object IDs of refs/heads and refs/tags once. +// Call it under the caller's cache lock; later ref changes do not affect it. +func (r *replicator) captureRefs(dir string) ([]gitRef, error) { + ctx, cancel := context.WithTimeout(r.ctx, r.timeout) + defer cancel() + cmd := r.gitCommand(ctx, "", "git", "--no-replace-objects", "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads", "refs/tags") + cmd.Dir = dir + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("capture refs: %w", err) + } + var refs []gitRef + for _, line := range strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") { + if line == "" { + continue + } + id, name, ok := strings.Cut(line, " ") + if !ok || !gitObjectIDRE.MatchString(id) || name == "" { + return nil, errors.New("invalid git for-each-ref output") + } + refs = append(refs, gitRef{Name: name, ID: id}) + } + return refs, nil +} + +// inventoryLFS maps OID to size for every pointer reachable from the captured +// refs only (later ref changes are ignored). An empty capture is an empty +// inventory, never "all refs". It fails closed: the first ambiguous candidate +// or conflicting size aborts with an error naming the blob, and no inventory is +// returned. A valid inventory visits every blob. +func (r *replicator) inventoryLFS(dir string, refs []gitRef) (lfsInventory, error) { + if err := r.guardLFSScan(dir); err != nil { + return nil, err + } + inv := lfsInventory{} + if len(refs) == 0 { + return inv, nil + } + var tips strings.Builder // via stdin: no argv limit + for _, ref := range refs { + tips.WriteString(ref.ID + "\n") + } + err := r.scanLFSBlobs(dir, []string{"--stdin"}, strings.NewReader(tips.String()), func(blobID string, size int64, prefix []byte) error { + p, found, blocked := classifyLFSBlob(prefix, size) + if blocked != "" { + return fmt.Errorf("Git LFS blob %s: %s", blobID, blocked) + } + if found { + if err := inv.add(p); err != nil { + return fmt.Errorf("Git LFS blob %s: %w", blobID, err) + } + } + return nil + }) + if err != nil { + return nil, err + } + return inv, nil +} + +// scanLFSBlobs streams every non-empty blob reachable from the rev-list +// selection (flags, optionally with stdin revisions) and calls visit with its object ID, size and first min(size,1024) bytes +// (valid only during the call). A visit error aborts the scan. +func (r *replicator) scanLFSBlobs(dir string, revs []string, revsIn io.Reader, visit func(blobID string, size int64, prefix []byte) error) error { ctx, cancel := context.WithTimeout(r.ctx, r.timeout) defer cancel() // --no-replace-objects: refs/replace in the cache must not hide what gets pushed. - reachable := r.gitCommand(ctx, "", "git", "--no-replace-objects", "rev-list", "--objects", "--no-object-names", "--branches", "--tags") + reachable := r.gitCommand(ctx, "", "git", append([]string{"--no-replace-objects", "rev-list", "--objects", "--no-object-names"}, revs...)...) + reachable.Stdin = revsIn check := r.gitCommand(ctx, "", "git", "--no-replace-objects", "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)") read := r.gitCommand(ctx, "", "git", "--no-replace-objects", "cat-file", "--batch") for _, cmd := range []*exec.Cmd{reachable, check, read} { @@ -184,8 +319,8 @@ func (r *replicator) checkLFS(dir string) error { if _, err := io.ReadFull(reader, prefix[:n]); err != nil { return fmt.Errorf("read Git object: %w", err) } - if isLFSPointer(prefix[:n]) { - return errors.New("Git LFS pointers detected; LFS objects are not supported, so replication stopped before destination changes") + if err := visit(fields[0], size, prefix[:n]); err != nil { + return err } if _, err := io.CopyN(io.Discard, reader, size-n); err != nil { return fmt.Errorf("read Git object: %w", err) From 48fda0694b925f5a00bf26016100b66c40d39cab Mon Sep 17 00:00:00 2001 From: Victor M Varela Date: Fri, 30 Oct 2026 14:12:47 +0100 Subject: [PATCH 2/5] fix: isolate final push and harden LFS transfer edge cases Address review findings on the canonical LFS transfer: - pushRefs now publishes through the isolated lfsRun environment (pinned endpoints, side token, cache lock), so inherited config cannot redirect it. - pointHEADAbsent uses refs/gh-replicate/ (outside fetched namespaces) and verifies HEAD does not resolve, so a committed .lfsconfig is never read. - cancellation kills the whole process group on Unix, not just the direct git, so a git-lfs descendant cannot outlive the ephemeral bare. - lfsSideEnv preserves lowercase proxy variables as well as uppercase. - ci.yml filter references the renamed TestSyncGitLifecycle. --- .github/workflows/ci.yml | 2 +- lfs_auxiliary.go | 29 +++++++++++++++--------- lfs_auxiliary_test.go | 12 +++++----- lfs_integration_test.go | 2 +- lfs_proc_test.go | 45 ++++++++++++++++++++++++++++++++++++ lfs_proc_unix.go | 23 +++++++++++++++++++ lfs_proc_windows.go | 15 ++++++++++++ replicate.go | 10 ++++---- robustness_test.go | 49 ++++++++++++++++++++++++++++++++++++---- 9 files changed, 159 insertions(+), 28 deletions(-) create mode 100644 lfs_proc_test.go create mode 100644 lfs_proc_unix.go create mode 100644 lfs_proc_windows.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4bbe148..934bb0a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,4 +65,4 @@ jobs: with: go-version: '1.27.3' - name: Test cache and OS locking - run: go test -timeout 3m -run 'Test(CacheLock.*|Journal.*|SyncGitCacheLifecycle|SyncGitNewObjectsAndSecondTarget|LFS.*)$' ./... + run: go test -timeout 3m -run 'Test(CacheLock.*|Journal.*|SyncGitLifecycle|SyncGitNewObjectsAndSecondTarget|LFS.*)$' ./... diff --git a/lfs_auxiliary.go b/lfs_auxiliary.go index 50681a4..1e0c4a8 100644 --- a/lfs_auxiliary.go +++ b/lfs_auxiliary.go @@ -185,17 +185,22 @@ func parseLFSMarks(data string, oids []string) (map[string]string, error) { var lfsBlobIDRE = regexp.MustCompile(`\A[0-9a-f]{40}\z`) // pointHEADAbsent sets HEAD to a ref guaranteed absent from the snapshot, so -// git-lfs cannot read a .lfsconfig committed in the replicated history. -func (a *lfsAux) pointHEADAbsent(ctx context.Context, refs []gitRef) error { - name := "refs/heads/gh-replicate-no-lfsconfig" - seen := make(map[string]bool, len(refs)) - for _, ref := range refs { - seen[ref.Name] = true +// git-lfs cannot read a .lfsconfig committed in the replicated history. The +// namespace refs/gh-replicate/ is outside refs/heads and refs/tags (the only +// namespaces the fetch writes), so it cannot collide with a replicated branch +// on a case-insensitive filesystem. +func (a *lfsAux) pointHEADAbsent(ctx context.Context) error { + const absent = "refs/gh-replicate/no-lfsconfig" + if err := a.run(ctx, "--git-dir="+a.Dir, "symbolic-ref", "HEAD", absent); err != nil { + return err } - for seen[name] { - name += "_" + // Fail closed if HEAD unexpectedly resolves to a commit. + cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "rev-parse", "--verify", "HEAD") // #nosec G204 -- resolved git binary, argv only + cmd.Dir, cmd.Env = a.root, a.env + if err := cmd.Run(); err == nil { + return errors.New("ephemeral HEAD resolves; refusing to run LFS") } - return a.run(ctx, "--git-dir="+a.Dir, "symbolic-ref", "HEAD", name) + return nil } // lfsEndpoint is the GitHub LFS API URL for a repo's HTTPS remote. @@ -221,7 +226,9 @@ func lfsSideEnv(root, token, path string) []string { if token != "" { env = append(env, "GH_TOKEN="+token) } - for _, k := range []string{"HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY", "ALL_PROXY", "GIT_SSL_CAINFO", "SSL_CERT_FILE"} { + // Preserve both spellings: proxies conventionally honor lowercase, and the + // previous gitEnv inherited everything, so dropping one would regress. + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy", "ALL_PROXY", "all_proxy", "GIT_SSL_CAINFO", "SSL_CERT_FILE"} { if v := os.Getenv(k); v != "" { env = append(env, k+"="+v) } @@ -246,7 +253,7 @@ func (r *replicator) lfsCmd(ctx context.Context, a *lfsAux, s side, ownerRepo st full := append([]string{"-c", "credential.helper=", "-c", "credential.https://github.com.helper=!gh auth git-credential", "-c", "lfs.url=" + lfsEndpoint(ownerRepo), "-c", "lfs.pushurl=" + lfsEndpoint(ownerRepo), "-c", "lfs.standalonetransferagent=" + lfsStandaloneAgent}, args...) - cmd := exec.CommandContext(ctx, a.git, full...) // #nosec G204 -- resolved git binary, argv only + cmd := newLFSCmd(ctx, a.git, full...) // #nosec G204 -- resolved git binary, argv only cmd.Dir = a.Dir cmd.Env = lfsSideEnv(a.root, s.token, os.Getenv("PATH")) if r.cacheLock != nil { diff --git a/lfs_auxiliary_test.go b/lfs_auxiliary_test.go index 970495d..36002e4 100644 --- a/lfs_auxiliary_test.go +++ b/lfs_auxiliary_test.go @@ -301,13 +301,13 @@ func TestLFSEndpoint(t *testing.T) { func TestLFSAuxPointHEADAbsent(t *testing.T) { a := newAux(t) - refs := []gitRef{{Name: "refs/heads/gh-replicate-no-lfsconfig", ID: strings.Repeat("1", 40)}} - must(t, a.pointHEADAbsent(context.Background(), refs)) - // The collision guard must pick a name not present in the snapshot. - if got := gitTest(t, a.Dir, "--git-dir="+a.Dir, "symbolic-ref", "HEAD"); got != "refs/heads/gh-replicate-no-lfsconfig_" { + must(t, a.pointHEADAbsent(context.Background())) + // HEAD points outside the refs the fetch writes, and does not resolve. + if got := gitTest(t, a.Dir, "--git-dir="+a.Dir, "symbolic-ref", "HEAD"); got != "refs/gh-replicate/no-lfsconfig" { t.Fatalf("HEAD = %q", got) } - if gitTest(t, a.Dir, "--git-dir="+a.Dir, "for-each-ref", "--format=%(refname)") != "" { - t.Fatalf("absent ref was materialized") + cmd := exec.Command("git", "--git-dir="+a.Dir, "rev-parse", "--verify", "HEAD") + if err := cmd.Run(); err == nil { + t.Fatal("absent HEAD unexpectedly resolves") } } diff --git a/lfs_integration_test.go b/lfs_integration_test.go index a885053..9a7f396 100644 --- a/lfs_integration_test.go +++ b/lfs_integration_test.go @@ -199,7 +199,7 @@ func TestLFSIntegrationTransfer(t *testing.T) { if len(inv) != 2 { t.Fatalf("inventory has %d objects, want 2", len(inv)) } - must(t, a.pointHEADAbsent(context.Background(), refs)) + must(t, a.pointHEADAbsent(context.Background())) must(t, r.transferLFS(context.Background(), a, "src", "dst", refs, inv)) diff --git a/lfs_proc_test.go b/lfs_proc_test.go new file mode 100644 index 0000000..96fb1ab --- /dev/null +++ b/lfs_proc_test.go @@ -0,0 +1,45 @@ +//go:build !windows + +package main + +import ( + "context" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func TestLFSCmdCancelKillsProcessGroup(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + pidfile := filepath.Join(t.TempDir(), "child.pid") + cmd := newLFSCmd(ctx, "sh", "-c", "sleep 30 & echo $! > "+pidfile+"; wait") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + var pid int + for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); { + if b, err := os.ReadFile(pidfile); err == nil && len(b) > 0 { + if p, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && p > 0 { + pid = p + break + } + } + time.Sleep(10 * time.Millisecond) + } + if pid <= 0 { + t.Fatal("child pid never recorded") + } + cancel() + if err := cmd.Wait(); err == nil { + t.Fatal("expected cancellation error") + } + // SIGKILL to the process group leaves no descendant behind. + time.Sleep(100 * time.Millisecond) + if err := syscall.Kill(pid, 0); err == nil || err != syscall.ESRCH { + t.Fatalf("child %d still alive (err=%v)", pid, err) + } +} diff --git a/lfs_proc_unix.go b/lfs_proc_unix.go new file mode 100644 index 0000000..efcf1bb --- /dev/null +++ b/lfs_proc_unix.go @@ -0,0 +1,23 @@ +//go:build !windows + +package main + +import ( + "context" + "os/exec" + "syscall" +) + +// newLFSCmd starts the command in its own process group so a cancellation kills +// the whole tree, including git-lfs descendants that hold the cache lock. +func newLFSCmd(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, name, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + if cmd.Process == nil { + return nil + } + return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } + return cmd +} diff --git a/lfs_proc_windows.go b/lfs_proc_windows.go new file mode 100644 index 0000000..ef5d191 --- /dev/null +++ b/lfs_proc_windows.go @@ -0,0 +1,15 @@ +//go:build windows + +package main + +import ( + "context" + "os/exec" +) + +// newLFSCmd on Windows kills only the direct child. +// shortcut: git-lfs descendants may survive a cancellation on Windows; add a +// Job Object before enabling LFS transfer there. +func newLFSCmd(ctx context.Context, name string, args ...string) *exec.Cmd { + return exec.CommandContext(ctx, name, args...) +} diff --git a/replicate.go b/replicate.go index 64d1a9f..a4cac82 100644 --- a/replicate.go +++ b/replicate.go @@ -469,7 +469,7 @@ func (r *replicator) syncGit(source, target string) error { if err := r.requireLFS(r.ctx, aux, r.source, source); err != nil { return err } - if err := aux.pointHEADAbsent(r.ctx, refs); err != nil { + if err := aux.pointHEADAbsent(r.ctx); err != nil { return err } if r.dryRun { @@ -481,16 +481,18 @@ func (r *replicator) syncGit(source, target string) error { r.disableActions(target) fmt.Fprintf(os.Stderr, " Pushing branches and tags to %s...\n", target) - return r.pushRefs(aux.Dir) + return r.pushRefs(aux, target) } -func (r *replicator) pushRefs(gitDir string) error { +// pushRefs publishes the snapshot with the same isolated per-side environment +// as the LFS transfer, so inherited config or env cannot redirect the push. +func (r *replicator) pushRefs(a *lfsAux, target string) error { args := []string{"push", "--atomic", "--force"} if r.dryRun { args = append(args, "--dry-run") } args = append(args, "replicate-target", "refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*") - if err := r.command(gitDir, r.target, "git", args...); err != nil { + if err := r.lfsRun(r.ctx, a, r.target, target, args...); err != nil { return fmt.Errorf("push refs: %w", err) } return nil diff --git a/robustness_test.go b/robustness_test.go index cf7e038..2426f71 100644 --- a/robustness_test.go +++ b/robustness_test.go @@ -399,9 +399,18 @@ func TestAtomicPushAndDryRun(t *testing.T) { first := gitTest(t, src, "rev-parse", "HEAD") gitTest(t, src, "branch", "a") gitTest(t, src, "branch", "b") - gitTest(t, src, "remote", "add", "replicate-target", dst) + + // The push publishes a fetched snapshot, mirroring syncGit's ephemeral bare. + aux := newAux(t) + gitTest(t, src, "--git-dir="+aux.Dir, "config", "remote.replicate-target.url", dst) + syncAux := func() { + t.Helper() + gitTest(t, src, "--git-dir="+aux.Dir, "fetch", src, "refs/heads/*:refs/heads/*") + } + syncAux() + r := &replicator{ctx: context.Background(), timeout: time.Minute} - if err := r.pushRefs(src); err != nil { + if err := r.pushRefs(aux, sourceRepo); err != nil { t.Fatal(err) } gitTest(t, dst, "update-ref", "refs/heads/destination-only", first) @@ -409,8 +418,9 @@ func TestAtomicPushAndDryRun(t *testing.T) { second := gitTest(t, src, "rev-parse", "HEAD") gitTest(t, src, "branch", "-f", "a", second) gitTest(t, src, "branch", "-f", "b", second) + syncAux() r.dryRun = true - if err := r.pushRefs(src); err != nil { + if err := r.pushRefs(aux, sourceRepo); err != nil { t.Fatal(err) } if got := gitTest(t, dst, "rev-parse", "a"); got != first { @@ -421,7 +431,7 @@ func TestAtomicPushAndDryRun(t *testing.T) { if err := os.WriteFile(hook, []byte("#!/bin/sh\n[ \"$1\" != refs/heads/b ]\n"), 0755); err != nil { t.Fatal(err) } - if err := r.pushRefs(src); err == nil { + if err := r.pushRefs(aux, sourceRepo); err == nil { t.Fatal("expected rejected push") } if got := gitTest(t, dst, "rev-parse", "a"); got != first { @@ -430,7 +440,7 @@ func TestAtomicPushAndDryRun(t *testing.T) { if err := os.Remove(hook); err != nil { t.Fatal(err) } - if err := r.pushRefs(src); err != nil { + if err := r.pushRefs(aux, sourceRepo); err != nil { t.Fatal(err) } if got := gitTest(t, dst, "rev-parse", "a"); got != second { @@ -441,6 +451,35 @@ func TestAtomicPushAndDryRun(t *testing.T) { } } +func TestAtomicPushIgnoresInheritedConfig(t *testing.T) { + src, dst := t.TempDir(), t.TempDir() + gitTest(t, src, "init") + gitTest(t, dst, "init", "--bare") + gitTest(t, src, "config", "user.name", "Test") + gitTest(t, src, "config", "user.email", "test@example.com") + gitTest(t, src, "commit", "--allow-empty", "-m", "first") + first := gitTest(t, src, "rev-parse", "HEAD") + gitTest(t, src, "branch", "a") + + aux := newAux(t) + gitTest(t, src, "--git-dir="+aux.Dir, "config", "remote.replicate-target.url", dst) + gitTest(t, src, "--git-dir="+aux.Dir, "fetch", src, "refs/heads/*:refs/heads/*") + + // An inherited pushurl override must be ignored: the push has to go to the + // configured destination, not wherever the parent environment points. + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_CONFIG_KEY_0", "remote.replicate-target.pushurl") + t.Setenv("GIT_CONFIG_VALUE_0", filepath.Join(t.TempDir(), "wrong.git")) + + r := &replicator{ctx: context.Background(), timeout: time.Minute} + if err := r.pushRefs(aux, sourceRepo); err != nil { + t.Fatalf("isolated push failed: %v", err) + } + if got := gitTest(t, dst, "rev-parse", "a"); got != first { + t.Fatalf("destination did not receive the snapshot: %q != %q", got, first) + } +} + func TestCorruptDownloadPreservesExistingAsset(t *testing.T) { writes := 0 r := fakeAPI(t, func(w http.ResponseWriter, req *http.Request) { From 7f510da9be74a1553cc8d9df9c0554830c573f8a Mon Sep 17 00:00:00 2001 From: Victor M Varela Date: Fri, 30 Oct 2026 14:24:31 +0100 Subject: [PATCH 3/5] refactor: remove dead LFS snapshot and pointer-seeding code --- lfs_auxiliary.go | 93 +----------- lfs_auxiliary_test.go | 119 ---------------- lfs_integration_test.go | 9 +- lfs_snapshot.go | 136 ------------------ lfs_snapshot_test.go | 305 ---------------------------------------- 5 files changed, 10 insertions(+), 652 deletions(-) delete mode 100644 lfs_snapshot.go delete mode 100644 lfs_snapshot_test.go diff --git a/lfs_auxiliary.go b/lfs_auxiliary.go index 1e0c4a8..91c36d7 100644 --- a/lfs_auxiliary.go +++ b/lfs_auxiliary.go @@ -1,17 +1,13 @@ package main import ( - "bytes" "context" "errors" "fmt" "os" "os/exec" "path/filepath" - "regexp" "runtime" - "sort" - "strconv" "strings" ) @@ -24,8 +20,9 @@ type lfsAux struct { git string } -// Env is built from scratch: no inherited GIT_*, PATH, HOME or tokens. -// shortcut: no PATH, so git helpers/git-lfs are not found; add when transfers are wired. +// lfsAuxEnv is the scratch environment for a.run, which only invokes local git +// commands (init, config, symbolic-ref) and so needs no PATH. The transfer +// commands run through lfsSideEnv instead. func lfsAuxEnv(root string) []string { env := []string{ "HOME=" + root, "USERPROFILE=" + root, "XDG_CONFIG_HOME=" + filepath.Join(root, "xdg"), @@ -100,90 +97,6 @@ func (a *lfsAux) Close() error { return err } -// lfsCanonicalPointer is the exact pointer text git-lfs writes (spec v1, no extensions). -func lfsCanonicalPointer(oid string, size int64) string { - return fmt.Sprintf("version https://git-lfs.github.com/spec/v1\noid sha256:%s\nsize %d\n", oid, size) -} - -// writePointers stores one canonical pointer blob per inventory object and -// returns oid -> blob id, an unambiguous selector. fast-import streams the -// blobs over stdin (no argv limits) and, with no commit/reset commands, -// creates no refs. An empty inventory runs nothing. -func (a *lfsAux) writePointers(ctx context.Context, inv lfsInventory) (map[string]string, error) { - if err := ctx.Err(); err != nil { - return nil, err - } - oids := make([]string, 0, len(inv)) - for oid, size := range inv { - if err := ctx.Err(); err != nil { - return nil, err - } - if !lfsBareOIDRE.MatchString(oid) { - return nil, fmt.Errorf("invalid Git LFS object id %q", oid) - } - if size <= 0 { - return nil, fmt.Errorf("invalid Git LFS size %d for object %s", size, oid) - } - oids = append(oids, oid) - } - sel := make(map[string]string, len(oids)) - if len(oids) == 0 { - return sel, nil - } - sort.Strings(oids) - var in bytes.Buffer - // shortcut: fast-import gets the whole input as one in-memory buffer (~150 B - // per object); switch to an io.Pipe writer if inventories reach millions of objects. - for i, oid := range oids { - if err := ctx.Err(); err != nil { - return nil, err - } - p := lfsCanonicalPointer(oid, inv[oid]) - fmt.Fprintf(&in, "blob\nmark :%d\ndata %d\n%s\n", i+1, len(p), p) - } - in.WriteString("done\n") - marks := filepath.Join(a.root, "marks") - defer os.Remove(marks) - cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "fast-import", "--quiet", "--done", "--export-marks="+marks) // #nosec G204 -- resolved git binary, argv only - cmd.Dir, cmd.Env, cmd.Stdin = a.root, a.env, &in - if out, err := cmd.CombinedOutput(); err != nil { - return nil, fmt.Errorf("git fast-import: %w: %s", err, out) - } - data, err := os.ReadFile(marks) - if err != nil { - return nil, err - } - return parseLFSMarks(string(data), oids) -} - -// parseLFSMarks fails closed: exactly one ":N <40 lowercase hex>" line per -// mark 1..len(oids), no duplicates, no extra fields. -func parseLFSMarks(data string, oids []string) (map[string]string, error) { - sel := make(map[string]string, len(oids)) - seen := map[string]bool{} - for _, line := range strings.Split(strings.TrimSpace(data), "\n") { - f := strings.Fields(line) - if len(f) != 2 || !strings.HasPrefix(f[0], ":") || !lfsBlobIDRE.MatchString(f[1]) { - return nil, fmt.Errorf("unexpected fast-import mark %q", line) - } - mark, err := strconv.Atoi(f[0][1:]) - if err != nil || mark < 1 || mark > len(oids) || f[0] != ":"+strconv.Itoa(mark) { - return nil, fmt.Errorf("unexpected fast-import mark %q", line) - } - if _, dup := sel[oids[mark-1]]; dup || seen[f[1]] { - return nil, fmt.Errorf("duplicate fast-import mark %q", line) - } - seen[f[1]] = true - sel[oids[mark-1]] = f[1] - } - if len(sel) != len(oids) { - return nil, fmt.Errorf("fast-import returned %d of %d pointers", len(sel), len(oids)) - } - return sel, nil -} - -var lfsBlobIDRE = regexp.MustCompile(`\A[0-9a-f]{40}\z`) - // pointHEADAbsent sets HEAD to a ref guaranteed absent from the snapshot, so // git-lfs cannot read a .lfsconfig committed in the replicated history. The // namespace refs/gh-replicate/ is outside refs/heads and refs/tags (the only diff --git a/lfs_auxiliary_test.go b/lfs_auxiliary_test.go index 36002e4..ef3590d 100644 --- a/lfs_auxiliary_test.go +++ b/lfs_auxiliary_test.go @@ -1,18 +1,11 @@ package main import ( - "bufio" - "bytes" "context" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" "os" "os/exec" "path/filepath" "runtime" - "strconv" "strings" "testing" ) @@ -144,118 +137,6 @@ func TestLFSAuxCleansOnFailure(t *testing.T) { } } -func TestLFSAuxWritePointers(t *testing.T) { - a := newAux(t) - sel, err := a.writePointers(context.Background(), lfsInventory{}) - must(t, err) - if len(sel) != 0 { - t.Fatal("empty inventory must yield no selectors") - } - for _, bad := range []lfsInventory{ - {"xyz": 1}, - {strings.Repeat("A", 64): 1}, - {strings.Repeat("a", 64): 0}, - {strings.Repeat("a", 64): -1}, - } { - if _, err := a.writePointers(context.Background(), bad); err == nil { - t.Fatalf("accepted %v", bad) - } - } - inv := lfsInventory{} - for i := 0; i < 3000; i++ { - h := sha256.Sum256([]byte(strconv.Itoa(i))) - inv[hex.EncodeToString(h[:])] = int64(i + 1) - } - sel, err = a.writePointers(context.Background(), inv) - must(t, err) - if len(sel) != len(inv) { - t.Fatalf("%d selectors for %d objects", len(sel), len(inv)) - } - // Stream every selector through cat-file and compare bytes and blob id. - var q strings.Builder - oids := make([]string, 0, len(sel)) - for oid, id := range sel { - oids = append(oids, oid) - q.WriteString(id + "\n") - } - cmd := exec.Command(a.git, "--git-dir="+a.Dir, "cat-file", "--batch") - cmd.Env, cmd.Stdin = a.env, strings.NewReader(q.String()) - out, err := cmd.Output() - must(t, err) - r := bufio.NewReader(bytes.NewReader(out)) - seen := map[string]bool{} - for _, oid := range oids { - hdr, err := r.ReadString('\n') - must(t, err) - var id, typ string - var n int - if _, err := fmt.Sscanf(hdr, "%s %s %d", &id, &typ, &n); err != nil || typ != "blob" || id != sel[oid] || seen[id] { - t.Fatalf("bad header %q for %s", hdr, oid) - } - seen[id] = true - body := make([]byte, n+1) - _, err = io.ReadFull(r, body) - must(t, err) - if string(body[:n]) != lfsCanonicalPointer(oid, inv[oid]) { - t.Fatalf("pointer mismatch for %s: %q", oid, body[:n]) - } - if lfs, err := exec.LookPath("git-lfs"); err == nil && len(seen) <= 3 { - c := exec.Command(lfs, "pointer", "--check", "--strict", "--stdin") - c.Env, c.Stdin = a.env, bytes.NewReader(body[:n]) - if out, err := c.CombinedOutput(); err != nil { - t.Fatalf("git-lfs rejects pointer: %v %s", err, out) - } - } - } - refs := exec.Command(a.git, "--git-dir="+a.Dir, "for-each-ref") - refs.Env = a.env - out, err = refs.Output() - must(t, err) - if len(out) != 0 { - t.Fatalf("refs created: %s", out) - } - if _, err := os.Stat(filepath.Join(a.root, "marks")); !os.IsNotExist(err) { - t.Fatalf("marks left: %v", err) - } -} - -func TestLFSAuxWritePointersCanceled(t *testing.T) { - a := newAux(t) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, err := a.writePointers(ctx, lfsInventory{}); err == nil { - t.Fatal("canceled ctx with empty inventory must fail") - } - inv := lfsInventory{strings.Repeat("a", 64): 1} - if _, err := a.writePointers(ctx, inv); err == nil { - t.Fatal("canceled ctx must fail") - } -} - -func TestLFSParseMarks(t *testing.T) { - id1, id2 := strings.Repeat("1", 40), strings.Repeat("2", 40) - oids := []string{"a", "b"} - if sel, err := parseLFSMarks(":1 "+id1+"\n:2 "+id2+"\n", oids); err != nil || sel["b"] != id2 { - t.Fatalf("valid rejected: %v", err) - } - for _, bad := range []string{ - ":1 " + id1, // missing mark - ":1 " + id1 + "\n:1 " + id2, // duplicate mark - ":1 " + id1 + "\n:2 " + id1, // duplicate blob id - ":1 " + id1 + "\n:3 " + id2, // out of range - ":1 " + id1 + "\n:2 " + strings.Repeat("G", 40), // non-hex - ":1 " + id1 + "\n:2 " + strings.Repeat("A", 40), // uppercase - ":1 " + id1 + "\n:2 " + strings.Repeat("2", 64), // sha256-length id - ":1 " + id1 + "\n:2 " + id2 + " extra", - ":1 " + id1 + "\n:+2 " + id2, - ":1 " + id1 + "\n garbage", - } { - if _, err := parseLFSMarks(bad, oids); err == nil { - t.Fatalf("accepted %q", bad) - } - } -} - func TestLFSSideEnvIsolation(t *testing.T) { t.Setenv("GIT_DIR", "/evil") t.Setenv("GH_TOKEN", "inherited-token") diff --git a/lfs_integration_test.go b/lfs_integration_test.go index 9a7f396..fecd70a 100644 --- a/lfs_integration_test.go +++ b/lfs_integration_test.go @@ -14,6 +14,7 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "strings" "sync" "testing" @@ -139,6 +140,10 @@ func sha256hex(data []byte) string { return hex.EncodeToString(sum[:]) } +func canonicalPointer(oid string, size int64) string { + return "version https://git-lfs.github.com/spec/v1\noid sha256:" + oid + "\nsize " + strconv.FormatInt(size, 10) + "\n" +} + // TestLFSIntegrationTransfer runs the real transferLFS path over HTTP against a // real git-lfs: a source bare with historical and tagged canonical pointers, an // isolated source LFS server, and a fresh destination server. It requires @@ -163,11 +168,11 @@ func TestLFSIntegrationTransfer(t *testing.T) { gitTest(t, work, "init", "-b", "main") gitTest(t, work, "config", "user.name", "Test") gitTest(t, work, "config", "user.email", "test@example.com") - must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(lfsCanonicalPointer(oid1, int64(len(content1)))), 0o644)) + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid1, int64(len(content1)))), 0o644)) gitTest(t, work, "add", ".") gitTest(t, work, "commit", "-m", "v1") gitTest(t, work, "tag", "v1") - must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(lfsCanonicalPointer(oid2, int64(len(content2)))), 0o644)) + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid2, int64(len(content2)))), 0o644)) gitTest(t, work, "add", ".") gitTest(t, work, "commit", "-m", "v2") gitTest(t, work, "push", "file://"+srcBare, "refs/heads/main:refs/heads/main", "refs/tags/v1:refs/tags/v1") diff --git a/lfs_snapshot.go b/lfs_snapshot.go deleted file mode 100644 index fe36c11..0000000 --- a/lfs_snapshot.go +++ /dev/null @@ -1,136 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" -) - -// materializeRefs makes a.Dir hold exactly refs (heads and tags, by object ID) -// with every reachable object copied into its own pack, read from the local -// bare store srcGitDir. Nothing runs inside srcGitDir: its config, hooks and -// HEAD are never read, and nothing is written there. a's HEAD is left alone. -// -// Objects are borrowed through a temporary alternates entry, packed locally -// with repack -a (which includes alternate objects), then the entry is removed -// and connectivity is checked with fsck. A missing or concurrently pruned -// object makes update-ref, repack or fsck fail: the step fails closed but this -// does not protect against a non-cooperating process deleting objects; run it -// under the cache lock. On error a is in an unspecified state: Close it. -// An empty refs still checks that the auxiliary has no visible refs. -func (a *lfsAux) materializeRefs(ctx context.Context, srcGitDir string, refs []gitRef) error { - if err := ctx.Err(); err != nil { - return err - } - var in strings.Builder - seen := make(map[string]string, len(refs)) - for _, r := range refs { - if err := ctx.Err(); err != nil { - return err - } - if !validSnapshotRefName(r.Name) { - return fmt.Errorf("invalid snapshot ref name %q", r.Name) - } - if !lfsBlobIDRE.MatchString(r.ID) { // aux is sha1-only - return fmt.Errorf("invalid object id %q for %s", r.ID, r.Name) - } - if _, exists := seen[r.Name]; exists { - return fmt.Errorf("duplicate snapshot ref %s", r.Name) - } - seen[r.Name] = r.ID - fmt.Fprintf(&in, "option no-deref\ncreate %s %s\n", r.Name, r.ID) - } - // Fail closed on any pre-existing ref (any namespace, loose or packed): - // wildcard pushes would otherwise publish refs outside the snapshot. - cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "for-each-ref", "--count=1", "--format=%(refname)") // #nosec G204 -- resolved git binary, argv only - cmd.Dir, cmd.Env = a.root, a.env - if out, err := cmd.Output(); err != nil { - return fmt.Errorf("git for-each-ref: %w", err) - } else if len(strings.TrimSpace(string(out))) != 0 { - return fmt.Errorf("auxiliary repository already has refs (%s)", strings.TrimSpace(string(out))) - } - if len(refs) == 0 { - return nil - } - src, err := filepath.Abs(filepath.Join(srcGitDir, "objects")) - if err != nil { - return err - } - if fi, err := os.Stat(src); err != nil || !fi.IsDir() { - return fmt.Errorf("snapshot source objects %s: not a directory", src) - } - if strings.ContainsAny(src, "\n\r") { - return errors.New("snapshot source path contains a newline") - } - alt := filepath.Join(a.Dir, "objects", "info", "alternates") - if err := os.WriteFile(alt, []byte(src+"\n"), 0o600); err != nil { - return err - } - defer os.Remove(alt) - // One transaction over stdin: no argv limit; "create" fails if a ref exists. - cmd = exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "update-ref", "--stdin") // #nosec G204 -- resolved git binary, argv only - cmd.Dir, cmd.Env, cmd.Stdin = a.root, a.env, strings.NewReader(in.String()) - if out, err := cmd.CombinedOutput(); err != nil { - return fmt.Errorf("git update-ref: %w: %s", err, out) - } - // Broken symbolic refs are invisible until their target exists. - cmd = exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "for-each-ref", "--format=%(refname) %(objectname)") // #nosec G204 -- resolved git binary, argv only - cmd.Dir, cmd.Env = a.root, a.env - out, err := cmd.Output() - if err != nil { - return fmt.Errorf("verify snapshot refs: %w", err) - } - remaining := len(seen) - for _, line := range strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") { - name, id, ok := strings.Cut(line, " ") - if !ok || seen[name] != id || id == "" { - return fmt.Errorf("unexpected snapshot ref %q", line) - } - delete(seen, name) - remaining-- - } - if remaining != 0 { - return errors.New("snapshot refs are incomplete") - } - if err := a.run(ctx, "--git-dir="+a.Dir, "repack", "-a", "-d", "-q"); err != nil { - return err - } - if err := os.Remove(alt); err != nil { - return err - } - return a.run(ctx, "--git-dir="+a.Dir, "fsck", "--connectivity-only", "--no-dangling", "--no-progress") -} - -// validSnapshotRefName is a conservative subset of git check-ref-format, -// limited to refs/heads/ and refs/tags/. A "@" or a component ending in "." -// is valid in Git; only the whole name may not end in ".". Spaces, control -// characters and newlines stay rejected: they would break update-ref --stdin. -func validSnapshotRefName(n string) bool { - rest, ok := strings.CutPrefix(n, "refs/heads/") - if !ok { - if rest, ok = strings.CutPrefix(n, "refs/tags/"); !ok { - return false - } - } - if rest == "" || strings.Contains(n, "..") || strings.Contains(n, "@{") { - return false - } - for _, c := range n { - if c <= ' ' || c == 0x7f || strings.ContainsRune(`~^:?*[\`, c) { - return false - } - } - if strings.HasSuffix(n, ".") { - return false - } - for _, p := range strings.Split(rest, "/") { - if p == "" || strings.HasPrefix(p, ".") || strings.HasSuffix(p, ".lock") { - return false - } - } - return true -} diff --git a/lfs_snapshot_test.go b/lfs_snapshot_test.go deleted file mode 100644 index 4c778b8..0000000 --- a/lfs_snapshot_test.go +++ /dev/null @@ -1,305 +0,0 @@ -package main - -import ( - "context" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" -) - -func snapGit(t *testing.T, dir string, args ...string) string { - t.Helper() - cmd := exec.Command("git", args...) - cmd.Dir = dir - cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1", - "GIT_AUTHOR_NAME=a", "GIT_AUTHOR_EMAIL=a@a", "GIT_COMMITTER_NAME=a", "GIT_COMMITTER_EMAIL=a@a") - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("git %v: %v: %s", args, err, out) - } - return strings.TrimSpace(string(out)) -} - -// snapSource builds a bare store with a branch, an annotated tag and annotated -// tags to a blob and a tree; returns the dir and its captured refs. -func snapSource(t *testing.T) (string, []gitRef) { - t.Helper() - work := t.TempDir() - snapGit(t, work, "init", "-q", "-b", "main", "--object-format=sha1") - must(t, os.WriteFile(filepath.Join(work, "f"), []byte("a\n"), 0o600)) - snapGit(t, work, "add", "f") - snapGit(t, work, "commit", "-qm", "c1") - snapGit(t, work, "tag", "-a", "v1", "-m", "v1") - snapGit(t, work, "tag", "-a", "blobtag", "-m", "b", snapGit(t, work, "rev-parse", "HEAD:f")) - snapGit(t, work, "tag", "-a", "treetag", "-m", "t", snapGit(t, work, "rev-parse", "HEAD^{tree}")) - snapGit(t, work, "branch", "gone") - src := filepath.Join(t.TempDir(), "src.git") - snapGit(t, work, "clone", "-q", "--bare", "--no-local", work, src) - return src, snapRefs(t, src) -} - -func snapRefs(t *testing.T, dir string) []gitRef { - t.Helper() - var refs []gitRef - for _, l := range strings.Split(snapGit(t, dir, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads", "refs/tags"), "\n") { - if id, n, ok := strings.Cut(l, " "); ok { - refs = append(refs, gitRef{Name: n, ID: id}) - } - } - return refs -} - -func snapFmt(refs []gitRef) string { - var b strings.Builder - for _, r := range refs { - b.WriteString(r.ID + " " + r.Name + "\n") - } - return b.String() -} - -func TestLFSSnapshotMaterializesExactRefs(t *testing.T) { - src, refs := snapSource(t) - a := newAux(t) - must(t, a.materializeRefs(context.Background(), src, refs)) - if got := snapFmt(snapRefs(t, a.Dir)); got != snapFmt(refs) { - t.Fatalf("refs\n%s\nwant\n%s", got, snapFmt(refs)) - } - if _, err := os.Stat(filepath.Join(a.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { - t.Fatalf("alternates left behind: %v", err) - } - if h := snapGit(t, a.Dir, "symbolic-ref", "HEAD"); h != "refs/heads/master" && h != "refs/heads/main" { - t.Fatalf("HEAD touched: %s", h) - } - for tag, typ := range map[string]string{"v1": "commit", "blobtag": "blob", "treetag": "tree"} { - if got := snapGit(t, a.Dir, "cat-file", "-t", "refs/tags/"+tag); got != "tag" { - t.Fatalf("%s is %s, want annotated tag", tag, got) - } - if got := snapGit(t, a.Dir, "cat-file", "-t", "refs/tags/"+tag+"^{}"); got != typ { - t.Fatalf("%s peels to %s want %s", tag, got, typ) - } - } - - // Mutate and GC the source: the snapshot is self-contained and unchanged. - snapGit(t, src, "update-ref", "-d", "refs/heads/gone") - snapGit(t, src, "update-ref", "-d", "refs/tags/v1") - snapGit(t, src, "update-ref", "refs/heads/later", refs[0].ID) - snapGit(t, src, "reflog", "expire", "--expire=now", "--all") - snapGit(t, src, "gc", "-q", "--prune=now") - snapGit(t, a.Dir, "fsck", "--connectivity-only", "--no-dangling") - - dst := filepath.Join(t.TempDir(), "dst.git") - snapGit(t, t.TempDir(), "init", "-q", "--bare", dst) - snapGit(t, a.Dir, "push", "-q", dst, refs[0].ID+":refs/heads/excl") - snapGit(t, a.Dir, "push", "-q", "--atomic", "--force", dst, "refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*") - got := snapRefs(t, dst) - var mirrored []gitRef - for _, r := range got { - if r.Name == "refs/heads/excl" { - if r.ID != refs[0].ID { - t.Fatal("exclusive ref changed") - } - continue - } - mirrored = append(mirrored, r) - } - if len(mirrored) == len(got) { - t.Fatal("exclusive ref lost") - } - if snapFmt(mirrored) != snapFmt(refs) { - t.Fatalf("destination\n%s\nwant\n%s", snapFmt(mirrored), snapFmt(refs)) - } -} - -func TestLFSSnapshotAtomicReject(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("shell hook") - } - src, refs := snapSource(t) - var c1 string - for _, r := range refs { - if r.Name == "refs/heads/main" { - c1 = r.ID - } - } - work := t.TempDir() - snapGit(t, work, "clone", "-q", src, "w") - w := filepath.Join(work, "w") - snapGit(t, w, "commit", "-q", "--allow-empty", "-m", "c2") - c2 := snapGit(t, w, "rev-parse", "HEAD") - snapGit(t, w, "push", "-q", "origin", "HEAD:refs/heads/main") - a := newAux(t) - must(t, a.materializeRefs(context.Background(), src, []gitRef{{"refs/heads/good", c2}, {"refs/heads/reject", c2}})) - - for _, atomic := range []bool{false, true} { - dst := filepath.Join(t.TempDir(), "dst.git") - snapGit(t, t.TempDir(), "init", "-q", "--bare", dst) - snapGit(t, src, "push", "-q", dst, c1+":refs/heads/good") - must(t, os.WriteFile(filepath.Join(dst, "hooks", "update"), []byte("#!/bin/sh\n[ \"$1\" = refs/heads/reject ] && exit 1\nexit 0\n"), 0o700)) - args := []string{"push", "-q", "--force", dst, "refs/heads/*:refs/heads/*"} - if atomic { - args = append(args[:1], append([]string{"--atomic"}, args[1:]...)...) - } - cmd := exec.Command("git", args...) - cmd.Dir, cmd.Env = a.Dir, append(os.Environ(), "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_CONFIG_NOSYSTEM=1") - if err := cmd.Run(); err == nil { - t.Fatalf("atomic=%v: push must fail", atomic) - } - want := c2 - if atomic { - want = c1 - } - if got := snapGit(t, dst, "rev-parse", "refs/heads/good"); got != want { - t.Fatalf("atomic=%v: good=%s want %s", atomic, got, want) - } - if snapGit(t, dst, "for-each-ref", "refs/heads/reject") != "" { - t.Fatalf("atomic=%v: reject created", atomic) - } - } -} - -func TestLFSSnapshotMissingObjectFailsClosed(t *testing.T) { - src, refs := snapSource(t) - // Unknown object: update-ref refuses. - a := newAux(t) - if err := a.materializeRefs(context.Background(), src, []gitRef{{"refs/heads/x", strings.Repeat("1", 40)}}); err == nil { - t.Fatal("missing tip must fail") - } - // Tip present but a reachable blob is gone: repack/fsck refuse. - loose := t.TempDir() - snapGit(t, loose, "init", "-q", "--bare", "l.git") - l := filepath.Join(loose, "l.git") - snapGit(t, src, "push", "-q", l, "refs/heads/main") - blob := snapGit(t, l, "rev-parse", "refs/heads/main:f") - // small pushes stay loose (receive.unpackLimit=100), so the blob is a single file - must(t, os.Remove(filepath.Join(l, "objects", blob[:2], blob[2:]))) - b := newAux(t) - var main string - for _, r := range refs { - if r.Name == "refs/heads/main" { - main = r.ID - } - } - if err := b.materializeRefs(context.Background(), l, []gitRef{{"refs/heads/main", main}}); err == nil { - t.Fatal("missing reachable object must fail") - } - if _, err := os.Stat(filepath.Join(b.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { - t.Fatalf("alternates left after failure: %v", err) - } -} - -func TestLFSSnapshotRejectsBadInputAndEmpty(t *testing.T) { - a := newAux(t) - id := strings.Repeat("a", 40) - bad := []gitRef{ - {"HEAD", id}, {"refs/remotes/x", id}, {"refs/heads/", id}, {"refs/heads/a..b", id}, - {"refs/heads/a b", id}, {"refs/heads/.x", id}, {"refs/heads/x.lock", id}, {"refs/heads/x/", id}, {"refs/heads/x.", id}, {"refs/heads//x", id}, {"refs/heads/a\x7fb", id}, {"refs/heads/a\tb", id}, {"refs/heads/a\x00b", id}, - {"refs/tags/a@{1}", id}, {"refs/heads/a\nb", id}, {"refs/heads/x", strings.Repeat("a", 64)}, - {"refs/heads/x", "HEAD"}, {"refs/heads/x", strings.ToUpper(id)}, - } - for _, r := range bad { - if err := a.materializeRefs(context.Background(), "/nonexistent", []gitRef{r}); err == nil { - t.Fatalf("accepted %q", r) - } - } - if err := a.materializeRefs(context.Background(), "/nonexistent", []gitRef{{"refs/heads/x", id}, {"refs/heads/x", id}}); err == nil { - t.Fatal("accepted duplicate") - } - // Empty: no-op even with a bogus source. - must(t, a.materializeRefs(context.Background(), "/nonexistent", nil)) - if snapGit(t, a.Dir, "for-each-ref") != "" { - t.Fatal("empty snapshot created refs") - } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - src, refs := snapSource(t) - if err := a.materializeRefs(ctx, src, refs); err == nil { - t.Fatal("cancelled context must fail") - } - if snapGit(t, a.Dir, "for-each-ref") != "" { - t.Fatal("cancelled snapshot created refs") - } -} - -func TestLFSSnapshotValidatorMatchesGit(t *testing.T) { - names := []string{"@", "foo./bar", "a.b", "a/b/c", "é", "-x", "a@b", "x.lock", "a/.b", "a/b.lock/c", "a..b", "a b", "x.", "a//b", "a/", "a@{b", "a~", "a^", "a:", "a?", "a*", "a[", `a\b`, "a\x7f", "a\tb", "/a"} - for _, pre := range []string{"refs/heads/", "refs/tags/"} { - for _, n := range names { - full := pre + n - err := exec.Command("git", "check-ref-format", full).Run() - if got := validSnapshotRefName(full); got != (err == nil) { - t.Errorf("%q: validator=%v git valid=%v", full, got, err == nil) - } - } - } - // Valid-but-unusual names really round-trip through update-ref --stdin. - src, refs := snapSource(t) - id := refs[0].ID - a := newAux(t) - in := []gitRef{{"refs/heads/@", id}, {"refs/heads/foo./bar", id}, {"refs/tags/@", id}, {"refs/tags/foo./bar", id}} - must(t, a.materializeRefs(context.Background(), src, in)) - got := map[string]string{} - for _, r := range snapRefs(t, a.Dir) { - got[r.Name] = r.ID - } - if len(got) != len(in) { - t.Fatalf("refs %v", got) - } - for _, r := range in { - if got[r.Name] != r.ID { - t.Fatalf("missing %s", r.Name) - } - } -} - -func TestLFSSnapshotFailsClosedOnExistingRefs(t *testing.T) { - src, refs := snapSource(t) - for _, packed := range []bool{false, true} { - for _, ref := range []string{"refs/heads/old", "refs/notes/x", "refs/foo/bar"} { - for name, mat := range map[string][]gitRef{"empty": nil, "refs": refs} { - a := newAux(t) - tree := snapGit(t, a.Dir, "mktree") // empty stdin: empty tree - c := snapGit(t, a.Dir, "commit-tree", "-m", "old", tree) - snapGit(t, a.Dir, "update-ref", ref, c) - if packed { - snapGit(t, a.Dir, "pack-refs", "--all") - } - before := snapGit(t, a.Dir, "for-each-ref") - if err := a.materializeRefs(context.Background(), src, mat); err == nil { - t.Fatalf("%s/%s packed=%v: must fail", name, ref, packed) - } - if after := snapGit(t, a.Dir, "for-each-ref"); after != before { - t.Fatalf("%s/%s: refs changed\n%s\n%s", name, ref, before, after) - } - if _, err := os.Stat(filepath.Join(a.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { - t.Fatalf("alternates left: %v", err) - } - } - } - } -} - -func TestLFSSnapshotRejectsDanglingSymbolicRefs(t *testing.T) { - src, refs := snapSource(t) - for _, ref := range []string{"refs/heads/unexpected", "refs/heads/main"} { - t.Run(ref, func(t *testing.T) { - a := newAux(t) - target := "refs/heads/main" - if ref == target { - target = "refs/heads/missing" - } - snapGit(t, a.Dir, "symbolic-ref", ref, target) - if got := snapGit(t, a.Dir, "for-each-ref"); got != "" { - t.Fatalf("dangling symbolic ref unexpectedly visible: %s", got) - } - if err := a.materializeRefs(context.Background(), src, refs); err == nil { - t.Fatal("snapshot accepted a dangling symbolic ref") - } - if _, err := os.Stat(filepath.Join(a.Dir, "objects", "info", "alternates")); !os.IsNotExist(err) { - t.Fatalf("alternates left after failure: %v", err) - } - }) - } -} From 7319d5923969c8397edd31e8fc7aea3a633d45ee Mon Sep 17 00:00:00 2001 From: Victor M Varela Date: Fri, 30 Oct 2026 17:51:58 +0100 Subject: [PATCH 4/5] fix: isolate scan from inherited config; restore Plan9/gosec CI; drop dead code --- .github/workflows/ci.yml | 17 ++++++++++ accounts_test.go | 28 ---------------- cache_lock.go | 11 ------- cache_test.go | 7 +++- lfs_auxiliary.go | 7 +--- lfs_objects.go | 2 +- lfs_proc_other.go | 15 +++++++++ lfs_proc_unix.go | 4 +-- lfs_proc_windows.go | 2 +- replicate.go | 18 ----------- safeguards.go | 70 +++++++++++++++++++++++----------------- 11 files changed, 83 insertions(+), 98 deletions(-) create mode 100644 lfs_proc_other.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 934bb0a..29b55b4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,6 +27,23 @@ jobs: - run: python3 scripts/test_verify_e2e.py -v + lfs-integration: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version: '1.27.3' + cache: true + - name: Install Git LFS 3.8.1 + run: | + curl -sSLo git-lfs.tar.gz https://github.com/git-lfs/git-lfs/releases/download/v3.8.1/git-lfs-linux-amd64-v3.8.1.tar.gz + tar -xzf git-lfs.tar.gz + echo "$PWD/git-lfs-3.8.1" >> "$GITHUB_PATH" + git lfs version + - run: go test -race -timeout 3m -tags=lfsintegration -run '^TestLFSIntegration' ./... + + binaries: runs-on: ubuntu-latest strategy: diff --git a/accounts_test.go b/accounts_test.go index b3d267f..447c2e6 100644 --- a/accounts_test.go +++ b/accounts_test.go @@ -7,39 +7,11 @@ import ( "fmt" "net/http" "reflect" - "slices" "strings" "testing" "time" ) -func TestGitEnvDropsInheritedTokens(t *testing.T) { - t.Setenv("GH_TOKEN", "inherited") - t.Setenv("GITHUB_TOKEN", "inherited-app") - env := gitEnv("side-token") - seen := 0 - for _, entry := range env { - if entry == "GH_TOKEN=side-token" { - seen++ - continue - } - if strings.HasPrefix(entry, "GH_TOKEN=") || strings.HasPrefix(entry, "GITHUB_TOKEN=") { - t.Errorf("inherited token survived: %q", entry) - } - } - if seen != 1 { - t.Fatalf("side token set %d times", seen) - } - if !slices.Contains(env, "GIT_TERMINAL_PROMPT=0") { - t.Fatal("missing GIT_TERMINAL_PROMPT=0") - } - for _, entry := range gitEnv("") { - if strings.HasPrefix(entry, "GH_TOKEN=") { - t.Fatal("inherited run must not receive a token") - } - } -} - func TestSideResolvesRequestedAccount(t *testing.T) { old := tokenForAccount t.Cleanup(func() { tokenForAccount = old }) diff --git a/cache_lock.go b/cache_lock.go index bceba92..a644fd6 100644 --- a/cache_lock.go +++ b/cache_lock.go @@ -1,10 +1,8 @@ package main import ( - "context" "fmt" "os" - "os/exec" ) // Never unlink the lock file: all users must lock the same file. @@ -15,12 +13,3 @@ func lockCache(path string) (*os.File, error) { } return f, nil } - -// Git retains a reference to the lock if the parent is killed mid-command. -func (r *replicator) gitCommand(ctx context.Context, token, name string, args ...string) *exec.Cmd { - cmd := gitCommand(ctx, token, name, args...) - if r.cacheLock != nil { - inheritCacheLock(cmd, r.cacheLock) - } - return cmd -} diff --git a/cache_test.go b/cache_test.go index 3479ab3..a9f541f 100644 --- a/cache_test.go +++ b/cache_test.go @@ -167,7 +167,12 @@ func TestCacheLockActiveChild(t *testing.T) { r := &replicator{cacheLock: lock, ctx: context.Background(), timeout: 20 * time.Second} // A real Git process must retain the lock while its command is active. alias := `!"` + filepath.ToSlash(os.Args[0]) + `" -test.run=^TestCacheLockActiveChild$ cache-child` - if err := r.command(root, side{}, "git", "-c", "alias.cache-child="+alias, "cache-child"); err != nil { + cmd := r.scanGitCommand(context.Background(), "-c", "alias.cache-child="+alias, "cache-child") + cmd.Dir = root + cmd.Env = append(cmd.Env, "GH_REPLICATE_ACTIVE_CHILD="+root) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { t.Fatal(err) } return diff --git a/lfs_auxiliary.go b/lfs_auxiliary.go index 91c36d7..419d5af 100644 --- a/lfs_auxiliary.go +++ b/lfs_auxiliary.go @@ -156,16 +156,11 @@ func lfsSideEnv(root, token, path string) []string { return env } -// lfsStandaloneAgent is empty in production: GitHub uses basic HTTPS transfer. -// Tests override it to "lfs-standalone-file" to exercise file:// remotes locally. -var lfsStandaloneAgent = "" - // lfsCmd builds a git command in the aux bare for one side, with the side's // isolated environment, its LFS endpoint pinned and the cache lock inherited. func (r *replicator) lfsCmd(ctx context.Context, a *lfsAux, s side, ownerRepo string, args ...string) *exec.Cmd { full := append([]string{"-c", "credential.helper=", "-c", "credential.https://github.com.helper=!gh auth git-credential", - "-c", "lfs.url=" + lfsEndpoint(ownerRepo), "-c", "lfs.pushurl=" + lfsEndpoint(ownerRepo), - "-c", "lfs.standalonetransferagent=" + lfsStandaloneAgent}, args...) + "-c", "lfs.url=" + lfsEndpoint(ownerRepo), "-c", "lfs.pushurl=" + lfsEndpoint(ownerRepo)}, args...) cmd := newLFSCmd(ctx, a.git, full...) // #nosec G204 -- resolved git binary, argv only cmd.Dir = a.Dir cmd.Env = lfsSideEnv(a.root, s.token, os.Getenv("PATH")) diff --git a/lfs_objects.go b/lfs_objects.go index c207028..547fe32 100644 --- a/lfs_objects.go +++ b/lfs_objects.go @@ -47,7 +47,7 @@ func verifyLFSObject(ctx context.Context, path, oid string, size int64) error { if fi.Size() != size { return fmt.Errorf("Git LFS object %s has size %d, expected %d", oid, fi.Size(), size) } - f, err := os.Open(path) + f, err := os.Open(path) // #nosec G304 -- path is built from a validated lowercase 64-hex OID under the controlled LFS root if err != nil { return fmt.Errorf("Git LFS object %s: %w", oid, err) } diff --git a/lfs_proc_other.go b/lfs_proc_other.go new file mode 100644 index 0000000..8bb33c2 --- /dev/null +++ b/lfs_proc_other.go @@ -0,0 +1,15 @@ +//go:build !unix && !windows + +package main + +import ( + "context" + "os/exec" +) + +// newLFSCmd on unsupported platforms (e.g. plan9) kills only the direct child. +// shortcut: git-lfs descendants may survive a cancellation here; LFS transfer is +// not exercised on these platforms. +func newLFSCmd(ctx context.Context, name string, args ...string) *exec.Cmd { + return exec.CommandContext(ctx, name, args...) // #nosec G204 -- name is the resolved absolute git binary, argv only +} diff --git a/lfs_proc_unix.go b/lfs_proc_unix.go index efcf1bb..d58bede 100644 --- a/lfs_proc_unix.go +++ b/lfs_proc_unix.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build unix package main @@ -11,7 +11,7 @@ import ( // newLFSCmd starts the command in its own process group so a cancellation kills // the whole tree, including git-lfs descendants that hold the cache lock. func newLFSCmd(ctx context.Context, name string, args ...string) *exec.Cmd { - cmd := exec.CommandContext(ctx, name, args...) + cmd := exec.CommandContext(ctx, name, args...) // #nosec G204 -- name is the resolved absolute git binary, argv only cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { if cmd.Process == nil { diff --git a/lfs_proc_windows.go b/lfs_proc_windows.go index ef5d191..11daa9f 100644 --- a/lfs_proc_windows.go +++ b/lfs_proc_windows.go @@ -11,5 +11,5 @@ import ( // shortcut: git-lfs descendants may survive a cancellation on Windows; add a // Job Object before enabling LFS transfer there. func newLFSCmd(ctx context.Context, name string, args ...string) *exec.Cmd { - return exec.CommandContext(ctx, name, args...) + return exec.CommandContext(ctx, name, args...) // #nosec G204 -- name is the resolved absolute git binary, argv only } diff --git a/replicate.go b/replicate.go index a4cac82..37cacb7 100644 --- a/replicate.go +++ b/replicate.go @@ -891,24 +891,6 @@ func jsonBody(v any) io.Reader { return &b } -func (r *replicator) command(dir string, s side, name string, args ...string) error { - ctx, cancel := context.WithTimeout(r.ctx, r.timeout) - defer cancel() - - cmd := r.gitCommand(ctx, s.token, name, args...) - cmd.Dir = dir - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - - if err := cmd.Run(); err != nil { - if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return fmt.Errorf("%s timed out after %s", name, r.timeout) - } - return fmt.Errorf("%s: %w", name, err) - } - return nil -} - // Validate downloaded bytes before deleting an existing destination asset. func verifyAsset(file *os.File, a asset) (string, error) { info, err := file.Stat() diff --git a/safeguards.go b/safeguards.go index 4d96209..bbcd3b8 100644 --- a/safeguards.go +++ b/safeguards.go @@ -12,6 +12,7 @@ import ( "os/exec" "path/filepath" "regexp" + "runtime" "strconv" "strings" "time" @@ -50,32 +51,6 @@ func uniqueTags(releases []release) error { return nil } -// Configuration applies only to this child process. Never write ~/.gitconfig. -func gitCommand(ctx context.Context, token, name string, args ...string) *exec.Cmd { - if name == "git" { - args = append([]string{"-c", "credential.helper=", "-c", "credential.https://github.com.helper=!gh auth git-credential", "-c", "http.https://github.com/.extraheader="}, args...) - } - cmd := exec.CommandContext(ctx, name, args...) // #nosec G204 -- all production callers pass the literal "git"; args go directly to argv with no shell - cmd.Env = gitEnv(token) - return cmd -} - -// A side's token must replace the inherited one: duplicate entries are -// resolved inconsistently by credential helpers. -func gitEnv(token string) []string { - env := make([]string, 0, len(os.Environ())+2) - for _, entry := range os.Environ() { - if strings.HasPrefix(entry, "GH_TOKEN=") || strings.HasPrefix(entry, "GITHUB_TOKEN=") { - continue - } - env = append(env, entry) - } - if token != "" { - env = append(env, "GH_TOKEN="+token) - } - return append(env, "GIT_TERMINAL_PROMPT=0") -} - // tokenForAccount reads a token the user already stored for that account; it // never switches the active account or writes the credential store. var tokenForAccount = func(login string) (string, error) { @@ -177,12 +152,47 @@ type gitRef struct{ Name, ID string } var gitObjectIDRE = regexp.MustCompile(`\A([0-9a-f]{40}|[0-9a-f]{64})\z`) +// localGitEnv is a minimal environment for local-only git commands (no network +// or credentials), isolated from inherited config and GIT_* overrides so the +// user's or parent's configuration cannot change what the scan reads. +func localGitEnv() []string { + env := []string{ + "HOME=" + os.TempDir(), + "XDG_CONFIG_HOME=" + filepath.Join(os.TempDir(), "gh-replicate-xdg"), + "PATH=" + os.Getenv("PATH"), + "GIT_CONFIG_NOSYSTEM=1", + "GIT_CONFIG_GLOBAL=" + os.DevNull, + "GIT_TERMINAL_PROMPT=0", + "GIT_ATTR_NOSYSTEM=1", + "LC_ALL=C", + } + if runtime.GOOS == "windows" { + for _, k := range []string{"SystemRoot", "ComSpec"} { + if v := os.Getenv(k); v != "" { + env = append(env, k+"="+v) + } + } + } + return env +} + +// scanGitCommand builds a local-only git command with the cache lock inherited +// and no inherited config, so the scan reads only the repository it is pointed at. +func (r *replicator) scanGitCommand(ctx context.Context, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, "git", args...) // #nosec G204 -- fixed "git" binary, argv only + cmd.Env = localGitEnv() + if r.cacheLock != nil { + inheritCacheLock(cmd, r.cacheLock) + } + return cmd +} + // captureRefs records the names and object IDs of refs/heads and refs/tags once. // Call it under the caller's cache lock; later ref changes do not affect it. func (r *replicator) captureRefs(dir string) ([]gitRef, error) { ctx, cancel := context.WithTimeout(r.ctx, r.timeout) defer cancel() - cmd := r.gitCommand(ctx, "", "git", "--no-replace-objects", "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads", "refs/tags") + cmd := r.scanGitCommand(ctx, "--no-replace-objects", "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads", "refs/tags") cmd.Dir = dir out, err := cmd.Output() if err != nil { @@ -244,10 +254,10 @@ func (r *replicator) scanLFSBlobs(dir string, revs []string, revsIn io.Reader, v ctx, cancel := context.WithTimeout(r.ctx, r.timeout) defer cancel() // --no-replace-objects: refs/replace in the cache must not hide what gets pushed. - reachable := r.gitCommand(ctx, "", "git", append([]string{"--no-replace-objects", "rev-list", "--objects", "--no-object-names"}, revs...)...) + reachable := r.scanGitCommand(ctx, append([]string{"--no-replace-objects", "rev-list", "--objects", "--no-object-names"}, revs...)...) reachable.Stdin = revsIn - check := r.gitCommand(ctx, "", "git", "--no-replace-objects", "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)") - read := r.gitCommand(ctx, "", "git", "--no-replace-objects", "cat-file", "--batch") + check := r.scanGitCommand(ctx, "--no-replace-objects", "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)") + read := r.scanGitCommand(ctx, "--no-replace-objects", "cat-file", "--batch") for _, cmd := range []*exec.Cmd{reachable, check, read} { cmd.Dir = dir } From f062f985c27098fa61c6b8cbc53c476ff109f182 Mon Sep 17 00:00:00 2001 From: Victor M Varela Date: Fri, 30 Oct 2026 23:17:15 +0100 Subject: [PATCH 5/5] fix: harden Git LFS transfer after review - Block LFS transfer on platforms without whole-tree cancellation (Windows). - Fail closed when the ephemeral HEAD unexpectedly resolves. - Prove per-side credential separation (unit test + external proxy/CA ensayo). - Assert dry-run makes no LFS requests and an upload failure stops before Actions or any ref push. - Build-tag the process-tree test to unix. - Document best-effort cleanup and possible orphaned upload objects. --- README.md | 2 +- entrypoint_test.go | 4 +- lfs_auxiliary.go | 21 ++- lfs_credential_test.go | 52 +++++++ lfs_integration_test.go | 330 +++++++++++++++++++++++++++++++++++++++- lfs_proc_other.go | 3 + lfs_proc_test.go | 8 +- lfs_proc_unix.go | 4 + lfs_proc_windows.go | 5 + replicate.go | 3 + 10 files changed, 418 insertions(+), 14 deletions(-) create mode 100644 lfs_credential_test.go diff --git a/README.md b/README.md index 3b45d0e..84fa7ba 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ Both flags are optional and independent; without them the active account is used ## Local cache -A per-source lock lives under your OS user cache directory (`gh-replicate/git-v1`) so a second run of the same source fails with the lock path until the first exits. Source history is no longer reused across runs: each run copies into a fresh, private, temporary repository with its own configuration, so an interrupted run leaves no partial state. You can delete the cache directory while no replication is running. +A per-source lock lives under your OS user cache directory (`gh-replicate/git-v1`) so a second run of the same source fails with the lock path until the first exits. Source history is no longer reused across runs: each run copies into a fresh, private, temporary repository with its own configuration, so no partial state is ever reused. Cleanup is best effort — a hard kill (SIGKILL) can leave a temporary directory behind — and a failed LFS upload can leave objects on the destination without new refs. You can delete the cache directory while no replication is running. ## License diff --git a/entrypoint_test.go b/entrypoint_test.go index 1a733d1..18ec7cb 100644 --- a/entrypoint_test.go +++ b/entrypoint_test.go @@ -25,8 +25,8 @@ const ( func seamStub(t *testing.T) { t.Helper() isolateCache(t) - oldSide, oldRemote := newSide, gitRemote - t.Cleanup(func() { newSide, gitRemote = oldSide, oldRemote }) + oldSide, oldRemote, oldEndpoint := newSide, gitRemote, lfsEndpoint + t.Cleanup(func() { newSide, gitRemote, lfsEndpoint = oldSide, oldRemote, oldEndpoint }) } type gitFixture struct { diff --git a/lfs_auxiliary.go b/lfs_auxiliary.go index 419d5af..9b6e18e 100644 --- a/lfs_auxiliary.go +++ b/lfs_auxiliary.go @@ -107,17 +107,26 @@ func (a *lfsAux) pointHEADAbsent(ctx context.Context) error { if err := a.run(ctx, "--git-dir="+a.Dir, "symbolic-ref", "HEAD", absent); err != nil { return err } - // Fail closed if HEAD unexpectedly resolves to a commit. - cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "rev-parse", "--verify", "HEAD") // #nosec G204 -- resolved git binary, argv only + // Fail closed if HEAD unexpectedly resolves to a commit. --quiet makes a + // dangling HEAD exit 1 with no output; any other non-zero exit (git broken, + // cancellation, bad git-dir) is a real failure and must abort, not pass. + cmd := exec.CommandContext(ctx, a.git, "--git-dir="+a.Dir, "rev-parse", "--verify", "--quiet", "HEAD") // #nosec G204 -- resolved git binary, argv only cmd.Dir, cmd.Env = a.root, a.env - if err := cmd.Run(); err == nil { + out, err := cmd.Output() + if err == nil { return errors.New("ephemeral HEAD resolves; refusing to run LFS") } - return nil + var ee *exec.ExitError + if errors.As(err, &ee) && ee.ExitCode() == 1 && len(out) == 0 { + return nil + } + return fmt.Errorf("verify ephemeral HEAD is absent: %w", err) } -// lfsEndpoint is the GitHub LFS API URL for a repo's HTTPS remote. -func lfsEndpoint(ownerRepo string) string { +// lfsEndpoint is the GitHub LFS API URL for a repo's HTTPS remote. It is a var +// so tests can point it at a synthetic server independently of gitRemote, which +// still drives the plain git fetch/push URL. +var lfsEndpoint = func(ownerRepo string) string { return gitRemote(ownerRepo) + "/info/lfs" } diff --git a/lfs_credential_test.go b/lfs_credential_test.go new file mode 100644 index 0000000..16be322 --- /dev/null +++ b/lfs_credential_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "context" + "strings" + "testing" +) + +// TestLFSSideCredentialsAreSeparated checks that the command built for the +// source side carries only the source token and source endpoint, and the target +// side only the target token and endpoint. lfsCmd only builds the command (it +// does not run), so this is deterministic and needs no git-lfs. +func TestLFSSideCredentialsAreSeparated(t *testing.T) { + r := &replicator{ + source: side{token: "source-token"}, + target: side{token: "target-token"}, + ctx: context.Background(), + } + a := newAux(t) + src := r.lfsCmd(context.Background(), a, r.source, "owner/source", "lfs", "fetch") + dst := r.lfsCmd(context.Background(), a, r.target, "owner/target", "lfs", "push") + + if got := envValue(src.Env, "GH_TOKEN"); got != "source-token" { + t.Fatalf("source GH_TOKEN = %q, want source-token", got) + } + if got := envValue(dst.Env, "GH_TOKEN"); got != "target-token" { + t.Fatalf("target GH_TOKEN = %q, want target-token", got) + } + srcArgs := strings.Join(src.Args, " ") + dstArgs := strings.Join(dst.Args, " ") + if !strings.Contains(srcArgs, "lfs.url=https://github.com/owner/source.git/info/lfs") || + !strings.Contains(srcArgs, "lfs.pushurl=https://github.com/owner/source.git/info/lfs") { + t.Fatalf("source endpoint not fully pinned: %s", srcArgs) + } + if !strings.Contains(dstArgs, "lfs.url=https://github.com/owner/target.git/info/lfs") || + !strings.Contains(dstArgs, "lfs.pushurl=https://github.com/owner/target.git/info/lfs") { + t.Fatalf("target endpoint not fully pinned: %s", dstArgs) + } + // The isolated environment must not inherit another GitHub token. + if envValue(src.Env, "GITHUB_TOKEN") != "" || envValue(dst.Env, "GITHUB_TOKEN") != "" { + t.Fatalf("inherited GITHUB_TOKEN leaked: src=%q dst=%q", envValue(src.Env, "GITHUB_TOKEN"), envValue(dst.Env, "GITHUB_TOKEN")) + } +} + +func envValue(env []string, key string) string { + for _, kv := range env { + if i := strings.IndexByte(kv, '='); i >= 0 && kv[:i] == key { + return kv[i+1:] + } + } + return "" +} diff --git a/lfs_integration_test.go b/lfs_integration_test.go index fecd70a..0c02b89 100644 --- a/lfs_integration_test.go +++ b/lfs_integration_test.go @@ -8,6 +8,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -24,14 +25,21 @@ import ( // lfsServer is a minimal Git LFS batch API + basic transfer over HTTP, enough // for transferLFS to run against a real git-lfs without GitHub or credentials. type lfsServer struct { - mu sync.Mutex - objects map[string][]byte + mu sync.Mutex + objects map[string][]byte + actionToken string // short-lived transfer capability the batch issues + failUpload string // OID whose PUT fails (partial-upload test) + puts int // PUTs received, proving a transfer was attempted + requests int // every LFS request (batch + objects), proving no contact } func newLFSServer(t *testing.T) (*httptest.Server, *lfsServer) { t.Helper() - s := &lfsServer{objects: map[string][]byte{}} + s := &lfsServer{objects: map[string][]byte{}, actionToken: "test"} ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + s.requests++ + s.mu.Unlock() switch { case strings.HasSuffix(r.URL.Path, "/info/lfs/objects/batch"): s.batch(w, r) @@ -82,7 +90,7 @@ func (s *lfsServer) batch(w http.ResponseWriter, r *http.Request) { "actions": map[string]any{ req.Operation: map[string]any{ "href": "http://" + r.Host + "/objects/" + o.OID, - "header": map[string]string{"Authorization": "Bearer test"}, + "header": map[string]string{"Authorization": "Bearer " + s.actionToken}, }, }, }) @@ -95,6 +103,12 @@ func (s *lfsServer) object(w http.ResponseWriter, r *http.Request) { oid := strings.TrimPrefix(r.URL.Path, "/objects/") s.mu.Lock() defer s.mu.Unlock() + // The action's header is a short-lived capability: it must reach the + // transfer, so a missing or wrong one proves it was not relayed. + if got := r.Header.Get("Authorization"); got != "Bearer "+s.actionToken { + http.Error(w, "missing or wrong transfer authorization", 401) + return + } switch r.Method { case http.MethodGet: data, ok := s.objects[oid] @@ -104,6 +118,15 @@ func (s *lfsServer) object(w http.ResponseWriter, r *http.Request) { } _, _ = w.Write(data) case http.MethodPut: + s.puts++ + if oid == s.failUpload { + // Fail mid-transfer with a Git-LFS JSON error (not text/plain, which + // git-lfs treats as a non-fatal "unsupported Content-Type"). + w.Header().Set("Content-Type", "application/vnd.git-lfs+json") + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"message":"injected upload failure"}`)) + return + } data, err := io.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), 400) @@ -135,6 +158,18 @@ func (s *lfsServer) get(oid string) []byte { return s.objects[oid] } +func (s *lfsServer) putCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.puts +} + +func (s *lfsServer) requestCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.requests +} + func sha256hex(data []byte) string { sum := sha256.Sum256(data) return hex.EncodeToString(sum[:]) @@ -220,3 +255,290 @@ func TestLFSIntegrationTransfer(t *testing.T) { t.Fatalf("destination object %s bytes differ", oid2) } } + +// TestLFSIntegrationPartialUploadFails ensures a mid-batch upload failure is +// reported as an error. syncGit returns on that error before disableActions and +// pushRefs, so a partial upload can never lead to publishing refs. +func TestLFSIntegrationPartialUploadFails(t *testing.T) { + if _, err := exec.LookPath("git-lfs"); err != nil { + t.Fatalf("git-lfs is required for -tags=lfsintegration: %v", err) + } + content1 := []byte("one\n") + content2 := []byte("two\n") + oid1, oid2 := sha256hex(content1), sha256hex(content2) + + src, srcStore := newLFSServer(t) + dst, dstStore := newLFSServer(t) + srcStore.add(oid1, content1) + srcStore.add(oid2, content2) + dstStore.failUpload = oid2 + + srcBare := filepath.Join(t.TempDir(), "src.git") + gitTest(t, t.TempDir(), "init", "--bare", srcBare) + work := t.TempDir() + gitTest(t, work, "init", "-b", "main") + gitTest(t, work, "config", "user.name", "Test") + gitTest(t, work, "config", "user.email", "test@example.com") + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid1, int64(len(content1)))), 0o644)) + gitTest(t, work, "add", ".") + gitTest(t, work, "commit", "-m", "one") + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid2, int64(len(content2)))), 0o644)) + gitTest(t, work, "add", ".") + gitTest(t, work, "commit", "-m", "two") + gitTest(t, work, "push", "file://"+srcBare, "refs/heads/main:refs/heads/main") + + prev := gitRemote + gitRemote = func(ownerRepo string) string { + if ownerRepo == "dst" { + return dst.URL + } + return src.URL + } + defer func() { gitRemote = prev }() + + a := newAux(t) + r := &replicator{ctx: context.Background(), timeout: time.Minute, source: side{}, target: side{}} + must(t, a.run(context.Background(), "--git-dir="+a.Dir, "config", "remote.replicate-target.url", dst.URL)) + must(t, a.run(context.Background(), "--git-dir="+a.Dir, "fetch", "--prune", "--no-tags", + "file://"+srcBare, "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*")) + refs, err := r.captureRefs(a.Dir) + must(t, err) + inv, err := r.inventoryLFS(a.Dir, refs) + must(t, err) + if len(inv) != 2 { + t.Fatalf("inventory has %d objects, want 2", len(inv)) + } + must(t, a.pointHEADAbsent(context.Background())) + + err = r.transferLFS(context.Background(), a, "src", "dst", refs, inv) + if err == nil || !strings.Contains(err.Error(), "upload Git LFS objects") { + t.Fatalf("error = %v, want upload failure", err) + } + if dstStore.putCount() == 0 { + t.Fatal("destination received no upload attempt before the failure") + } + if !dstStore.has(oid1) { + t.Fatal("valid object was not stored before the injected failure") + } + if dstStore.has(oid2) { + t.Fatal("failed object was stored despite the injected failure") + } +} + +// TestLFSIntegrationSyncGitDryRunTransfersNothing runs syncGit in dry-run over a +// source with a canonical pointer (its object absent) and asserts the report is +// emitted while the destination stays empty: no LFS transfer, no ref push. +func TestLFSIntegrationSyncGitDryRunTransfersNothing(t *testing.T) { + if _, err := exec.LookPath("git-lfs"); err != nil { + t.Fatalf("git-lfs is required for -tags=lfsintegration: %v", err) + } + f := newGitFixture(t) + work := filepath.Join(t.TempDir(), "w") + gitTest(t, filepath.Dir(work), "clone", f.source, work) + gitTest(t, work, "config", "user.name", "Test") + gitTest(t, work, "config", "user.email", "test@example.com") + oid := strings.Repeat("a", 64) + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid, 12)), 0o644)) + gitTest(t, work, "add", "a.bin") + gitTest(t, work, "commit", "-m", "add pointer") + gitTest(t, work, "push", "origin", "main") + + seamStub(t) + gitRemote = func(ownerRepo string) string { + if ownerRepo == sourceRepo { + return f.source + } + if ownerRepo == targetRepo { + return f.destination + } + t.Fatalf("unexpected repository %q", ownerRepo) + return "" + } + side := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) { + fmt.Fprint(w, `{"enabled":false}`) + }), "token") + r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute, dryRun: true} + + out := captureStderr(t, func() { + if err := r.syncGit(sourceRepo, targetRepo); err != nil { + t.Fatalf("dry run failed: %v", err) + } + }) + if !strings.Contains(out, "Would transfer 1 Git LFS objects") { + t.Fatalf("dry run did not report the LFS transfer: %q", out) + } + if refs := gitRefs(t, f.destination); refs != "" { + t.Fatalf("dry run published destination refs: %q", refs) + } +} + +// TestLFSIntegrationSyncGitDownloadFailureStopsBeforePublishing runs syncGit over +// a source whose pointer names an absent object, so the LFS download fails; it +// asserts the run aborts before touching Actions or publishing any ref. +func TestLFSIntegrationSyncGitDownloadFailureStopsBeforePublishing(t *testing.T) { + if _, err := exec.LookPath("git-lfs"); err != nil { + t.Fatalf("git-lfs is required for -tags=lfsintegration: %v", err) + } + f := newGitFixture(t) + work := filepath.Join(t.TempDir(), "w") + gitTest(t, filepath.Dir(work), "clone", f.source, work) + gitTest(t, work, "config", "user.name", "Test") + gitTest(t, work, "config", "user.email", "test@example.com") + oid := strings.Repeat("a", 64) // object deliberately absent from the source + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid, 12)), 0o644)) + gitTest(t, work, "add", "a.bin") + gitTest(t, work, "commit", "-m", "add pointer") + gitTest(t, work, "push", "origin", "main") + + seamStub(t) + gitRemote = func(ownerRepo string) string { + if ownerRepo == sourceRepo { + return f.source + } + if ownerRepo == targetRepo { + return f.destination + } + t.Fatalf("unexpected repository %q", ownerRepo) + return "" + } + calls := 0 + side := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) { + calls++ + fmt.Fprint(w, `{"enabled":false}`) + }), "token") + r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute} + + err := r.syncGit(sourceRepo, targetRepo) + if err == nil || !strings.Contains(err.Error(), "download Git LFS objects") { + t.Fatalf("error = %v, want LFS download failure", err) + } + if refs := gitRefs(t, f.destination); refs != "" { + t.Fatalf("destination refs published despite transfer failure: %q", refs) + } + if calls != 0 { + t.Fatalf("Actions API called %d times despite transfer failure", calls) + } +} + +// TestLFSIntegrationSyncGitDryRunMakesNoLFSRequests pins the LFS endpoint to a +// synthetic server (independent of the file:// git remote) and asserts a dry run +// never contacts it: transferLFS is skipped, so no LFS batch or object request. +func TestLFSIntegrationSyncGitDryRunMakesNoLFSRequests(t *testing.T) { + if _, err := exec.LookPath("git-lfs"); err != nil { + t.Fatalf("git-lfs is required for -tags=lfsintegration: %v", err) + } + f := newGitFixture(t) + work := filepath.Join(t.TempDir(), "w") + gitTest(t, filepath.Dir(work), "clone", f.source, work) + gitTest(t, work, "config", "user.name", "Test") + gitTest(t, work, "config", "user.email", "test@example.com") + content := []byte("dry\n") + oid := sha256hex(content) + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid, int64(len(content)))), 0o644)) + gitTest(t, work, "add", "a.bin") + gitTest(t, work, "commit", "-m", "add pointer") + gitTest(t, work, "push", "origin", "main") + + seamStub(t) + gitRemote = func(ownerRepo string) string { + if ownerRepo == sourceRepo { + return f.source + } + if ownerRepo == targetRepo { + return f.destination + } + t.Fatalf("unexpected repository %q", ownerRepo) + return "" + } + lfsSrv, lfsStore := newLFSServer(t) + lfsStore.add(oid, content) + lfsEndpoint = func(ownerRepo string) string { return lfsSrv.URL + "/info/lfs" } + + side := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) { + fmt.Fprint(w, `{"enabled":false}`) + }), "token") + r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute, dryRun: true} + + out := captureStderr(t, func() { + if err := r.syncGit(sourceRepo, targetRepo); err != nil { + t.Fatalf("dry run failed: %v", err) + } + }) + if !strings.Contains(out, "Would transfer 1 Git LFS objects") { + t.Fatalf("dry run did not report the LFS transfer: %q", out) + } + if refs := gitRefs(t, f.destination); refs != "" { + t.Fatalf("dry run published destination refs: %q", refs) + } + if n := lfsStore.requestCount(); n != 0 { + t.Fatalf("dry run made %d LFS requests, want 0", n) + } +} + +// TestLFSIntegrationSyncGitUploadFailureStopsBeforePublishing runs syncGit with a +// source object that downloads fine and a destination that rejects its upload, so +// the failure happens after a real download; it asserts the run aborts before +// Actions or any ref push. +func TestLFSIntegrationSyncGitUploadFailureStopsBeforePublishing(t *testing.T) { + if _, err := exec.LookPath("git-lfs"); err != nil { + t.Fatalf("git-lfs is required for -tags=lfsintegration: %v", err) + } + f := newGitFixture(t) + work := filepath.Join(t.TempDir(), "w") + gitTest(t, filepath.Dir(work), "clone", f.source, work) + gitTest(t, work, "config", "user.name", "Test") + gitTest(t, work, "config", "user.email", "test@example.com") + content := []byte("payload\n") + oid := sha256hex(content) + must(t, os.WriteFile(filepath.Join(work, "a.bin"), []byte(canonicalPointer(oid, int64(len(content)))), 0o644)) + gitTest(t, work, "add", "a.bin") + gitTest(t, work, "commit", "-m", "add pointer") + gitTest(t, work, "push", "origin", "main") + + seamStub(t) + gitRemote = func(ownerRepo string) string { + if ownerRepo == sourceRepo { + return f.source + } + if ownerRepo == targetRepo { + return f.destination + } + t.Fatalf("unexpected repository %q", ownerRepo) + return "" + } + srcSrv, srcStore := newLFSServer(t) + dstSrv, dstStore := newLFSServer(t) + srcStore.add(oid, content) + dstStore.failUpload = oid + lfsEndpoint = func(ownerRepo string) string { + if ownerRepo == sourceRepo { + return srcSrv.URL + "/info/lfs" + } + if ownerRepo == targetRepo { + return dstSrv.URL + "/info/lfs" + } + t.Fatalf("unexpected repository %q", ownerRepo) + return "" + } + + calls := 0 + side := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) { + calls++ + fmt.Fprint(w, `{"enabled":false}`) + }), "token") + r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute} + + err := r.syncGit(sourceRepo, targetRepo) + if err == nil || !strings.Contains(err.Error(), "upload Git LFS objects") { + t.Fatalf("error = %v, want LFS upload failure", err) + } + if refs := gitRefs(t, f.destination); refs != "" { + t.Fatalf("destination refs published despite upload failure: %q", refs) + } + if calls != 0 { + t.Fatalf("Actions API called %d times despite upload failure", calls) + } + if dstStore.has(oid) { + t.Fatal("failed object stored despite injected upload failure") + } +} diff --git a/lfs_proc_other.go b/lfs_proc_other.go index 8bb33c2..17b7c4a 100644 --- a/lfs_proc_other.go +++ b/lfs_proc_other.go @@ -7,6 +7,9 @@ import ( "os/exec" ) +// lfsTreeCancel is false on unsupported platforms: LFS transfer is refused. +const lfsTreeCancel = false + // newLFSCmd on unsupported platforms (e.g. plan9) kills only the direct child. // shortcut: git-lfs descendants may survive a cancellation here; LFS transfer is // not exercised on these platforms. diff --git a/lfs_proc_test.go b/lfs_proc_test.go index 96fb1ab..0fa47b5 100644 --- a/lfs_proc_test.go +++ b/lfs_proc_test.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build unix package main @@ -43,3 +43,9 @@ func TestLFSCmdCancelKillsProcessGroup(t *testing.T) { t.Fatalf("child %d still alive (err=%v)", pid, err) } } + +func TestLFSTreeCancelEnabled(t *testing.T) { + if !lfsTreeCancel { + t.Fatal("lfsTreeCancel must be true on platforms where LFS transfer is allowed") + } +} diff --git a/lfs_proc_unix.go b/lfs_proc_unix.go index d58bede..1e64c9f 100644 --- a/lfs_proc_unix.go +++ b/lfs_proc_unix.go @@ -8,6 +8,10 @@ import ( "syscall" ) +// lfsTreeCancel reports that newLFSCmd cancels the whole process tree; LFS +// transfer is only allowed on platforms where this holds. +const lfsTreeCancel = true + // newLFSCmd starts the command in its own process group so a cancellation kills // the whole tree, including git-lfs descendants that hold the cache lock. func newLFSCmd(ctx context.Context, name string, args ...string) *exec.Cmd { diff --git a/lfs_proc_windows.go b/lfs_proc_windows.go index 11daa9f..c13a838 100644 --- a/lfs_proc_windows.go +++ b/lfs_proc_windows.go @@ -7,6 +7,11 @@ import ( "os/exec" ) +// lfsTreeCancel is false on Windows: newLFSCmd kills only the direct child, so +// a cancellation can leave git-lfs descendants running during cleanup. LFS +// transfer is refused here until a Job Object makes cancellation kill the tree. +const lfsTreeCancel = false + // newLFSCmd on Windows kills only the direct child. // shortcut: git-lfs descendants may survive a cancellation on Windows; add a // Job Object before enabling LFS transfer there. diff --git a/replicate.go b/replicate.go index 37cacb7..574f675 100644 --- a/replicate.go +++ b/replicate.go @@ -466,6 +466,9 @@ func (r *replicator) syncGit(source, target string) error { } if len(inv) > 0 { + if !lfsTreeCancel { + return errors.New("Git LFS transfer is not supported on this platform because cancellation cannot terminate all git-lfs processes") + } if err := r.requireLFS(r.ctx, aux, r.source, source); err != nil { return err }