Skip to content

Git designed for AI agents.

43.1 KB
Raw Blame
package repository

import (
	"archive/tar"
	"bytes"
	"context"
	"encoding/binary"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"syscall"
	"testing"

	"github.com/feder-cr/git-ai/internal/git"
	"github.com/feder-cr/git-ai/internal/git/gittest"
	"github.com/feder-cr/git-ai/internal/git/localrepo"
	"github.com/feder-cr/git-ai/internal/gitaly/config"
	gitalyhook "github.com/feder-cr/git-ai/internal/gitaly/hook"
	"github.com/feder-cr/git-ai/internal/gitaly/repoutil"
	"github.com/feder-cr/git-ai/internal/gitaly/storage"
	"github.com/feder-cr/git-ai/internal/gitaly/storage/mode"
	"github.com/feder-cr/git-ai/internal/gitaly/transaction"
	"github.com/feder-cr/git-ai/internal/grpc/backchannel"
	"github.com/feder-cr/git-ai/internal/grpc/client"
	"github.com/feder-cr/git-ai/internal/grpc/metadata"
	"github.com/feder-cr/git-ai/internal/helper/text"
	"github.com/feder-cr/git-ai/internal/structerr"
	"github.com/feder-cr/git-ai/internal/testhelper"
	"github.com/feder-cr/git-ai/internal/testhelper/testcfg"
	"github.com/feder-cr/git-ai/internal/testhelper/testserver"
	"github.com/feder-cr/git-ai/internal/transaction/txinfo"
	"github.com/feder-cr/git-ai/internal/transaction/voting"
	"github.com/feder-cr/git-ai/proto/go/gitalypb"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
)

