Skip to content

Git designed for AI agents.

repoutil, UserCreateBranch: a contended repository lock and an access-check denial are not internal errors

Federico Elia2af8ca6c8333
diff --git a/cmd/graft/repo.go b/cmd/graft/repo.go
index 897a1db..ee4636a 100644
--- a/cmd/graft/repo.go
+++ b/cmd/graft/repo.go
@@ -10,6 +10,7 @@ import (
"strings"
"google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
"github.com/feder-cr/git-ai/internal/git"
"github.com/feder-cr/git-ai/internal/graft/workspace"
@@ -194,6 +195,10 @@ func repoCreate(ctx context.Context, out io.Writer, o *options, f *repoFlags, ar
// Complete the existing repository below.
case sdk.IsAlreadyExists(err):
return fmt.Errorf("repository %s exists already", displayText(relativePath))
+ case sdk.Code(err) == codes.FailedPrecondition && strings.HasSuffix(status.Convert(err).Message(), "repository is already locked"):
+ // The server's answer while another request creates or removes the
+ // repository (repoutil.Create, wrapped by the handler).
+ return fmt.Errorf("repository %s is being created or removed by another request: %w\nrun the same command again once it is done", displayText(relativePath), err)
default:
return withOperatorHint(err)
}
diff --git a/cmd/graft/repo_test.go b/cmd/graft/repo_test.go
index 255e992..2688b34 100644
--- a/cmd/graft/repo_test.go
+++ b/cmd/graft/repo_test.go
@@ -179,12 +179,15 @@ func TestCLIRepoCreateConverges(t *testing.T) {
}
wg.Wait()
- path := filepath.Join(storagePath, "raced.git")
- tip := strings.TrimSpace(string(gittest.Exec(t, env.cfg, "-C", path, "rev-parse", "refs/heads/main")))
+ // Every run converges on the repository, or fails cleanly because another
+ // run held the repository's lock while creating it.
created, commits := 0, 0
for i := 0; i < runs; i++ {
- require.Equal(t, exitOK, codes[i], "run %d: %s", i, stderrs[i])
- require.Equal(t, tip, results[i].InitialCommit, "run %d", i)
+ if codes[i] != exitOK {
+ require.Equal(t, exitError, codes[i], "run %d: %s", i, stderrs[i])
+ require.Contains(t, stderrs[i], "repository raced.git is being created or removed by another request", "run %d", i)
+ continue
+ }
if results[i].Created {
created++
}
@@ -194,6 +197,20 @@ func TestCLIRepoCreateConverges(t *testing.T) {
}
require.Equal(t, 1, created, "one run created the repository")
require.Equal(t, 1, commits, "one run made the initial commit")
+
+ // The same command afterwards changes nothing.
+ path := filepath.Join(storagePath, "raced.git")
+ tip := strings.TrimSpace(string(gittest.Exec(t, env.cfg, "-C", path, "rev-parse", "refs/heads/main")))
+ code, again, stderr := repoCLI(t, server, "raced.git", "--initial-commit", "--branch", "feature")
+ require.Equal(t, exitOK, code, stderr)
+ require.Equal(t, tip, again.InitialCommit)
+ require.False(t, again.InitialCommitCreated)
+ require.Equal(t, []string{"feature"}, again.BranchesExisting)
+ for i := 0; i < runs; i++ {
+ if codes[i] == exitOK {
+ require.Equal(t, tip, results[i].InitialCommit, "run %d", i)
+ }
+ }
requireRefs(t, env.cfg, path, map[string]string{"refs/heads/main": tip, "refs/heads/feature": tip})
})
}
diff --git a/internal/gitaly/repoutil/create.go b/internal/gitaly/repoutil/create.go
index 45bed45..5750c25 100644
--- a/internal/gitaly/repoutil/create.go
+++ b/internal/gitaly/repoutil/create.go
@@ -190,6 +190,12 @@ func Create(
// vote.
unlock, err := Lock(ctx, logger, locator, repository)
if err != nil {
+ // Another request is creating or removing the repository (or one left a
+ // stale lock): a conflict of the caller, as in Remove, not an internal
+ // error.
+ if errors.Is(err, safe.ErrFileAlreadyLocked) {
+ return structerr.NewFailedPrecondition("repository is already locked")
+ }
return fmt.Errorf("locking repository: %w", err)
}
defer unlock()
diff --git a/internal/gitaly/repoutil/create_test.go b/internal/gitaly/repoutil/create_test.go
index 4547a5c..bb76cbf 100644
--- a/internal/gitaly/repoutil/create_test.go
+++ b/internal/gitaly/repoutil/create_test.go
@@ -23,7 +23,6 @@ import (
"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/helper/text"
- "github.com/feder-cr/git-ai/internal/safe"
"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"
@@ -209,7 +208,7 @@ func TestCreate(t *testing.T) {
requireFullRepackTimestampExists(t, realRepoPath, false)
},
- requireError: equalError(fmt.Errorf("locking repository: %w", safe.ErrFileAlreadyLocked)),
+ requireError: equalError(structerr.NewFailedPrecondition("repository is already locked")),
},
{
desc: "successful transaction",
@@ -290,7 +289,7 @@ func TestCreate(t *testing.T) {
require.NoDirExists(t, tempRepoPath)
require.NoDirExists(t, realRepoPath)
},
- requireError: equalError(fmt.Errorf("locking repository: %w", errors.New("file already locked"))),
+ requireError: equalError(structerr.NewFailedPrecondition("repository is already locked")),
},
func() setup {
var votingRepo *localrepo.Repo
diff --git a/internal/gitaly/service/objectpool/create_test.go b/internal/gitaly/service/objectpool/create_test.go
index b4af369..a0f719b 100644
--- a/internal/gitaly/service/objectpool/create_test.go
+++ b/internal/gitaly/service/objectpool/create_test.go
@@ -250,7 +250,7 @@ func TestCreate_unsuccessful(t *testing.T) {
},
},
},
- expectedErr: structerr.NewInternal("creating object pool: locking repository: file already locked"),
+ expectedErr: structerr.NewFailedPrecondition("creating object pool: repository is already locked"),
},
{
desc: "pool exists",
diff --git a/internal/gitaly/service/operations/user_create_branch.go b/internal/gitaly/service/operations/user_create_branch.go
index 016c661..10ddc15 100644
--- a/internal/gitaly/service/operations/user_create_branch.go
+++ b/internal/gitaly/service/operations/user_create_branch.go
@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/feder-cr/git-ai/internal/git"
+ "github.com/feder-cr/git-ai/internal/gitaly/hook"
"github.com/feder-cr/git-ai/internal/gitaly/hook/updateref"
"github.com/feder-cr/git-ai/internal/gitaly/storage"
"github.com/feder-cr/git-ai/internal/structerr"
@@ -66,6 +67,14 @@ func (s *Server) UserCreateBranch(ctx context.Context, req *gitalypb.UserCreateB
if err := s.updateReferenceWithHooks(ctx, req.GetRepository(), req.GetUser(), quarantineDir, referenceName, startPointOID, objectHash.ZeroOID); err != nil {
var customHookErr updateref.CustomHookError
+ var notAllowedError hook.NotAllowedError
+
+ // An access check that refuses the update (the standalone policy, or GitLab)
+ // is a denial, as in UserDeleteBranch, not an internal error.
+ // UserCreateBranchError has no access check detail.
+ if errors.As(err, &notAllowedError) {
+ return nil, structerr.NewPermissionDenied("creation denied by access checks: %w", err)
+ }
if errors.As(err, &customHookErr) {
return nil, structerr.NewPermissionDenied("creation denied by custom hooks: %w", err).WithDetail(
diff --git a/internal/gitaly/service/operations/user_create_branch_access_test.go b/internal/gitaly/service/operations/user_create_branch_access_test.go
new file mode 100644
index 0000000..e64e01c
--- /dev/null
+++ b/internal/gitaly/service/operations/user_create_branch_access_test.go
@@ -0,0 +1,44 @@
+package operations
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/feder-cr/git-ai/internal/git/gittest"
+ "github.com/feder-cr/git-ai/internal/gitlab"
+ "github.com/feder-cr/git-ai/internal/structerr"
+ "github.com/feder-cr/git-ai/internal/testhelper"
+ "github.com/feder-cr/git-ai/internal/testhelper/testserver"
+ "github.com/feder-cr/git-ai/proto/go/gitalypb"
+)
+
+// TestUserCreateBranch_accessCheck checks that an access check that refuses the
+// new branch is reported as PermissionDenied, as UserDeleteBranch reports it, and
+// that the branch is not created.
+func TestUserCreateBranch_accessCheck(t *testing.T) {
+ t.Parallel()
+
+ ctx := testhelper.Context(t)
+ ctx, cfg, client := setupOperationsService(t, ctx, testserver.WithGitLabClient(
+ gitlab.NewMockClient(t, func(context.Context, gitlab.AllowedParams) (bool, string, error) {
+ return false, "policy denies the branch", nil
+ }, gitlab.MockPreReceive, gitlab.MockPostReceive),
+ ))
+
+ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)
+ commitID := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))
+
+ response, err := client.UserCreateBranch(ctx, &gitalypb.UserCreateBranchRequest{
+ Repository: repo,
+ BranchName: []byte("denied"),
+ StartPoint: []byte(commitID),
+ User: gittest.TestUser,
+ })
+ testhelper.RequireGrpcError(t, structerr.NewPermissionDenied("creation denied by access checks: running pre-receive hooks: GitLab: policy denies the branch"), err)
+ require.Nil(t, response)
+
+ refs := gittest.Exec(t, cfg, "-C", repoPath, "for-each-ref", "--format=%(refname)", "refs/heads/denied")
+ require.Empty(t, refs, "the denied branch is not created")
+}