Git designed for AI agents.
hook, auth: refs/graft/ is reserved for agents in every mode; no upload-archive for agents
Federico Elia2effcce78fa0
diff --git a/doc/graft/AGENT-SECURITY.md b/doc/graft/AGENT-SECURITY.mdindex c288521..97366b4 100644--- a/doc/graft/AGENT-SECURITY.md+++ b/doc/graft/AGENT-SECURITY.md@@ -61,6 +61,8 @@ These can never be enabled, not even through `graft.agent_rpcs`:- `RefService` `UpdateReferences` and `DeleteRefs`.- `RemoteService` `UpdateRemoteMirror`, `FindRemoteRepository` and`FindRemoteRootRef`, which push to or query a URL the caller chooses.+- `SSHService` `SSHUploadArchive`, which reads any revision named in its own+ input, `refs/graft/` included (see below).- `CleanupService`, `ObjectPoolService`, `HookService`, `InternalGitaly`,`PartitionService`, and `StorageCoreService` (imports, checkpoints andgarbage collection, which deletes packs of the bucket).@@ -144,25 +146,36 @@ Whatever the RPC and whatever the policy says, an agent never creates,updates or deletes a reference under `refs/graft/`. The namespace is theserver's: the proposals of a land (`refs/graft/proposals/`, hidden fromadvertisement and push, written by the server) and graft-verify's green-references (written with the shared token). Three layers enforce it, in the-order a write meets them:--1. A push (when an operator opens `SSHReceivePack` or the HTTP push to agents):- `git-receive-pack` runs with `receive.hideRefs=refs/graft/` for agents, so- git refuses the update ("deny updating a hidden ref") before any hook.-2. The RPCs that update references without the pre-receive hook+references (written with the shared token). The reservation is not a rule of+the policy: it holds in every mode, standalone or not, for every agent. The+layers that enforce it, in the order a request meets them:++1. The agent allowlist. `UpdateReferences`, `DeleteRefs` and `WriteRef` are never+ open to agents, and neither is `SSHUploadArchive`: git-upload-archive takes+ the revision to archive in its own input, where the request filter cannot see+ it, and ignores `uploadpack.hideRefs`.+2. The request filter of the agent interceptor (`checkAgentRefs`): a request+ whose revision, reference or pattern fields name `refs/graft/` is refused+ before the RPC runs.+3. On a push (when an operator opens `SSHReceivePack` or the HTTP push to+ agents), `git-receive-pack` runs with `receive.hideRefs=refs/graft/` for+ agents, so git refuses the update ("deny updating a hidden ref") before any+ hook. The RPCs that update references without the pre-receive hook(`UserMergeToRef`, `UserRebaseToRef` when opened with `agent_rpcs`) check the- reservation with the policy before they write (`CheckAgentPolicy`), and- answer `PermissionDenied`. The other agent RPCs write only `refs/heads/`.- `UpdateReferences`, `DeleteRefs` and `WriteRef` are never open to agents.-3. The reference-transaction hook refuses every agent update under- `refs/graft/` while the references are locked, whatever reached it.--`TestPolicyHoldsOnAgentPushes` in `internal/graft/e2e` pins the first layer on a-real push, and `TestPolicyHookDecidesForAgentUpdates` the third one alone (the-real hook, run by `git update-ref` with the payload of an agent's write). The-pre-receive hook judges the policy only; it does not check the reservation,-because no agent write reaches it with a `refs/graft/` update.+ reservation before they write (`CheckAgentPolicy`) and answer+ `PermissionDenied`. The other agent RPCs write branches, the review roots+ (`refs/keep-around/review/`) and, when opened with `agent_rpcs`, tags.+4. The reference-transaction hook refuses every agent update under+ `refs/graft/` while the references are locked, whatever reached it. It sees+ the references git updates, so an update through a symbolic reference whose+ target is under `refs/graft/` is refused too.++`TestPolicyHoldsOnAgentPushes` in `internal/graft/e2e` pins layer 3 on a real+push, and `TestPolicyHookDecidesForAgentUpdates` layer 4 alone (the real hook,+run by `git update-ref` with the payload of an agent's write, a symbolic+reference included), both in standalone mode and outside it. The pre-receive+hook judges the policy only; it does not check the reservation, because no+agent write reaches it with a `refs/graft/` update.Every other RPC that is not on the allowlist (for example the other`OperationService` RPCs such as `UserMergeBranch`, or `SSHService`) is denieddiff --git a/doc/graft/LIMITATIONS.md b/doc/graft/LIMITATIONS.mdindex 580f09f..01f0a00 100644--- a/doc/graft/LIMITATIONS.md+++ b/doc/graft/LIMITATIONS.md@@ -61,11 +61,12 @@ in `internal/graft/e2e` covers the denials end to end, and the tests ofreference-transaction hook.Agents never create, update or delete a reference under `refs/graft/`, whatever-the policy says: that namespace is the server's (land proposals, graft-verify's-references). A push of it is refused by `git-receive-pack`, which hides the-namespace from agents; `UserMergeToRef` and `UserRebaseToRef` refuse it before-they write; and the reference-transaction hook refuses it as the last layer.-See [AGENT-SECURITY](AGENT-SECURITY.md).+the policy says and in every mode, standalone or not: that namespace is the+server's (land proposals, graft-verify's references). The request filter+refuses a request that names it, `git-receive-pack` hides it from agents on a+push, `UserMergeToRef` and `UserRebaseToRef` refuse it before they write, and+the reference-transaction hook refuses it as the last layer, also through a+symbolic reference. See [AGENT-SECURITY](AGENT-SECURITY.md).The policy governs the references under `refs/` and the `HEAD` symbolicreference, so an agent cannot repoint `HEAD` to get around a protected branch.@@ -95,6 +96,7 @@ they are rejected with `PermissionDenied` and need the shared token:- `RefService`: `UpdateReferences`, `DeleteRefs`;- `RemoteService`: `UpdateRemoteMirror`, `FindRemoteRepository`,`FindRemoteRootRef` (they push to or query a URL the caller chooses);+- `SSHService`: `SSHUploadArchive` (it reads any revision its input names);- every RPC of `HookService`, `ObjectPoolService`, `CleanupService`,`PartitionService`, `InternalGitaly` and `StorageCoreService`.diff --git a/internal/gitaly/hook/referencetransaction.go b/internal/gitaly/hook/referencetransaction.goindex 459e6e4..e323abe 100644--- a/internal/gitaly/hook/referencetransaction.go+++ b/internal/gitaly/hook/referencetransaction.go@@ -456,7 +456,8 @@ func (m *GitLabHookManager) trackPendingTransaction(state ReferenceTransactionSt// refs/ and HEAD, so that a symbolic update of the default branch is decided// like any other update. Other pseudo-references are not governed.//-// Outside standalone mode, or with an empty policy, it does nothing.+// The reservation of refs/graft/ (GraftReservedRefPrefix) applies to agents in every mode; the+// rest of the policy applies only in standalone mode with a policy.func (m *GitLabHookManager) enforceGraftPolicy(ctx context.Context, env []string, changes []byte) error {message, err := m.graftPolicyDecision(env, changes)if err != nil {@@ -468,7 +469,7 @@ func (m *GitLabHookManager) enforceGraftPolicy(ctx context.Context, env []stringm.logger.WithFields(log.Fields{"actor": meta.Actor,"reason": message,- }).InfoContext(ctx, "standalone policy denied reference transaction")+ }).InfoContext(ctx, "agent reference update denied")return structerr.NewPermissionDenied("%s", message)}@@ -480,15 +481,13 @@ func (m *GitLabHookManager) enforceGraftPolicy(ctx context.Context, env []string// denial of the transaction, or an empty message when the policy allows it or// does not apply to it.func (m *GitLabHookManager) graftPolicyDecision(env []string, changes []byte) (string, error) {- if !m.cfg.Graft.Standalone {- return "", nil- }+ policyApplies := m.cfg.Graft.Standalone && len(m.cfg.Graft.Policy) > 0meta, err := gitcmd.ChangelogMetaFromEnv(env)if err != nil {- if len(m.cfg.Graft.Policy) == 0 {- // Without a policy the metadata decides nothing but the reservation of refs/graft/,- // which needs an agent the metadata names.+ // The metadata names the agent of the update. Without agents and without a policy to+ // apply there is nothing to decide; otherwise the update cannot be judged.+ if !policyApplies && len(m.cfg.Graft.Agents) == 0 {return "", nil}return "", fmt.Errorf("reading graft metadata: %w", err)@@ -514,11 +513,13 @@ func (m *GitLabHookManager) graftPolicyDecision(env []string, changes []byte) (sreturn "", nil}- // refs/graft/ is the server's, whatever the policy says.+ // refs/graft/ is the server's, whatever the policy says and whether or not the server runs+ // in standalone mode: it is not a rule of the policy but an invariant of the server, for+ // every agent.if message := graftReservedDenial(changes); message != "" {return message, nil}- if len(m.cfg.Graft.Policy) == 0 {+ if !policyApplies {return "", nil}@@ -538,21 +539,19 @@ func (m *GitLabHookManager) graftPolicyDecision(env []string, changes []byte) (s// checks it first to return the policy message with PermissionDenied.//// Like enforceGraftPolicy, it decides only for a caller that authenticated with-// a per-agent token, outside standalone mode or with an empty policy it does-// nothing, and the decision is final: the hook still runs afterwards.+// a per-agent token: the reservation of refs/graft/ in every mode, the rest of+// the policy only in standalone mode with a policy. The hook still runs+// afterwards.func CheckAgentPolicy(ctx context.Context, graft config.Graft, changes string) error {- if !graft.Standalone {- return nil- }-id, ok := identity.FromContext(ctx)if !ok || id.Source != identity.SourceAgent {return nil}+ // The reservation of refs/graft/ holds in every mode, as in the hook.if message := graftReservedDenial([]byte(changes)); message != "" {return structerr.NewPermissionDenied("%s", message)}- if len(graft.Policy) == 0 {+ if !graft.Standalone || len(graft.Policy) == 0 {return nil}@@ -599,7 +598,11 @@ func graftPolicyDenial(policy []config.GraftPolicyRule, actor string, changes []// GraftReservedRefPrefix is the namespace of the references that only the server writes: the// proposals of a land (refs/graft/proposals/) and graft-verify's green references, which it// writes with the shared token. An agent never creates, updates or deletes a reference under it,-// whatever the policy says, by any RPC or a push: the reference-transaction hook refuses it.+// whatever the policy says and in every mode. The layers that refuse it, in the order a write+// meets them: the request filter of the agent interceptor (a request that names it), git's+// receive.hideRefs on a push, CheckAgentPolicy in the RPCs that skip the pre-receive hook, and+// last the reference-transaction hook (graftPolicyDecision), which sees the references git+// actually updates, the target of a symbolic reference included. See doc/graft/AGENT-SECURITY.md.const GraftReservedRefPrefix = "refs/graft/"// graftReservedDenial returns the denial of changes that update a reference underdiff --git a/internal/gitaly/hook/referencetransaction_policy_test.go b/internal/gitaly/hook/referencetransaction_policy_test.goindex e746535..ee8d970 100644--- a/internal/gitaly/hook/referencetransaction_policy_test.go+++ b/internal/gitaly/hook/referencetransaction_policy_test.go@@ -10,6 +10,7 @@ import ("github.com/feder-cr/git-ai/internal/git/gitcmd""github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/feder-cr/git-ai/internal/graft/identity""github.com/feder-cr/git-ai/internal/testhelper""github.com/stretchr/testify/require""google.golang.org/grpc/codes"@@ -231,7 +232,60 @@ func TestEnforceGraftPolicy_refsGraftIsReserved(t *testing.T) {require.NoError(t, m.enforceGraftPolicy(ctx, policyEnv(t, "agent-a", true), policyChanges("refs/heads/main")), name)}- // Outside standalone mode nothing is decided here.- m := graftPolicyManager(t, config.Graft{})- require.NoError(t, m.enforceGraftPolicy(ctx, policyEnv(t, "agent-a", true), policyChanges("refs/graft/green/main")))+ // Outside standalone mode the reservation still holds for agents: it is an invariant of the+ // server, not a rule of the policy. The policy itself does not apply there.+ for name, graft := range map[string]config.Graft{+ "not standalone": {Agents: []config.GraftAgent{{Name: "agent-a"}}},+ "not standalone, a policy": {Agents: []config.GraftAgent{{Name: "agent-a"}}, Policy: []config.GraftPolicyRule{{Allow: false}}},+ "standalone, policy denies": {Standalone: true, Policy: []config.GraftPolicyRule{{Allow: false}}},+ } {+ m := graftPolicyManager(t, graft)+ err := m.enforceGraftPolicy(ctx, policyEnv(t, "agent-a", true), policyChanges("refs/graft/green/main"))+ require.Equal(t, codes.PermissionDenied, status.Code(err), name)+ require.ErrorContains(t, err, "reserved for the server", name)+ require.NoError(t, m.enforceGraftPolicy(ctx, policyEnv(t, "", false), policyChanges("refs/graft/green/main")), name)+ }+ m := graftPolicyManager(t, config.Graft{Agents: []config.GraftAgent{{Name: "agent-a"}}, Policy: []config.GraftPolicyRule{{Allow: false}}})+ require.NoError(t, m.enforceGraftPolicy(ctx, policyEnv(t, "agent-a", true), policyChanges("refs/heads/main")),+ "outside standalone mode the policy does not apply")+}++// TestCheckAgentPolicy checks the policy check of the RPCs that skip the pre-receive hook: the+// reservation of refs/graft/ refuses an agent in every mode, the rest of the policy only in+// standalone mode, and callers that are not agents are not restricted.+func TestCheckAgentPolicy(t *testing.T) {+ t.Parallel()++ agentCtx := identity.NewContext(testhelper.Context(t), identity.Identity{Name: "agent-a", Source: identity.SourceAgent})+ deny := []config.GraftPolicyRule{{Allow: false}}+ reserved := fmt.Sprintf("%s %s refs/graft/green/main\n", policyOldOID, policyNewOID)+ branch := fmt.Sprintf("%s %s refs/heads/main\n", policyOldOID, policyNewOID)++ for name, graft := range map[string]config.Graft{+ "standalone": {Standalone: true, Policy: deny},+ "not standalone": {Policy: deny},+ } {+ err := CheckAgentPolicy(agentCtx, graft, reserved)+ require.Equal(t, codes.PermissionDenied, status.Code(err), name)+ require.ErrorContains(t, err, "reserved for the server", name)+ require.NoError(t, CheckAgentPolicy(testhelper.Context(t), graft, reserved), "%s: not an agent", name)+ }++ err := CheckAgentPolicy(agentCtx, config.Graft{Standalone: true, Policy: deny}, branch)+ require.Equal(t, codes.PermissionDenied, status.Code(err))+ require.NoError(t, CheckAgentPolicy(agentCtx, config.Graft{Policy: deny}, branch), "outside standalone mode the policy does not apply")+}++// TestEnforceGraftPolicy_missingMetadataWithAgents: an update whose metadata cannot be read cannot be+// told apart from an agent's, so it is refused whenever agents are configured, in every mode; without+// agents and without a policy to apply there is nothing to decide.+func TestEnforceGraftPolicy_missingMetadataWithAgents(t *testing.T) {+ t.Parallel()++ ctx := testhelper.Context(t)+ agents := []config.GraftAgent{{Name: "agent-a"}}+ require.Error(t, graftPolicyManager(t, config.Graft{Agents: agents}).enforceGraftPolicy(ctx, nil, policyChanges("refs/heads/main")))+ require.Error(t, graftPolicyManager(t, config.Graft{Standalone: true, Agents: agents}).enforceGraftPolicy(ctx, nil, policyChanges("refs/heads/main")))+ require.NoError(t, graftPolicyManager(t, config.Graft{}).enforceGraftPolicy(ctx, nil, policyChanges("refs/heads/main")))+ require.NoError(t, graftPolicyManager(t, config.Graft{Standalone: true}).enforceGraftPolicy(ctx, nil, policyChanges("refs/heads/main")))}diff --git a/internal/gitaly/server/auth/agent_allowlist_test.go b/internal/gitaly/server/auth/agent_allowlist_test.goindex 6ffecd6..8c8f6d7 100644--- a/internal/gitaly/server/auth/agent_allowlist_test.go+++ b/internal/gitaly/server/auth/agent_allowlist_test.go@@ -150,6 +150,7 @@ func TestAgentAllowlist_EveryRegisteredRPC(t *testing.T) {require.Positive(t, allowed)for _, fullMethod := range []string{+ gitalypb.SSHService_SSHUploadArchive_FullMethodName,gitalypb.RepositoryService_WriteRef_FullMethodName,gitalypb.RefService_DeleteRefs_FullMethodName,gitalypb.RefService_UpdateReferences_FullMethodName,@@ -349,6 +350,7 @@ func TestNewAgentAllowlist_Validation(t *testing.T) {{desc: "backup repository", rpcs: []string{gitalypb.RepositoryService_BackupRepository_FullMethodName}, wantErr: "may never be called by an agent"},{desc: "ssh upload-pack is opt-in only", rpcs: []string{gitalypb.SSHService_SSHUploadPackWithSidechannel_FullMethodName}},{desc: "ssh receive-pack is opt-in only", rpcs: []string{gitalypb.SSHService_SSHReceivePack_FullMethodName}},+ {desc: "ssh upload-archive", rpcs: []string{gitalypb.SSHService_SSHUploadArchive_FullMethodName}, wantErr: "may never be called by an agent"},{desc: "hook callback", rpcs: []string{gitalypb.HookService_PreReceiveHook_FullMethodName}, wantErr: "may never be called by an agent"},{desc: "object pool", rpcs: []string{gitalypb.ObjectPoolService_DeleteObjectPool_FullMethodName}, wantErr: "may never be called by an agent"},{desc: "cleanup service", rpcs: []string{gitalypb.CleanupService_RewriteHistory_FullMethodName}, wantErr: "may never be called by an agent"},diff --git a/internal/gitaly/server/auth/agent_methods.go b/internal/gitaly/server/auth/agent_methods.goindex e40a6c4..d97ae1d 100644--- a/internal/gitaly/server/auth/agent_methods.go+++ b/internal/gitaly/server/auth/agent_methods.go@@ -65,7 +65,15 @@ var agentNeverAllowedServices = []string{// authorization header and a resolved address that pins DNS. Like// CreateRepositoryFromURL, they would let an agent make the server send requests// to any address, including internal ones (server-side request forgery).+//+// SSHService.SSHUploadArchive runs git-upload-archive, which takes the revision+// to archive in its own pkt-line input, not in a field of the request, and does+// not honour uploadpack.hideRefs. The request filter cannot see that revision,+// so an agent could read refs/graft/ by name with `git archive --remote`. No+// graft client needs it (RepositoryService.GetArchive names its revision in a+// field the filter checks), so it is never allowed rather than parsed.var agentNeverAllowedMethods = map[string]struct{}{+ gitalypb.SSHService_SSHUploadArchive_FullMethodName: {},gitalypb.RemoteService_UpdateRemoteMirror_FullMethodName: {},gitalypb.RemoteService_FindRemoteRepository_FullMethodName: {},gitalypb.RemoteService_FindRemoteRootRef_FullMethodName: {},diff --git a/internal/gitaly/server/auth/agent_refs_test.go b/internal/gitaly/server/auth/agent_refs_test.goold mode 100755new mode 100644index cdfb9a5..004e79e--- a/internal/gitaly/server/auth/agent_refs_test.go+++ b/internal/gitaly/server/auth/agent_refs_test.go@@ -99,6 +99,8 @@ func TestCheckAgentRefs(t *testing.T) {"ListBlobs, a name after a line": {&gitalypb.ListBlobsRequest{Revisions: []string{"--glob=x\nrefs/graft/green/main"}}, true},"ListCommits, a name after a CR": {&gitalypb.ListCommitsRequest{Revisions: []string{"--glob=x\rrefs/graft/green/main"}}, true},"ListCommits, a name after a NUL": {&gitalypb.ListCommitsRequest{Revisions: []string{"--glob=x\x00refs/graft/green/main"}}, true},+ "GetArchive of a proposal": {&gitalypb.GetArchiveRequest{CommitId: "refs/graft/proposals/0123456789abcdef/1"}, true},+ "GetArchive of a branch": {&gitalypb.GetArchiveRequest{CommitId: "main"}, false},} {err := checkAgentRefs(agentContext(), tc.req)if tc.denied {diff --git a/internal/graft/e2e/e2e_test.go b/internal/graft/e2e/e2e_test.goindex 52b499d..a9baa73 100644--- a/internal/graft/e2e/e2e_test.go+++ b/internal/graft/e2e/e2e_test.go@@ -146,11 +146,21 @@ func startExampleUnbatched(t *testing.T) gitalyStack {func startGitaly(t *testing.T, graft config.Graft, sharedToken string, opts ...testserver.GitalyServerOpt) gitalyStack {t.Helper()+ return startGitalyInMode(t, graft, sharedToken, true, opts...)+}++// startGitalyInMode is startGitaly with standalone mode on or off. Off, the agents of+// graft still authenticate, but the request defaults and the policy of standalone+// mode do not apply; the access checks of the pre-receive hook still go to the+// standalone client, which stands in for GitLab here.+func startGitalyInMode(t *testing.T, graft config.Graft, sharedToken string, standalone bool, opts ...testserver.GitalyServerOpt) gitalyStack {+ t.Helper()+ctx := featureflag.OutgoingCtxWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false)cfg := testcfg.Build(t)cfg.Auth.Token = sharedTokencfg.Graft = graft- cfg.Graft.Standalone = true+ cfg.Graft.Standalone = standalonetestcfg.BuildGitalySSH(t, cfg)testcfg.BuildGitalyHooks(t, cfg)diff --git a/internal/graft/e2e/policy_hook_test.go b/internal/graft/e2e/policy_hook_test.goindex 697ddd5..6be86ca 100644--- a/internal/graft/e2e/policy_hook_test.go+++ b/internal/graft/e2e/policy_hook_test.go@@ -1,6 +1,7 @@package e2eimport (+ "fmt""strings""testing"@@ -20,12 +21,17 @@ import (// own: the real reference-transaction hook (git runs the gitaly-hooks binary,// which calls the server's HookService), run by git update-ref with the hooks// payload that the server builds for a write of an agent, as for an RPC or a-// push. The earlier layers (the pre-receive hook, CheckAgentPolicy, the agents'-// receive.hideRefs) do not take part, so the hook decides alone:+// push. The earlier layers (the request filter, the pre-receive hook,+// CheckAgentPolicy, the agents' receive.hideRefs) do not take part, so the hook+// decides alone:// - refs/graft/x is refused although the policy lets the builder update-// refs/graft/** (startWithAgentPushes), because that namespace is the server's;+// refs/graft/** (startWithAgentPushes), because that namespace is the+// server's, in standalone mode and outside it;+// - so is an update through a symbolic reference whose target is under+// refs/graft/: the hook sees the target;// - a branch the policy allows is written;-// - a branch the policy denies (main for the builder) is refused.+// - a branch the policy denies (main for the builder) is refused in standalone+// mode, and written outside it, where the policy does not apply.//// git only reports that the hook aborted the transaction, so the reason of each// refusal is read from the hook's log entry in the server. TestPolicyHoldsOnAgentPushes@@ -33,9 +39,18 @@ import (func TestPolicyHookDecidesForAgentUpdates(t *testing.T) {t.Parallel()+ for _, standalone := range []bool{true, false} {+ t.Run(fmt.Sprintf("standalone=%t", standalone), func(t *testing.T) {+ t.Parallel()+ testPolicyHookDecidesForAgentUpdates(t, standalone)+ })+ }+}++func testPolicyHookDecidesForAgentUpdates(t *testing.T, standalone bool) {logger := testhelper.NewLogger(t)logs := testhelper.AddLoggerHook(logger)- s := startWithAgentPushes(t, testserver.WithLogger(logger))+ s := startWithAgentPushes(t, standalone, testserver.WithLogger(logger))mainCommit := writeMain(t, s, map[string]string{"README.md": "hook\n"})next := gittest.WriteCommit(t, s.cfg, s.repoPath, gittest.WithParents(git.ObjectID(mainCommit)), gittest.WithMessage("next"))@@ -60,11 +75,11 @@ func TestPolicyHookDecidesForAgentUpdates(t *testing.T) {}return commitErr}- // hookDenials returns the reasons of the hook's policy denials logged so far.+ // hookDenials returns the reasons of the hook's denials logged so far.hookDenials := func() []string {var reasons []stringfor _, entry := range logs.AllEntries() {- if entry.Message == "standalone policy denied reference transaction" {+ if entry.Message == "agent reference update denied" {reasons = append(reasons, entry.Data["reason"].(string))}}@@ -76,13 +91,29 @@ func TestPolicyHookDecidesForAgentUpdates(t *testing.T) {require.Equal(t, next.String(), s.git(t, "rev-parse", "refs/heads/feature/hook"))require.Empty(t, hookDenials())- require.Error(t, update("refs/heads/main", next, git.ObjectID(mainCommit)))- require.Equal(t, mainCommit, s.git(t, "rev-parse", "refs/heads/main"))- require.Equal(t, []string{`policy denies "builder" to update "refs/heads/main" (rule 3)`}, hookDenials())+ var want []string+ if standalone {+ require.Error(t, update("refs/heads/main", next, git.ObjectID(mainCommit)))+ require.Equal(t, mainCommit, s.git(t, "rev-parse", "refs/heads/main"))+ want = append(want, `policy denies "builder" to update "refs/heads/main" (rule 3)`)+ } else {+ require.NoError(t, update("refs/heads/main", next, git.ObjectID(mainCommit)))+ require.Equal(t, next.String(), s.git(t, "rev-parse", "refs/heads/main"))+ }+ require.Equal(t, want, hookDenials())require.Error(t, update("refs/graft/x", next, zero))require.Empty(t, s.git(t, "for-each-ref", "refs/graft/"))++ // A symbolic reference to refs/graft/x, which only the server could have made: the+ // update of the symbolic reference writes its target, and the hook refuses that.+ s.git(t, "symbolic-ref", "refs/heads/alias", "refs/graft/x")+ require.Error(t, update("refs/heads/alias", next, zero))+ require.Empty(t, s.git(t, "for-each-ref", "refs/graft/"))+denials := hookDenials()- require.Len(t, denials, 2)- require.True(t, strings.HasPrefix(denials[1], `"refs/graft/x" is under refs/graft/, which is reserved for the server`), denials[1])+ require.Len(t, denials, len(want)+2)+ for _, denial := range denials[len(want):] {+ require.True(t, strings.HasPrefix(denial, `"refs/graft/x" is under refs/graft/, which is reserved for the server`), denial)+ }}diff --git a/internal/graft/e2e/policy_push_test.go b/internal/graft/e2e/policy_push_test.goindex 1f329af..8124209 100644--- a/internal/graft/e2e/policy_push_test.go+++ b/internal/graft/e2e/policy_push_test.go@@ -21,7 +21,7 @@ import (// opened to agents through [graft] agent_rpcs, the operator opt-in of// AGENT-SECURITY.md, and a policy that also lets the builder update// refs/graft/**, so that only the reservation of that namespace can refuse it.-func startWithAgentPushes(t *testing.T, opts ...testserver.GitalyServerOpt) gitalyStack {+func startWithAgentPushes(t *testing.T, standalone bool, opts ...testserver.GitalyServerOpt) gitalyStack {t.Helper()ex := loadExample(t)@@ -30,7 +30,7 @@ func startWithAgentPushes(t *testing.T, opts ...testserver.GitalyServerOpt) gita{Actor: "builder", Refs: []string{"refs/graft/**"}, Allow: true},}, ex.graft.Policy...)- return startGitaly(t, ex.graft, ex.sharedToken, opts...)+ return startGitalyInMode(t, ex.graft, ex.sharedToken, standalone, opts...)}// agentPush pushes refspec from the client repository at clientPath to the@@ -73,11 +73,21 @@ func agentPush(t *testing.T, s gitalyStack, clientPath, token, agent, refspec st// accepted, and one it denies is refused by the policy in the pre-receive hook.// refs/graft/ is reserved for the server whatever the policy says: the builder// may update refs/graft/** by policy here, and git-receive-pack still refuses its-// push there, because that namespace is hidden from agents.+// push there, because that namespace is hidden from agents. The reservation is+// not a rule of the policy: it holds outside standalone mode too.func TestPolicyHoldsOnAgentPushes(t *testing.T) {t.Parallel()- s := startWithAgentPushes(t)+ for _, standalone := range []bool{true, false} {+ t.Run(fmt.Sprintf("standalone=%t", standalone), func(t *testing.T) {+ t.Parallel()+ testPolicyHoldsOnAgentPushes(t, standalone)+ })+ }+}++func testPolicyHoldsOnAgentPushes(t *testing.T, standalone bool) {+ s := startWithAgentPushes(t, standalone)base := writeMain(t, s, map[string]string{"README.md": "push\n"})clientPath := filepath.Join(t.TempDir(), "client")@@ -94,11 +104,14 @@ func TestPolicyHoldsOnAgentPushes(t *testing.T) {require.True(t, ok, out)require.Equal(t, pushed, s.git(t, "rev-parse", "refs/heads/feature/pushed"))- // A branch the policy denies is refused by the policy.- out, ok = agentPush(t, s, clientPath, builder, "builder", "HEAD:refs/heads/main")- require.False(t, ok, out)- require.Contains(t, out, `policy denies "builder" to update "refs/heads/main" (rule 3)`)- require.Equal(t, base, s.git(t, "rev-parse", "refs/heads/main"))+ // A branch the policy denies is refused by the policy. Outside standalone mode+ // that decision is GitLab's, which the test does not run.+ if standalone {+ out, ok = agentPush(t, s, clientPath, builder, "builder", "HEAD:refs/heads/main")+ require.False(t, ok, out)+ require.Contains(t, out, `policy denies "builder" to update "refs/heads/main" (rule 3)`)+ require.Equal(t, base, s.git(t, "rev-parse", "refs/heads/main"))+ }// refs/graft/ is the server's, although the policy allows the builder there:// git-receive-pack hides it from agents (receive.hideRefs), so git refuses the