func TestReplicateRepository(t *testing.T) {
	ctx := testhelper.Context(t)

	type setupData struct {
		source                 *gitalypb.Repository
		target                 *gitalypb.Repository
		expectedObjects        []string
		expectedCustomHooks    []string
		expectedError          error
		expectedConfigMismatch bool
		env                    map[string]string
	}

	setupSourceAndTarget := func(t *testing.T, cfg config.Cfg, createTarget bool) (*gitalypb.Repository, string, *gitalypb.Repository, string) {
		t.Helper()

		source, sourcePath := gittest.CreateRepository(t, ctx, cfg)
		gittest.WriteCommit(t, cfg, sourcePath, gittest.WithMessage("init"), gittest.WithBranch("main"))

		var target *gitalypb.Repository
		var targetPath string
		if createTarget {
			target, targetPath = gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
				RelativePath: source.GetRelativePath(),
				Storage:      cfg.Storages[1],
			})
		} else {
			target = proto.Clone(source).(*gitalypb.Repository)
			target.StorageName = cfg.Storages[1].Name
			targetPath = filepath.Join(cfg.Storages[1].Path, target.GetRelativePath())
		}

		return source, sourcePath, target, targetPath
	}

	for _, tc := range []struct {
		desc       string
		serverOpts []testserver.GitalyServerOpt
		setup      func(t *testing.T, cfg config.Cfg) setupData
	}{
		{
			desc: "replicate config",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Write a modified Git config file to the source repository to verify it is
				// getting created in the target repository as expected.
				gittest.Exec(t, cfg, "-C", sourcePath, "config", "please.replicate", "me")

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "replicate info attributes",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Write an info attributes file to the source repository to verify it is getting
				// created in the target repository as expected.
				// We should get rid of this with https://gitlab.com/groups/gitlab-org/-/epics/9006
				attrFilePath := filepath.Join(sourcePath, "info", "attributes")
				require.NoError(t, os.MkdirAll(filepath.Dir(attrFilePath), mode.Directory))
				attributesData := []byte("*.pbxproj binary\n")
				require.NoError(t, os.WriteFile(attrFilePath, attributesData, mode.File))

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "replicate branch",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Create a new branch that only exists in the source repository to verify that it
				// is getting created in the target repository as expected.
				gittest.WriteCommit(t, cfg, sourcePath, gittest.WithBranch("branch"))

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "replicate source repo is of different reference backend",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Create a new branch that only exists in the source repository to verify that it
				// is getting created in the target repository as expected.
				gittest.WriteCommit(t, cfg, sourcePath, gittest.WithBranch("branch"))

				migrateTo := git.ReferenceBackendReftables.Name
				if testhelper.IsReftableEnabled() {
					migrateTo = git.ReferenceBackendFiles.Name
				}

				gittest.Exec(t, cfg, "-C", sourcePath, "refs", "migrate", "--ref-format="+migrateTo)

				return setupData{
					source: source,
					target: target,
					env: map[string]string{
						"GIT_DEFAULT_REF_FORMAT": "",
					},
					expectedConfigMismatch: true,
				}
			},
		},
		{
			desc: "replicate unreachable object with snapshot-base replication",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Create a loose object in the source repository to verify that it is getting
				// created in the target repository as expected. This ensures that snapshot
				// replication is being used.
				blobData, err := text.RandomHex(10)
				require.NoError(t, err)
				blobID := text.ChompBytes(gittest.ExecOpts(t, cfg, gittest.ExecConfig{Stdin: bytes.NewBufferString(blobData)},
					"-C", sourcePath, "hash-object", "-w", "--stdin",
				))

				return setupData{
					source:          source,
					target:          target,
					expectedObjects: []string{blobID},
				}
			},
		},
		{
			desc: "replicate custom hooks",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Set up custom hooks in source repository to verify that the hooks are getting
				// created in the target repository as expected.
				hooks := testhelper.MustCreateCustomHooksTar(t)
				require.NoError(t, repoutil.ExtractHooks(ctx, testhelper.NewLogger(t), hooks, sourcePath, false))

				return setupData{
					source:              source,
					target:              target,
					expectedCustomHooks: []string{"/pre-commit", "/pre-push", "/pre-receive"},
				}
			},
		},
		{
			desc: "replicate internal references to new target",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Create internal references in the source repository to verify that they are
				// getting created in the newly created target repository as expected. Regardless of
				// whether we classify them as hidden or read-only, we should be able to replicate
				// all of them.
				for refPrefix := range git.InternalRefPrefixes {
					_ = gittest.WriteCommit(t, cfg, sourcePath, gittest.WithParents(), gittest.WithMessage(refPrefix), gittest.WithReference(refPrefix+"1"))
				}

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "replicate internal references to existing target",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, targetPath := setupSourceAndTarget(t, cfg, true)

				// Create the same commit in both repositories so that they're in a known-good
				// state.
				sourceCommitID := gittest.WriteCommit(t, cfg, sourcePath, gittest.WithParents(), gittest.WithMessage("base"), gittest.WithBranch("main"))
				targetCommitID := gittest.WriteCommit(t, cfg, targetPath, gittest.WithParents(), gittest.WithMessage("base"), gittest.WithBranch("main"))
				require.Equal(t, sourceCommitID, targetCommitID)

				// Create internal references in the source repository to verify that they are
				// getting created in the existing target repository as expected. Regardless of
				// whether we classify them as hidden or read-only, we should be able to replicate
				// all of them.
				for refPrefix := range git.InternalRefPrefixes {
					gittest.WriteCommit(t, cfg, sourcePath, gittest.WithParents(), gittest.WithMessage(refPrefix), gittest.WithReference(refPrefix+"1"))
				}

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "empty target repository",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, _ := gittest.CreateRepository(t, ctx, cfg)

				// Set up a request with no target repository specified to verify that validation
				// fails and the RPC returns an error as expected.
				return setupData{
					source:        source,
					target:        nil,
					expectedError: structerr.NewInvalidArgument("%w", storage.ErrRepositoryNotSet),
				}
			},
		},
		{
			desc: "empty source repository",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				// Set up a request with no source repository specified to verify that validation
				// fails and the RPC returns an error as expected.
				return setupData{
					source: nil,
					target: &gitalypb.Repository{
						StorageName:  cfg.Storages[1].Name,
						RelativePath: "/ab/cd/abcdef1234",
					},
					expectedError: structerr.NewInvalidArgument("source repository cannot be empty"),
				}
			},
		},
		{
			desc: "target and source repository have same storage",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				// Set up a request with a source and target repository that share the same storage
				// to verify that validation fails and the RPC returns an error as expected.
				source, _ := gittest.CreateRepository(t, ctx, cfg)
				target := proto.Clone(source).(*gitalypb.Repository)

				return setupData{
					source:        source,
					target:        target,
					expectedError: structerr.NewInvalidArgument("repository and source have the same storage"),
				}
			},
		},
		{
			desc: "invalid target repository",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, _, target, targetPath := setupSourceAndTarget(t, cfg, true)

				// Delete Git data to make target repository invalid to verify that replication
				// proceeds and the invalid target repository is overwritten. No error is expected
				// since the RPC is still able to successfully replicate.
				for _, path := range []string{"refs", "objects", "HEAD"} {
					require.NoError(t, os.RemoveAll(filepath.Join(targetPath, path)))
				}

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "invalid source repository",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Delete Git data to make the source repository invalid to verify that repository
				// validation fails on the source and the RPC returns an error as expected.
				for _, path := range []string{"refs", "objects", "HEAD"} {
					require.NoError(t, os.RemoveAll(filepath.Join(sourcePath, path)))
				}

				err := ErrInvalidSourceRepository
				return setupData{
					source:        source,
					target:        target,
					expectedError: err,
				}
			},
		},
		{
			desc: "invalid source and target repository",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, targetPath := setupSourceAndTarget(t, cfg, true)

				// Delete Git data to make the source and target repositories invalid to verify that
				// repository validation fails and the RPC returns an error as expected.
				for _, repoPath := range []string{sourcePath, targetPath} {
					for _, path := range []string{"refs", "objects", "HEAD"} {
						require.NoError(t, os.RemoveAll(filepath.Join(repoPath, path)))
					}
				}

				return setupData{
					source:        source,
					target:        target,
					expectedError: ErrInvalidSourceRepository,
				}
			},
		},
		{
			desc: "fail to fetch source repository",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, true)

				// Corrupt the repository by writing garbage into HEAD to verify the RPC fails to
				// fetch the source repository and returns an error as expected.
				//
				// Remove the HEAD first as the files are read-only with transactions.
				headPath := filepath.Join(sourcePath, "HEAD")
				require.NoError(t, os.Remove(headPath))
				require.NoError(t, os.WriteFile(headPath, []byte("garbage"), mode.File))

				return setupData{
					source:        source,
					target:        target,
					expectedError: structerr.NewInternal("replicating repository: synchronizing references: fetch internal remote: getting remote default branch: head reference: exit status 128"),
				}
			},
		},
		{
			desc: "fsck disabled for fetch",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				// To validate that fsck is disabled, `git-fetch(1)` must be used to replicate
				// objects in the source repository. If the target repository already exists prior
				// to replication, snapshot replication is skipped ensuring all necessary objects in
				// the source repository are replicated to the target via `git-fetch(1)`.
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, true)

				// Write a tree into the source repository that's known-broken. For this object to
				// be fetched into the target repository `fsck` must be disabled.
				treeID := gittest.WriteTree(t, cfg, sourcePath, []gittest.TreeEntry{
					{Content: "content", Path: "dup", Mode: "100644"},
					{Content: "content", Path: "dup", Mode: "100644"},
				})

				commitID := gittest.WriteCommit(t, cfg, sourcePath,
					gittest.WithParents(),
					gittest.WithBranch("main"),
					gittest.WithTree(treeID),
				)

				repoClient := gitalypb.NewRepositoryServiceClient(gittest.DialService(t, ctx, cfg))

				// Verify that the broken tree is indeed in the source repository and that it is
				// reported as broken by git-fsck(1).
				resp, err := repoClient.Fsck(ctx, &gitalypb.FsckRequest{
					Repository: source,
				})
				require.NoError(t, err)
				require.Equal(t, fmt.Sprintf("error in tree %s: duplicateEntries: contains duplicate file entries\n", treeID), string(resp.GetError()))

				return setupData{
					source:          source,
					target:          target,
					expectedObjects: []string{treeID.String(), commitID.String()},
				}
			},
		},
		{
			desc: "source has different default branch",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, true)

				// Write a file in the repo
				treeID := gittest.WriteTree(t, cfg, sourcePath, []gittest.TreeEntry{
					{Content: "content", Path: "a.txt", Mode: "100644"},
				})

				// Commit on branch main
				commitID := gittest.WriteCommit(t, cfg, sourcePath,
					gittest.WithParents(),
					gittest.WithBranch("main"),
					gittest.WithTree(treeID),
					gittest.WithMessage("Initial commit"),
				)

				// Create a new branch
				gittest.CreateBranch(t, cfg, sourcePath, "new-branch")

				// Write a file on new branch
				secondTreeID := gittest.WriteTree(t, cfg, sourcePath, []gittest.TreeEntry{
					{Content: "new-content", Path: "new-context.txt", Mode: "100644"},
				})

				// Commit on new branch
				secondCommitID := gittest.WriteCommit(t, cfg, sourcePath,
					gittest.WithParents(),
					gittest.WithBranch("new-branch"),
					gittest.WithTree(secondTreeID),
					gittest.WithMessage("Commit on new branch"),
				)

				// Set default branch to the new branch
				gittest.SetDefaultBranch(t, cfg, sourcePath, "new-branch")

				return setupData{
					source:          source,
					target:          target,
					expectedObjects: []string{treeID.String(), commitID.String(), secondCommitID.String()},
				}
			},
		},
		{
			desc: "source HEAD points to non-existing branch",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				source, sourcePath, target, _ := setupSourceAndTarget(t, cfg, false)

				// Point the source HEAD at a branch that does not exist. This makes
				// resolving the remote HEAD fail with ErrReferenceNotFound in
				// fetchInternalRemote, exercising the early-return branch when
				// remoteHeadResolved is false.
				gittest.SetDefaultBranch(t, cfg, sourcePath, "does-not-exist")

				return setupData{
					source: source,
					target: target,
				}
			},
		},
		{
			desc: "replicate source repo with MVCC reference backend",
			setup: func(t *testing.T, cfg config.Cfg) setupData {
				// When GIT_DEFAULT_REF_FORMAT is set, git honors it directly, so an MVCC
				// repository cannot be created distinctly.
				testhelper.SkipWithReftable(t, "MVCC backend selection is overridden by GIT_DEFAULT_REF_FORMAT")
				// An MVCC repository must be created out-of-band, so with Praefect it is never
				// registered in the database and RepositoryExists fails before the backend check.
				testhelper.SkipWithPraefect(t, "MVCC repositories cannot be registered in Praefect's database")

				source, sourcePath := gittest.CreateMVCCRepository(t, ctx, cfg)
				commitID := gittest.WriteCommit(t, cfg, sourcePath, gittest.WithBranch("main"))
				gittest.Exec(t, cfg, "-C", sourcePath, "symbolic-ref", "HEAD", "refs/heads/main")

				target := proto.Clone(source).(*gitalypb.Repository)
				target.StorageName = cfg.Storages[1].Name

				return setupData{
					source:          source,
					target:          target,
					expectedObjects: []string{commitID.String()},
				}
			},
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("default", "target"))
			cfg := cfgBuilder.Build(t)

			testcfg.BuildGitalyHooks(t, cfg)
			testcfg.BuildGitalySSH(t, cfg)

			repoClient, serverSocketPath := runRepositoryService(t, cfg, tc.serverOpts...)
			cfg.SocketPath = serverSocketPath

			setup := tc.setup(t, cfg)

			for key, value := range setup.env {
				t.Setenv(key, value)
			}

			ctx := testhelper.MergeOutgoingMetadata(ctx, testcfg.GitalyServersMetadataFromCfg(t, cfg))
			_, err := repoClient.ReplicateRepository(ctx, &gitalypb.ReplicateRepositoryRequest{
				Repository: setup.target,
				Source:     setup.source,
			})

			// Verify error matches expected test case state.
			expectedStatus := status.Convert(setup.expectedError)
			actualStatus := status.Convert(err)

			// It is possible for the returned error to contain metadata that is difficult to assert
			// equivalency. For this reason, only the status code and error message are verified.
			assert.Equal(t, expectedStatus.Code(), actualStatus.Code())
			require.Equal(t, expectedStatus.Message(), actualStatus.Message())
			if err != nil {
				return
			}

			sourcePath := filepath.Join(cfg.Storages[0].Path, gittest.GetReplicaPath(t, ctx, cfg, setup.source))
			targetPath := filepath.Join(cfg.Storages[1].Path, gittest.GetReplicaPath(t, ctx, cfg, setup.target))

			refClient := gitalypb.NewRefServiceClient(gittest.DialService(t, ctx, cfg))

			// Compare refs from both repositories
			sourceRefs := gittest.GetReferencesAPI(t, ctx, refClient, setup.source, [][]byte{[]byte("refs/"), []byte("HEAD")})
			targetRefs := gittest.GetReferencesAPI(t, ctx, refClient, setup.target, [][]byte{[]byte("refs/"), []byte("HEAD")})
			require.Equal(t, sourceRefs, targetRefs, "refs including HEAD should match")

			// Verify Git config matches.
			if !setup.expectedConfigMismatch {
				require.Equal(t,
					testhelper.MustReadFile(t, filepath.Join(sourcePath, "config")),
					testhelper.MustReadFile(t, filepath.Join(targetPath, "config")),
					"config file must match",
				)
			}

			// Verify custom hooks replicated.
			var targetHooks []string
			targetHooksPath := filepath.Join(targetPath, repoutil.CustomHooksDir)
			require.NoError(t, filepath.WalkDir(targetHooksPath, func(path string, entry fs.DirEntry, err error) error {
				if os.IsNotExist(err) {
					return nil
				}
				require.NoError(t, err)

				trimmedPath := strings.TrimPrefix(path, targetHooksPath)
				if trimmedPath != "" {
					targetHooks = append(targetHooks, trimmedPath)
				}

				return nil
			}))
			require.ElementsMatch(t, setup.expectedCustomHooks, targetHooks)

			// Verify objects replicated.
			for _, oid := range setup.expectedObjects {
				gittest.Exec(t, cfg, "-C", targetPath, "cat-file", "-p", oid)
			}

			sourceBackend, err := localrepo.NewTestRepo(t, cfg, setup.source).ReferenceBackend(ctx)
			require.NoError(t, err)
			targetBackend, err := localrepo.NewTestRepo(t, cfg, setup.target).ReferenceBackend(ctx)
			require.NoError(t, err)

			require.Equal(t, sourceBackend.Name, targetBackend.Name)
		})
	}
}

func TestReplicateRepository_transactional(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("default", "replica"))
	cfg := cfgBuilder.Build(t)

	testcfg.BuildGitalyHooks(t, cfg)
	testcfg.BuildGitalySSH(t, cfg)

	_, serverSocketPath := runRepositoryService(t, cfg, testserver.WithDisablePraefect())
	cfg.SocketPath = serverSocketPath

	sourceRepo, sourceRepoPath := gittest.CreateRepository(t, ctx, cfg)
	commitID1 := gittest.WriteCommit(t, cfg, sourceRepoPath)
	commitID2 := gittest.WriteCommit(t, cfg, sourceRepoPath, gittest.WithBranch("master"), gittest.WithParents(commitID1))

	targetRepo := proto.Clone(sourceRepo).(*gitalypb.Repository)
	targetRepo.StorageName = cfg.Storages[1].Name

	var votes []voting.Vote
	txServer := testTransactionServer{
		vote: func(request *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
			vote, err := voting.VoteFromHash(request.GetReferenceUpdatesHash())
			require.NoError(t, err)
			votes = append(votes, vote)

			return &gitalypb.VoteTransactionResponse{
				State: gitalypb.VoteTransactionResponse_COMMIT,
			}, nil
		},
	}

	ctx, err := txinfo.InjectTransaction(ctx, 1, "primary", true)
	require.NoError(t, err)
	ctx = metadata.IncomingToOutgoing(ctx)
	ctx = testhelper.MergeOutgoingMetadata(ctx, testcfg.GitalyServersMetadataFromCfg(t, cfg))

	client := newMuxedRepositoryClient(t, ctx, cfg, serverSocketPath, backchannel.NewClientHandshaker(
		testhelper.SharedLogger(t),
		func() backchannel.Server {
			srv := grpc.NewServer()
			gitalypb.RegisterRefTransactionServer(srv, &txServer)
			return srv
		},
		backchannel.DefaultConfiguration(),
	))

	// The first invocation creates the repository via a snapshot given that it doesn't yet
	// exist.
	_, err = client.ReplicateRepository(ctx, &gitalypb.ReplicateRepositoryRequest{
		Repository: targetRepo,
		Source:     sourceRepo,
	})

	require.NoError(t, err)

	// There is a gitconfig though, so the vote should reflect its contents.
	gitconfigVote := voting.VoteFromData(testhelper.MustReadFile(t, filepath.Join(sourceRepoPath, "config")))

	// The custom hooks directory is empty, so we will only write a single empty directory. Thus, we only
	// write the relative path of that directory (".") as well as its mode bits to the vote hash. Note that
	// we use a temporary file here to figure out the expected permissions as they would in fact be subject
	// to change depending on the current umask.
	noHooksVoteData := [5]byte{'.', 0, 0, 0, 0}
	binary.BigEndian.PutUint32(noHooksVoteData[1:], uint32(mode.Directory))
	noHooksVote := voting.VoteFromData(noHooksVoteData[:])

	expectedVotes := []voting.Vote{
		// The first three votes are from repo creation.
		// We cannot easily derive these first three votes: they are based on the complete
		// hashed contents of the unpacked repository. We thus just only assert that they
		// are always the first three entries and that they are the same by simply taking the
		// first vote three times here.
		votes[0],
		votes[0],
		votes[0],

		// Votes from setting config files (called from voting.CommitLockedFile).
		voting.VoteFromData([]byte("preparing commit locked file")),
		gitconfigVote,
		gitconfigVote,

		// Votes from setting custom hooks
		voting.VoteFromData([]byte("preparing set custom hooks")),
		noHooksVote,
		noHooksVote,
	}

	require.Equal(t, expectedVotes, votes)

	// We're about to change refs/heads/master, and thus the mirror-fetch will update it. The
	// vote should reflect that.
	replicationVote := voting.VoteFromData([]byte(fmt.Sprintf("%[1]s %[2]s refs/heads/master\n", commitID2, commitID1)))

	// We're now changing a reference in the source repository such that we can observe changes
	// in the target repo.
	resp, err := client.WriteRef(ctx, &gitalypb.WriteRefRequest{
		Repository: sourceRepo,
		Ref:        []byte("refs/heads/master"),
		Revision:   []byte(commitID1),
	})
	require.NoError(t, err)
	testhelper.ProtoEqual(t, &gitalypb.WriteRefResponse{}, resp)

	votes = nil

	// And the second invocation uses FetchInternalRemote.
	_, err = client.ReplicateRepository(ctx, &gitalypb.ReplicateRepositoryRequest{
		Repository: targetRepo,
		Source:     sourceRepo,
	})
	require.NoError(t, err)

	expectedVotes = []voting.Vote{
		// Votes from setting config files (called from voting.CommitLockedFile).
		voting.VoteFromData([]byte("preparing commit locked file")),
		gitconfigVote,
		gitconfigVote,

		// Votes from reference transaction hook when updating refs/heads/master
		// This is current two because the git binary we are using now is not yet aware of
		// The preparing phase. Once newer version of git is used, this need to be updated
		// to three votes.
		replicationVote,
		replicationVote,

		// Votes from setting custom hooks
		voting.VoteFromData([]byte("preparing set custom hooks")),
		noHooksVote,
		noHooksVote,
	}

	require.Equal(t, expectedVotes, votes)
}

func TestFetchInternalRemote_successful(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)

	remoteCfg := testcfg.Build(t)
	remoteRepo, remoteRepoPath := gittest.CreateRepository(t, ctx, remoteCfg, gittest.CreateRepositoryConfig{
		SkipCreationViaService: true,
	})
	testcfg.BuildGitalyHooks(t, remoteCfg)
	gittest.WriteCommit(t, remoteCfg, remoteRepoPath, gittest.WithBranch(git.DefaultBranch))

	_, remoteAddr := runRepositoryService(t, remoteCfg, testserver.WithDisablePraefect())

	localCfg := testcfg.Build(t)
	localRepoProto, localRepoPath := gittest.CreateRepository(t, ctx, localCfg, gittest.CreateRepositoryConfig{
		SkipCreationViaService: true,
	})
	localRepo := localrepo.NewTestRepo(t, localCfg, localRepoProto)
	testcfg.BuildGitalySSH(t, localCfg)
	testcfg.BuildGitalyHooks(t, localCfg)
	gittest.Exec(t, remoteCfg, "-C", localRepoPath, "symbolic-ref", "HEAD", "refs/heads/feature")

	referenceTransactionHookCalled := 0

	// We do not require the server's address, but it needs to be around regardless such that
	// `FetchInternalRemote` can reach the hook service which is injected via the config.
	runRepositoryService(t, localCfg, testserver.WithHookManager(gitalyhook.NewMockManager(t, nil, nil, nil,
		func(t *testing.T, _ context.Context, _ gitalyhook.ReferenceTransactionState, _ []string, stdin io.Reader) error {
			// We need to discard stdin or otherwise the sending Goroutine may return an
			// EOF error and cause the test to fail.
			_, err := io.Copy(io.Discard, stdin)
			require.NoError(t, err)

			referenceTransactionHookCalled++
			return nil
		}),
	))

	ctx, err := storage.InjectGitalyServers(ctx, remoteRepo.GetStorageName(), remoteAddr, remoteCfg.Auth.Token)
	require.NoError(t, err)
	ctx = metadata.OutgoingToIncoming(ctx)

	getGitalySSHInvocationParams := listenGitalySSHCalls(t, localCfg)

	connsPool := client.NewPool()
	defer testhelper.MustClose(t, connsPool)

	// Use the `assert` package such that we can get information about why hooks have failed via
	// the hook logs in case it did fail unexpectedly.
	assert.NoError(t, fetchInternalRemote(ctx, &transaction.MockManager{}, connsPool, localRepo, remoteRepo))

	require.Equal(t,
		string(gittest.Exec(t, remoteCfg, "-C", remoteRepoPath, "show-ref", "--head")),
		string(gittest.Exec(t, localCfg, "-C", localRepoPath, "show-ref", "--head")),
	)

	sshParams := getGitalySSHInvocationParams()
	require.Equal(t, []string{"upload-pack", "gitaly", "git-upload-pack", "'/internal.git'\n"}, sshParams.arguments)
	require.Subset(t,
		sshParams.environment,
		[]string{
			"GIT_TERMINAL_PROMPT=0",
			"GIT_SSH_VARIANT=simple",
			"LANG=en_US.UTF-8",
			"GITALY_ADDRESS=" + remoteAddr,
		},
	)

	// referenceTransactionHookCalled is 4 (2 calls × 2 phases) on regular CI, which does not
	// yet include upstream commit ae55b12bb3 ("preparing" phase). On nightly builds it is 6
	// (2 calls × 3 phases). Once GIT_VERSION_PREV is bumped past ae55b12bb3, this can be
	// updated to expect 6 only.
	require.Contains(t, []int{4, 6}, referenceTransactionHookCalled)
}

func TestFetchInternalRemote_failure(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfg := testcfg.Build(t)

	repoProto, _ := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
		SkipCreationViaService: true,
	})
	repo := localrepo.NewTestRepo(t, cfg, repoProto)

	ctx = testhelper.MergeIncomingMetadata(ctx, testcfg.GitalyServersMetadataFromCfg(t, cfg))

	connsPool := client.NewPool()
	defer testhelper.MustClose(t, connsPool)

	err := fetchInternalRemote(ctx, &transaction.MockManager{}, connsPool, repo, &gitalypb.Repository{
		StorageName:  repoProto.GetStorageName(),
		RelativePath: "does-not-exist.git",
	})
	require.Error(t, err)

	// This error occurs because in `fetchInternalRemote` we first try to create
	// a remote repository to access the remote repo. But given that no connection
	// exists for Praefect, the dial phase fails.
	require.Contains(t, err.Error(), "could not dial source")
}

func TestExtractTarToDirectory_SymlinkValidation(t *testing.T) {
	t.Parallel()

	type tarEntry struct {
		header *tar.Header
		body   []byte
	}

	createTar := func(t *testing.T, entries []tarEntry) io.Reader {
		t.Helper()
		var buf bytes.Buffer
		tw := tar.NewWriter(&buf)
		for _, e := range entries {
			require.NoError(t, tw.WriteHeader(e.header))
			if len(e.body) > 0 {
				_, err := tw.Write(e.body)
				require.NoError(t, err)
			}
		}
		require.NoError(t, tw.Close())
		return &buf
	}

	tests := []struct {
		name        string
		entries     []tarEntry
		expectError string
	}{
		{
			name: "relative symlink within directory is allowed",
			entries: []tarEntry{
				{header: &tar.Header{Name: "subdir/", Typeflag: tar.TypeDir, Mode: 0o755}},
				{header: &tar.Header{Name: "subdir/target.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 5}, body: []byte("hello")},
				{header: &tar.Header{Name: "link", Typeflag: tar.TypeSymlink, Linkname: "subdir/target.txt"}},
			},
		},
		{
			name: "relative symlink escaping via dotdot is rejected",
			entries: []tarEntry{
				{header: &tar.Header{Name: "valid_before.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("aaa")},
				{header: &tar.Header{Name: "escape", Typeflag: tar.TypeSymlink, Linkname: "../../../../tmp"}},
				{header: &tar.Header{Name: "valid_after.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("bbb")},
			},
			expectError: "symlink target escapes extraction directory",
		},
		{
			name: "absolute symlink is still rejected",
			entries: []tarEntry{
				{header: &tar.Header{Name: "valid_before.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("aaa")},
				{header: &tar.Header{Name: "abs", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd"}},
				{header: &tar.Header{Name: "valid_after.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("bbb")},
			},
			expectError: "absolute symlink not allowed",
		},
		{
			name: "nested relative symlink escaping is rejected",
			entries: []tarEntry{
				{header: &tar.Header{Name: "a/b/", Typeflag: tar.TypeDir, Mode: 0o755}},
				{header: &tar.Header{Name: "a/b/safe.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("aaa")},
				{header: &tar.Header{Name: "a/b/link", Typeflag: tar.TypeSymlink, Linkname: "../../../etc"}},
				{header: &tar.Header{Name: "a/b/another.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("bbb")},
			},
			expectError: "symlink target escapes extraction directory",
		},
		{
			// Neither symlink escapes on its own, but chained together they do.
			name: "symlink chain escaping through a symlinked parent is rejected",
			entries: []tarEntry{
				{header: &tar.Header{Name: "valid_before.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("aaa")},
				{header: &tar.Header{Name: "a/", Typeflag: tar.TypeDir, Mode: 0o755}},
				{header: &tar.Header{Name: "a/up", Typeflag: tar.TypeSymlink, Linkname: ".."}},
				{header: &tar.Header{Name: "escape", Typeflag: tar.TypeSymlink, Linkname: "a/up/.."}},
				{header: &tar.Header{Name: "escape/pwned.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("bbb")},
			},
			expectError: "symlink target escapes extraction directory",
		},
		{
			// Same chain as above, but "escape" is extracted before the links it points
			// through exist. Its target cannot be resolved conclusively when it is created,
			// so the escape is only detectable once the whole archive is on disk.
			name: "symlink chain completed by a later entry is rejected",
			entries: []tarEntry{
				{header: &tar.Header{Name: "escape", Typeflag: tar.TypeSymlink, Linkname: "a/up/.."}},
				{header: &tar.Header{Name: "a/", Typeflag: tar.TypeDir, Mode: 0o755}},
				{header: &tar.Header{Name: "a/up", Typeflag: tar.TypeSymlink, Linkname: ".."}},
			},
			expectError: "symlink target escapes extraction directory",
		},
		{
			// Hard linking a symlink does not follow it, so "relocated" becomes a second
			// symlink carrying the same target in a different parent directory. From "a/b"
			// the target is the file at the root, but from the root it is two levels above
			// the extraction directory, so the copy has to be validated separately from the
			// original.
			name: "hard link relocating a symlink out of the directory is rejected",
			entries: []tarEntry{
				{header: &tar.Header{Name: "a/b/", Typeflag: tar.TypeDir, Mode: 0o755}},
				{header: &tar.Header{Name: "target.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("aaa")},
				{header: &tar.Header{Name: "a/b/link", Typeflag: tar.TypeSymlink, Linkname: "../../target.txt"}},
				{header: &tar.Header{Name: "relocated", Typeflag: tar.TypeLink, Linkname: "a/b/link"}},
			},
			expectError: "symlink target escapes extraction directory",
		},
		{
			// The copy resolves the same way as the original here, so recording hard linked
			// symlinks for validation must not reject them outright.
			name: "hard link copying a symlink within the directory is allowed",
			entries: []tarEntry{
				{header: &tar.Header{Name: "sub/", Typeflag: tar.TypeDir, Mode: 0o755}},
				{header: &tar.Header{Name: "sub/target.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 5}, body: []byte("hello")},
				{header: &tar.Header{Name: "sub/link", Typeflag: tar.TypeSymlink, Linkname: "target.txt"}},
				{header: &tar.Header{Name: "sub/copy", Typeflag: tar.TypeLink, Linkname: "sub/link"}},
			},
		},
		{
			name: "hard link to a regular file is allowed",
			entries: []tarEntry{
				{header: &tar.Header{Name: "target.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3}, body: []byte("aaa")},
				{header: &tar.Header{Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "target.txt"}},
			},
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()

			targetDir := t.TempDir()
			s := &server{logger: testhelper.NewLogger(t)}
			ctx := testhelper.Context(t)

			err := s.extractTarToDirectory(ctx, createTar(t, tc.entries), targetDir)
			if tc.expectError != "" {
				require.Error(t, err)
				require.Contains(t, err.Error(), tc.expectError)
			} else {
				require.NoError(t, err)
			}
		})
	}
}

func TestValidateSymlinkWithinRoot(t *testing.T) {
	t.Parallel()

	// symlink creates a symlink at root/path pointing at target, creating parent directories as
	// needed.
	symlink := func(t *testing.T, root, path, target string) {
		t.Helper()
		require.NoError(t, os.MkdirAll(filepath.Dir(filepath.Join(root, path)), mode.Directory))
		require.NoError(t, os.Symlink(target, filepath.Join(root, path)))
	}

	writeFile := func(t *testing.T, root, path string) {
		t.Helper()
		require.NoError(t, os.MkdirAll(filepath.Dir(filepath.Join(root, path)), mode.Directory))
		require.NoError(t, os.WriteFile(filepath.Join(root, path), []byte("content"), mode.File))
	}

	for _, tc := range []struct {
		desc string
		// setup prepares the state the symlink target is resolved against. The symlink being
		// validated is deliberately not created, as validation happens before it exists.
		setup func(t *testing.T, root string)
		// relPath is the path of the symlink being validated, relative to root.
		relPath string
		// linkname is the target of the symlink being validated.
		linkname    string
		expectedErr error
	}{
		{
			desc:     "target in the root",
			setup:    func(t *testing.T, root string) { writeFile(t, root, "target.txt") },
			relPath:  "link",
			linkname: "target.txt",
		},
		{
			desc:     "target in a subdirectory",
			setup:    func(t *testing.T, root string) { writeFile(t, root, "sub/target.txt") },
			relPath:  "link",
			linkname: "sub/target.txt",
		},
		{
			desc: "target reached by walking up out of a subdirectory",
			setup: func(t *testing.T, root string) {
				require.NoError(t, os.MkdirAll(filepath.Join(root, "a", "b"), mode.Directory))
				writeFile(t, root, "target.txt")
			},
			relPath:  "a/b/link",
			linkname: "../../target.txt",
		},
		{
			// Pointing at the root is permitted. It is only a problem in combination with a
			// further "..", which is caught when that other symlink is validated.
			desc:     "target is the root itself",
			relPath:  "link",
			linkname: ".",
		},
		{
			// Archives may contain symlinks whose target never materialises, so a target that
			// does not resolve to anything is not by itself a reason to reject.
			desc:     "dangling target inside the root",
			relPath:  "link",
			linkname: "does/not/exist",
		},
		{
			desc: "chain of symlinks staying inside the root",
			setup: func(t *testing.T, root string) {
				writeFile(t, root, "sub/target.txt")
				symlink(t, root, "first", "sub")
			},
			relPath:  "second",
			linkname: "first/target.txt",
		},
		{
			// The target resolves from where the symlink really lands, which is inside the
			// directory "linkdir" points at rather than "linkdir" itself.
			desc: "parent directory of the symlink is a symlink",
			setup: func(t *testing.T, root string) {
				require.NoError(t, os.MkdirAll(filepath.Join(root, "real"), mode.Directory))
				writeFile(t, root, "target.txt")
				symlink(t, root, "linkdir", "real")
			},
			relPath:  "linkdir/link",
			linkname: "../target.txt",
		},
		{
			desc: "chain of the maximum permitted length",
			setup: func(t *testing.T, root string) {
				writeFile(t, root, "target.txt")
				// The final link points at the target, so the chain contains exactly
				// maxSymlinkChainLength symlinks.
				for i := range maxSymlinkChainLength {
					target := "target.txt"
					if i < maxSymlinkChainLength-1 {
						target = fmt.Sprintf("link%d", i+1)
					}
					symlink(t, root, fmt.Sprintf("link%d", i), target)
				}
			},
			relPath:  "start",
			linkname: "link0",
		},
		{
			desc:        "target escapes with dotdot",
			relPath:     "link",
			linkname:    "../outside",
			expectedErr: errSymlinkEscapes,
		},
		{
			desc: "target escapes out of a subdirectory",
			setup: func(t *testing.T, root string) {
				require.NoError(t, os.MkdirAll(filepath.Join(root, "a", "b"), mode.Directory))
			},
			relPath:     "a/b/link",
			linkname:    "../../../outside",
			expectedErr: errSymlinkEscapes,
		},
		{
			// Components that do not exist are walked as if they were directories rather than
			// ending the resolution, so the ".." following them is still accounted for.
			desc:        "target escapes past components that do not exist",
			relPath:     "link",
			linkname:    "nonexistent/../../outside",
			expectedErr: errSymlinkEscapes,
		},
		{
			// "a/up" resolves to the root, so "a/up/.." resolves to the root's parent even
			// though cleaning "a/up/.." lexically yields "a".
			desc: "target escapes through a chained symlink",
			setup: func(t *testing.T, root string) {
				symlink(t, root, "a/up", "..")
			},
			relPath:     "escape",
			linkname:    "a/up/..",
			expectedErr: errSymlinkEscapes,
		},
		{
			desc: "target escapes because the symlink's parent is a symlink",
			setup: func(t *testing.T, root string) {
				require.NoError(t, os.MkdirAll(filepath.Join(root, "real"), mode.Directory))
				symlink(t, root, "linkdir", "real")
			},
			relPath:     "linkdir/link",
			linkname:    "../../outside",
			expectedErr: errSymlinkEscapes,
		},
		{
			desc: "chain traverses an absolute symlink",
			setup: func(t *testing.T, root string) {
				symlink(t, root, "abs", "/etc")
			},
			relPath:     "link",
			linkname:    "abs/passwd",
			expectedErr: errSymlinkEscapes,
		},
		{
			desc: "cyclic chain terminates",
			setup: func(t *testing.T, root string) {
				symlink(t, root, "x", "y")
				symlink(t, root, "y", "x")
			},
			relPath:     "link",
			linkname:    "x",
			expectedErr: syscall.ELOOP,
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			t.Parallel()

			root := t.TempDir()
			if tc.setup != nil {
				tc.setup(t, root)
			}

			err := validateSymlinkWithinRoot(root, tc.relPath, tc.linkname)
			if tc.expectedErr == nil {
				require.NoError(t, err)
				return
			}

			require.ErrorIs(t, err, tc.expectedErr)
			// The rejected symlink is identified in the error.
			require.ErrorContains(t, err, fmt.Sprintf("validating symlink %s -> %s", tc.relPath, tc.linkname))
		})
	}
}

// gitalySSHParams contains parameters used to exec 'gitaly-ssh' binary.
type gitalySSHParams struct {
	arguments   []string
	environment []string
}

// listenGitalySSHCalls creates a script that intercepts 'gitaly-ssh' binary calls.
// It replaces 'gitaly-ssh' with a interceptor script that calls actual binary after flushing env var and
// arguments used for the binary invocation. That information will be returned back to the caller
// after invocation of the returned anonymous function.
func listenGitalySSHCalls(t *testing.T, conf config.Cfg) func() gitalySSHParams {
	t.Helper()

	require.NotEmpty(t, conf.BinDir)
	initialPath := conf.BinaryPath("gitaly-ssh")
	updatedPath := initialPath + "-actual"
	require.NoError(t, os.Rename(initialPath, updatedPath))

	tmpDir := testhelper.TempDir(t)

	script := fmt.Sprintf(`#!/usr/bin/env bash

		# To omit possible problem with parallel run and a race for the file creation with '>'
		# this option is used, please checkout https://mywiki.wooledge.org/NoClobber for more details.
		set -eo noclobber

		env >%[1]q/environment
		echo "$@" >%[1]q/arguments

		exec %[2]q "$@"`, tmpDir, updatedPath)
	require.NoError(t, os.WriteFile(initialPath, []byte(script), mode.Executable))

	return func() gitalySSHParams {
		arguments := testhelper.MustReadFile(t, filepath.Join(tmpDir, "arguments"))
		environment := testhelper.MustReadFile(t, filepath.Join(tmpDir, "environment"))
		return gitalySSHParams{
			arguments:   strings.Split(string(arguments), " "),
			environment: strings.Split(string(environment), "\n"),
		}
	}
}

type testTransactionServer struct {
	gitalypb.UnimplementedRefTransactionServer
	vote func(*gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error)
}

func (s *testTransactionServer) VoteTransaction(ctx context.Context, in *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
	if s.vote != nil {
		return s.vote(in)
	}
	return nil, nil
}