Git designed for AI agents.
graft: the four readers of the policy decide with the policy store
Federico Elia94860217e141
diff --git a/internal/cli/gitaly/policy_reload.go b/internal/cli/gitaly/policy_reload.gonew file mode 100644index 0000000..61768f6--- /dev/null+++ b/internal/cli/gitaly/policy_reload.go@@ -0,0 +1,82 @@+package gitaly++import (+ "os"+ "os/signal"+ "syscall"++ "github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/feder-cr/git-ai/internal/graft/policystore"+ "github.com/feder-cr/git-ai/internal/log"+)++// policyReloadSignal reloads the standalone access policy from the configuration file. SIGHUP is+// taken: the default bootstrap shuts down on it and the tableflip bootstrap upgrades+// (doc/graft/PLAN12.md, section 4).+var policyReloadSignal = syscall.SIGUSR1++// reloadPolicyOnSignal reloads the policy of store from the configuration file at configPath every+// time the process receives policyReloadSignal, one reload at a time. running is the [graft]+// section the server started with. The returned function stops it.+func reloadPolicyOnSignal(logger log.Logger, configPath string, running config.Graft, store *policystore.Store) func() {+ signals := make(chan os.Signal, 1)+ done := make(chan struct{})+ signal.Notify(signals, policyReloadSignal)++ go func() {+ defer close(done)+ for range signals {+ reloadPolicy(logger, configPath, running, store)+ }+ }()++ return func() {+ signal.Stop(signals)+ close(signals)+ <-done+ }+}++// reloadPolicy reads the configuration file at configPath again and puts its policy in force when it+// is valid; otherwise the policy in force stays. The outcome is logged: an invalid configuration at+// ERROR, a new policy at INFO, and the changes that need a restart and the actors that name no+// configured agent at WARN.+func reloadPolicy(logger log.Logger, configPath string, running config.Graft, store *policystore.Store) policystore.Outcome {+ logger = logger.WithField("config_path", configPath)++ next, err := loadConfig(configPath)+ var outcome policystore.Outcome+ if err != nil {+ outcome = store.Reject()+ } else {+ outcome, err = store.Reload(next.Graft, running)+ }+ if err != nil {+ logger.WithError(err).WithFields(log.Fields{+ "generation": outcome.Current.Generation,+ "sha256": outcome.Current.SHA256,+ }).Error("policy reload rejected: the policy in force stays")+ return outcome+ }++ fields := log.Fields{+ "generation": outcome.Current.Generation,+ "sha256": outcome.Current.SHA256,+ "rules": len(outcome.Current.Rules),+ }+ switch outcome.Result {+ case policystore.Applied:+ fields["previous_generation"] = outcome.Previous.Generation+ fields["previous_sha256"] = outcome.Previous.SHA256+ logger.WithFields(fields).Info("policy reloaded")+ default:+ logger.WithFields(fields).Info("policy reload: the policy is unchanged")+ }+ if len(outcome.NeedsRestart) > 0 {+ logger.WithField("needs_restart", outcome.NeedsRestart).Warn("policy reload: the configuration changed outside the policy; those changes need a restart and were not applied")+ }+ if len(outcome.UnknownActors) > 0 {+ logger.WithField("actors", outcome.UnknownActors).Warn("policy reload: actors of the policy that name no configured agent (user IDs of callers with the shared token?)")+ }+ return outcome+}diff --git a/internal/cli/gitaly/serve.go b/internal/cli/gitaly/serve.goindex dcd1c5f..a53aa2e 100644--- a/internal/cli/gitaly/serve.go+++ b/internal/cli/gitaly/serve.go@@ -50,6 +50,7 @@ import (_ "github.com/feder-cr/git-ai/internal/graft/derived/graph" // registers the graph warmer"github.com/feder-cr/git-ai/internal/graft/eager""github.com/feder-cr/git-ai/internal/graft/landlane"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/graft/resolver""github.com/feder-cr/git-ai/internal/grpc/backchannel""github.com/feder-cr/git-ai/internal/grpc/client"@@ -216,10 +217,10 @@ func configure(configPath string) (config.Cfg, log.Logger, error) {// callbacks. In Graft standalone mode it is the built-in policy client and// GitLab is never contacted. Otherwise it is the stub client when hooks are// bypassed for testing, and the GitLab HTTP client in all other cases.-func newGitlabAPIClient(logger log.Logger, cfg config.Cfg) (gitlab.Client, error) {+func newGitlabAPIClient(logger log.Logger, cfg config.Cfg, policy *policystore.Store) (gitlab.Client, error) {if cfg.Graft.Standalone {logger.Info("graft standalone mode: access checks use the built-in policy, GitLab is not contacted")- return gitlab.NewStandaloneClient(cfg.Graft, logger), nil+ return gitlab.NewStandaloneClientWithPolicy(policy, logger), nil}if skipHooks, _ := env.GetBool("GITALY_TESTING_NO_GIT_HOOKS", false); skipHooks {@@ -584,7 +585,14 @@ func run(appCtx *cli.Command, cfg config.Cfg, logger log.Logger) error {mvccMiddleware,)- gitlabClient, err := newGitlabAPIClient(logger, cfg)+ // The standalone access policy is held by one store, which every reader decides with and+ // SIGUSR1 reloads from the configuration file (doc/graft/PLAN12.md).+ graftPolicy := policystore.New(cfg.Graft.Policy)+ prometheus.MustRegister(graftPolicy)+ stopPolicyReload := reloadPolicyOnSignal(logger, appCtx.Args().First(), cfg.Graft, graftPolicy)+ defer stopPolicyReload()++ gitlabClient, err := newGitlabAPIClient(logger, cfg, graftPolicy)if err != nil {return err}@@ -621,7 +629,7 @@ func run(appCtx *cli.Command, cfg config.Cfg, logger log.Logger) error {// storage core.prometheus.MustRegister(reviewroots.DefaultSweeper)- hookManagerOpts := []hook.ManagerOption{hook.WithEagerObserver(eagerObserver)}+ hookManagerOpts := []hook.ManagerOption{hook.WithEagerObserver(eagerObserver), hook.WithPolicyStore(graftPolicy)}var (storageSyncer corestore.FreshenerstorageGate *gate.Gate@@ -832,6 +840,7 @@ func run(appCtx *cli.Command, cfg config.Cfg, logger log.Logger) error {ArchiveCache: archiveStreamCache,PoolMetadataStore: poolMetadataStore,GitlabClient: gitlabClient,+ GraftPolicy: graftPolicy,ObjectPoolStateManager: objectPoolStateManager,PostReceiveRegistry: postReceiveRegistry,GraftLandLanes: landLanes,diff --git a/internal/cli/gitaly/serve_test.go b/internal/cli/gitaly/serve_test.goindex ebc0192..8fc9fe1 100644--- a/internal/cli/gitaly/serve_test.go+++ b/internal/cli/gitaly/serve_test.go@@ -6,6 +6,7 @@ import ("github.com/feder-cr/git-ai/internal/git""github.com/feder-cr/git-ai/internal/gitaly/config""github.com/feder-cr/git-ai/internal/gitlab"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/testhelper""github.com/prometheus/client_golang/prometheus""github.com/stretchr/testify/require"@@ -33,7 +34,7 @@ func TestNewGitlabAPIClient_Standalone(t *testing.T) {},}- client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg)+ client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg, policystore.New(cfg.Graft.Policy))require.NoError(t, err)// The policy is enforced by the built-in client.@@ -62,7 +63,7 @@ func TestNewGitlabAPIClient_StandaloneTakesPrecedenceOverBypass(t *testing.T) {},}- client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg)+ client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg, policystore.New(cfg.Graft.Policy))require.NoError(t, err)allowed, _, err := client.Allowed(testhelper.Context(t), gitlab.AllowedParams{@@ -76,7 +77,7 @@ func TestNewGitlabAPIClient_StandaloneTakesPrecedenceOverBypass(t *testing.T) {func TestNewGitlabAPIClient_BypassUsesStubClient(t *testing.T) {t.Setenv("GITALY_TESTING_NO_GIT_HOOKS", "true")- client, err := newGitlabAPIClient(testhelper.SharedLogger(t), config.Cfg{})+ client, err := newGitlabAPIClient(testhelper.SharedLogger(t), config.Cfg{}, policystore.New(nil))require.NoError(t, err)// The stub client does not connect to the internal API, so Check fails.@@ -98,7 +99,7 @@ func TestNewGitlabAPIClient_HTTPClient(t *testing.T) {},}- client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg)+ client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg, policystore.New(cfg.Graft.Policy))require.NoError(t, err)httpClient, ok := client.(*gitlab.HTTPClient)@@ -121,7 +122,7 @@ func TestNewGitlabAPIClient_HTTPClientConfigurationError(t *testing.T) {},}- client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg)+ client, err := newGitlabAPIClient(testhelper.SharedLogger(t), cfg, policystore.New(cfg.Graft.Policy))require.Error(t, err)require.Contains(t, err.Error(), "could not create GitLab API client")require.Nil(t, client)diff --git a/internal/git/gitcmd/hooks_payload.go b/internal/git/gitcmd/hooks_payload.goindex 99394d1..246451a 100644--- a/internal/git/gitcmd/hooks_payload.go+++ b/internal/git/gitcmd/hooks_payload.go@@ -18,6 +18,7 @@ import ("github.com/feder-cr/git-ai/internal/gitaly/storage""github.com/feder-cr/git-ai/internal/graft/changelog""github.com/feder-cr/git-ai/internal/graft/identity"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/grpc/metadata""github.com/feder-cr/git-ai/internal/log""github.com/feder-cr/git-ai/internal/transaction/txinfo"@@ -155,6 +156,12 @@ type ChangelogMeta struct {// the request has no MVCC cache that it commits, or when the changeset log is// disabled.MVCCCommit string `json:"mvcc_commit,omitempty"`+ // PolicyGeneration is the generation of the standalone access policy under which a land+ // batch admitted its members (policystore.WithAdmissionGeneration). The+ // reference-transaction hook refuses the batch's update when the policy in force is another+ // one (doc/graft/PLAN12.md, section 5). Only the server builds it from the context, like+ // Members.+ PolicyGeneration uint64 `json:"policy_generation,omitempty"`// Members lists the changes that a batched land folded into the updates, in// the order they were landed (see changelog.WithBatch). The list is capped at// maxChangelogMembersSize. Only the server builds it from the context, so a@@ -302,6 +309,7 @@ func NewHooksPayload(LandReference: landReference,Lands: lands,MVCCCommit: mvccCommitHandle(ctx, cfg),+ PolicyGeneration: policystore.AdmissionGeneration(ctx),},}}diff --git a/internal/gitaly/hook/manager.go b/internal/gitaly/hook/manager.goindex de80d7b..d026a7e 100644--- a/internal/gitaly/hook/manager.go+++ b/internal/gitaly/hook/manager.go@@ -12,6 +12,7 @@ import ("github.com/feder-cr/git-ai/internal/gitaly/transaction""github.com/feder-cr/git-ai/internal/gitlab""github.com/feder-cr/git-ai/internal/graft/eager"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/helper""github.com/feder-cr/git-ai/internal/log""github.com/feder-cr/git-ai/proto/go/gitalypb"@@ -85,6 +86,9 @@ type GitLabHookManager struct {// observer receives the committed reference updates, see// ReferenceTransactionHook. A nil observer does nothing.observer *eager.Observer+ // policy holds the standalone access policy in force (doc/graft/PLAN12.md). It is never nil:+ // without WithPolicyStore it holds the policy of cfg.+ policy *policystore.Store// storageVoter commits reference transactions to the Graft storage core, nil when it is off.storageVoter StorageVoter// startLandIntentsCompaction starts a compaction of land intents that a prepared@@ -105,6 +109,15 @@ func WithEagerObserver(observer *eager.Observer) ManagerOption {}}+// WithPolicyStore sets the store of the standalone access policy that the reference-transaction hook+// decides with, the one the server reloads. Without it the hook decides with the policy of the+// configuration.+func WithPolicyStore(store *policystore.Store) ManagerOption {+ return func(m *GitLabHookManager) {+ m.policy = store+ }+}+// Describe is used to describe Prometheus metrics.func (m *GitLabHookManager) Describe(descs chan<- *prometheus.Desc) {m.refUpdatesCounter.Describe(descs)@@ -185,6 +198,9 @@ func NewManager(for _, opt := range opts {opt(m)}+ if m.policy == nil {+ m.policy = policystore.New(cfg.Graft.Policy)+ }return m}diff --git a/internal/gitaly/hook/referencetransaction.go b/internal/gitaly/hook/referencetransaction.goindex fb4b603..452ab0e 100644--- a/internal/gitaly/hook/referencetransaction.go+++ b/internal/gitaly/hook/referencetransaction.go@@ -477,11 +477,27 @@ func (m *GitLabHookManager) enforceGraftPolicy(ctx context.Context, env []stringreturn nil}+// PolicyChangedError refuses the combined update of a land batch whose members were admitted under+// another generation of the access policy than the one in force (doc/graft/PLAN12.md, section 5).+// The batch then lands each request alone, under the policy in force.+type PolicyChangedError struct {+ // Admitted is the generation the batch admitted its members under (0 when the batch carried+ // none), InForce the generation in force.+ Admitted, InForce uint64+}++func (e PolicyChangedError) Error() string {+ return fmt.Sprintf("the access policy changed during the land batch: its members were admitted under generation %d, generation %d is in force", e.Admitted, e.InForce)+}+// graftPolicyDecision is the decision of enforceGraftPolicy: the message of the// 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) {- policyApplies := m.cfg.Graft.Standalone && len(m.cfg.Graft.Policy) > 0+ // One policy decides the whole transaction: the one in force now, while git holds the+ // references' locks (doc/graft/PLAN12.md, section 5).+ policy := m.policy.Current()+ policyApplies := m.cfg.Graft.Standalone && len(policy.Rules) > 0meta, err := gitcmd.ChangelogMetaFromEnv(env)if err != nil {@@ -519,6 +535,14 @@ func (m *GitLabHookManager) graftPolicyDecision(env []string, changes []byte) (s}}+ // The members of a batch were admitted under one generation of the policy. If another one is+ // in force, a member it denies would be landed: the batch is refused, and its requests land+ // alone, each judged by the policy in force. Outside standalone mode no member was admitted+ // by a policy, so there is nothing to compare.+ if batch && m.cfg.Graft.Standalone && meta.PolicyGeneration != policy.Generation {+ return "", PolicyChangedError{Admitted: meta.PolicyGeneration, InForce: policy.Generation}+ }+if batch || !agent {return "", nil}@@ -526,7 +550,7 @@ func (m *GitLabHookManager) graftPolicyDecision(env []string, changes []byte) (sreturn "", nil}- message, err := graftPolicyDenial(m.cfg.Graft.Policy, meta.Actor, changes)+ message, err := graftPolicyDenial(policy.Rules, meta.Actor, changes)if err != nil {return "", fmt.Errorf("evaluating graft policy: %w", err)}diff --git a/internal/gitaly/hook/referencetransaction_members_test.go b/internal/gitaly/hook/referencetransaction_members_test.goindex ec7c6b4..d69542e 100644--- a/internal/gitaly/hook/referencetransaction_members_test.go+++ b/internal/gitaly/hook/referencetransaction_members_test.go@@ -12,6 +12,7 @@ import ("github.com/feder-cr/git-ai/internal/gitlab""github.com/feder-cr/git-ai/internal/graft/changelog""github.com/feder-cr/git-ai/internal/graft/identity"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/grpc/backchannel""github.com/feder-cr/git-ai/internal/testhelper""github.com/feder-cr/git-ai/internal/testhelper/testcfg"@@ -151,6 +152,9 @@ func TestReferenceTransactionHook_batchPolicySkip(t *testing.T) {payloadCtx := identity.NewContext(ctx, identity.Identity{Name: "builder", Source: identity.SourceAgent})payloadCtx = changelog.WithOperation(payloadCtx, tc.operation)payloadCtx = changelog.WithBatch(payloadCtx, tc.members)+ // A batch carries the generation of the policy it admitted its members under: the+ // startup policy here, as in the server.+ payloadCtx = policystore.WithAdmissionGeneration(payloadCtx, 1)env, err := gitcmd.NewHooksPayload(payloadCtx,diff --git a/internal/gitaly/hook/referencetransaction_policy_test.go b/internal/gitaly/hook/referencetransaction_policy_test.goindex f166c63..fb66b04 100644--- a/internal/gitaly/hook/referencetransaction_policy_test.go+++ b/internal/gitaly/hook/referencetransaction_policy_test.go@@ -11,6 +11,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/graft/policystore""github.com/feder-cr/git-ai/internal/testhelper""github.com/stretchr/testify/require""google.golang.org/grpc/codes"@@ -47,6 +48,7 @@ func graftPolicyManager(t *testing.T, graft config.Graft) *GitLabHookManager {return &GitLabHookManager{cfg: config.Cfg{Graft: graft},logger: testhelper.SharedLogger(t),+ policy: policystore.New(graft.Policy),}}@@ -257,8 +259,7 @@ func TestEnforceGraftPolicy_batchIsHeldToTheReservation(t *testing.T) {t.Parallel()ctx := testhelper.Context(t)- payload := `{"graft_changelog":{"operation":"land_batch","members":[{"original_commit":"a","commit":"b","actor":"agent-a"}]}}`- env := []string{gitcmd.EnvHooksPayload + "=" + base64.StdEncoding.EncodeToString([]byte(payload))}+ env := batchEnv(1)for name, graft := range map[string]config.Graft{"standalone, policy denies": {Standalone: true, Policy: []config.GraftPolicyRule{{Allow: false}}},@@ -272,6 +273,62 @@ func TestEnforceGraftPolicy_batchIsHeldToTheReservation(t *testing.T) {}}+// batchEnv returns the hook environment of the combined update of a land batch whose members were+// admitted under the given generation of the policy.+func batchEnv(generation uint64) []string {+ payload := fmt.Sprintf(`{"graft_changelog":{"operation":"land_batch","policy_generation":%d,"members":[{"original_commit":"a","commit":"b","actor":"agent-a"}]}}`, generation)+ return []string{gitcmd.EnvHooksPayload + "=" + base64.StdEncoding.EncodeToString([]byte(payload))}+}++// TestEnforceGraftPolicy_batchUnderAnotherPolicy: in standalone mode a batch whose members were+// admitted under another generation of the policy than the one in force is refused with+// PolicyChangedError, so that the batch lands each request alone under the policy in force+// (doc/graft/PLAN12.md, section 5). A batch that carries no generation is refused too. Outside+// standalone mode no member was admitted by a policy.+func TestEnforceGraftPolicy_batchUnderAnotherPolicy(t *testing.T) {+ t.Parallel()++ ctx := testhelper.Context(t)+ running := config.Graft{Standalone: true, Policy: []config.GraftPolicyRule{{Allow: true}}}+ m := graftPolicyManager(t, running)+ require.NoError(t, m.enforceGraftPolicy(ctx, batchEnv(1), policyChanges("refs/heads/main")))++ next := running+ next.Policy = []config.GraftPolicyRule{{Actor: "agent-a", Allow: false}, {Allow: true}}+ _, err := m.policy.Reload(next, running)+ require.NoError(t, err)++ err = m.enforceGraftPolicy(ctx, batchEnv(1), policyChanges("refs/heads/main"))+ var changed PolicyChangedError+ require.ErrorAs(t, err, &changed)+ require.Equal(t, PolicyChangedError{Admitted: 1, InForce: 2}, changed)+ require.NoError(t, m.enforceGraftPolicy(ctx, batchEnv(2), policyChanges("refs/heads/main")))+ require.ErrorAs(t, m.enforceGraftPolicy(ctx, batchEnv(0), policyChanges("refs/heads/main")), &changed)++ outside := graftPolicyManager(t, config.Graft{Policy: running.Policy})+ require.NoError(t, outside.enforceGraftPolicy(ctx, batchEnv(0), policyChanges("refs/heads/main")))+}++// TestEnforceGraftPolicy_decidesWithThePolicyInForce: the hook decides with the policy the store+// holds now, not with the one it was built with.+func TestEnforceGraftPolicy_decidesWithThePolicyInForce(t *testing.T) {+ t.Parallel()++ ctx := testhelper.Context(t)+ running := config.Graft{Standalone: true, Policy: []config.GraftPolicyRule{{Actor: "agent-a", Allow: true}}}+ m := graftPolicyManager(t, running)+ require.NoError(t, m.enforceGraftPolicy(ctx, policyEnv(t, "agent-a", true), policyChanges("refs/heads/main")))++ next := running+ next.Policy = []config.GraftPolicyRule{{Actor: "agent-a", Refs: []string{"refs/heads/main"}, Allow: false}, {Allow: true}}+ _, err := m.policy.Reload(next, running)+ require.NoError(t, err)++ err = m.enforceGraftPolicy(ctx, policyEnv(t, "agent-a", true), policyChanges("refs/heads/main"))+ require.Equal(t, codes.PermissionDenied, status.Code(err))+ require.ErrorContains(t, err, `policy denies "agent-a" to update "refs/heads/main" (rule 1)`)+}+// 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.diff --git a/internal/gitaly/service/dependencies.go b/internal/gitaly/service/dependencies.goindex 5be6e97..d716b9f 100644--- a/internal/gitaly/service/dependencies.go+++ b/internal/gitaly/service/dependencies.go@@ -22,6 +22,7 @@ import ("github.com/feder-cr/git-ai/internal/gitlab""github.com/feder-cr/git-ai/internal/graft/corestore""github.com/feder-cr/git-ai/internal/graft/landlane"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/graft/resolver""github.com/feder-cr/git-ai/internal/grpc/backchannel""github.com/feder-cr/git-ai/internal/grpc/client"@@ -33,15 +34,18 @@ import (// Dependencies assembles set of components required by different kinds of services.type Dependencies struct {- Logger log.Logger- Cfg config.Cfg- GitalyHookManager gitalyhook.Manager- TransactionManager transaction.Manager- StorageLocator storage.Locator- ClientPool *client.Pool- GitCmdFactory gitcmd.CommandFactory- BackchannelRegistry *backchannel.Registry- GitlabClient gitlab.Client+ Logger log.Logger+ Cfg config.Cfg+ GitalyHookManager gitalyhook.Manager+ TransactionManager transaction.Manager+ StorageLocator storage.Locator+ ClientPool *client.Pool+ GitCmdFactory gitcmd.CommandFactory+ BackchannelRegistry *backchannel.Registry+ GitlabClient gitlab.Client+ // GraftPolicy holds the standalone access policy in force, which the server reloads+ // (doc/graft/PLAN12.md). Nil means the static policy of Cfg.+ GraftPolicy *policystore.StoreCatfileCache catfile.CacheDiskCache cache.CachePackObjectsCache streamcache.Cache@@ -137,6 +141,15 @@ func (dc *Dependencies) GetBackchannelRegistry() *backchannel.Registry {return dc.BackchannelRegistry}+// GetGraftPolicy returns the store of the standalone access policy in force: GraftPolicy, or a+// store of the static policy of the configuration when it is not set.+func (dc *Dependencies) GetGraftPolicy() *policystore.Store {+ if dc.GraftPolicy != nil {+ return dc.GraftPolicy+ }+ return policystore.New(dc.Cfg.Graft.Policy)+}+// GetGitlabClient returns client to access GitLab API.func (dc *Dependencies) GetGitlabClient() gitlab.Client {return dc.GitlabClientdiff --git a/internal/gitaly/service/operations/land_batch_objectdir_test.go b/internal/gitaly/service/operations/land_batch_objectdir_test.goindex cfe5dad..0aca82b 100644--- a/internal/gitaly/service/operations/land_batch_objectdir_test.go+++ b/internal/gitaly/service/operations/land_batch_objectdir_test.go@@ -4,6 +4,7 @@ import ("testing""github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/testhelper""github.com/feder-cr/git-ai/proto/go/gitalypb""github.com/stretchr/testify/require"@@ -17,7 +18,7 @@ func TestLandBatchable_requestWithObjectDirectoryLandsAlone(t *testing.T) {ctx := testhelper.Context(t)// The lanes are only checked for presence: a request that is excluded never reaches the factory.- s := &Server{landLanes: &landBatchLanes{}, graft: config.Graft{Standalone: true}}+ s := &Server{landLanes: &landBatchLanes{}, graft: config.Graft{Standalone: true}, graftPolicy: policystore.New(nil)}newRequest := func(repo *gitalypb.Repository) *gitalypb.UserLandRequest {return &gitalypb.UserLandRequest{diff --git a/internal/gitaly/service/operations/land_batch_server.go b/internal/gitaly/service/operations/land_batch_server.goindex 4d9228f..71aa799 100644--- a/internal/gitaly/service/operations/land_batch_server.go+++ b/internal/gitaly/service/operations/land_batch_server.go@@ -12,6 +12,7 @@ import ("github.com/feder-cr/git-ai/internal/gitaly/hook/updateref""github.com/feder-cr/git-ai/internal/graft/changelog""github.com/feder-cr/git-ai/internal/graft/landlane"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/log""github.com/feder-cr/git-ai/internal/structerr""github.com/feder-cr/git-ai/proto/go/gitalypb"@@ -187,7 +188,7 @@ func (s *Server) newLandBatchStepper(ctx context.Context, repository *gitalypb.Rreturn nil, nil, err}- return &serverLandBatchStepper{landingAttempt: attempt}, cleanup, nil+ return &serverLandBatchStepper{landingAttempt: attempt, policy: s.graftPolicy.Current()}, cleanup, nil}// landBatchResult builds the result of a request of a batch.@@ -235,6 +236,11 @@ func landBatchGiveUp(req *landBatchRequest, cause error, attempts int) error {// combined update of the batch.type serverLandBatchStepper struct {*landingAttempt+ // policy is the standalone access policy that admits the members of this batch attempt: one+ // generation for all of them. The combined update carries its generation, and the+ // reference-transaction hook refuses it when another policy is in force by then+ // (doc/graft/PLAN12.md, section 5).+ policy *policystore.Snapshot}// Land lands the request onto tip with the decision that every land makes (landingAttempt.decide).@@ -276,7 +282,7 @@ func (st *serverLandBatchStepper) Land(ctx context.Context, tip git.ObjectID, re// runs as the graft-batch user, so every member is checked here, before it enters the running tip.// A denied request fails alone with the reason of the policy.func (st *serverLandBatchStepper) admit(req *landBatchRequest, reference git.ReferenceName, oldOID, newOID git.ObjectID) error {- allowed, message, err := hook.EvaluateGraftPolicy(st.server.graft, req.actor, reference.String(), oldOID.String(), newOID.String())+ allowed, message, err := hook.EvaluateGraftPolicy(config.Graft{Policy: st.policy.Rules}, req.actor, reference.String(), oldOID.String(), newOID.String())if err != nil {return structerr.NewInternal("evaluating graft policy: %w", err)}@@ -310,6 +316,7 @@ func (st *serverLandBatchStepper) Update(ctx context.Context, reference git.Refectx = batchUpdateContext(ctx)ctx = changelog.WithBatch(changelog.WithOperation(ctx, changelog.OperationLandBatch), members)+ ctx = policystore.WithAdmissionGeneration(ctx, st.policy.Generation)// The compare-and-swap reads only the repository and the user of the request.in := &gitalypb.UserLandRequest{@@ -368,7 +375,10 @@ func (st *serverLandBatchStepper) updateKind(err error) (landUpdateKind, error)var customHookErr updateref.CustomHookErrorvar notAllowedErr hook.NotAllowedError- if errors.As(err, &customHookErr) || errors.As(err, ¬AllowedErr) {+ // A policy that changed since the members were admitted refuses the combined update: each+ // request then lands alone, judged by the policy in force.+ var policyChanged hook.PolicyChangedError+ if errors.As(err, &customHookErr) || errors.As(err, ¬AllowedErr) || errors.As(err, &policyChanged) {return landUpdateRejected, err}diff --git a/internal/gitaly/service/operations/land_inline.go b/internal/gitaly/service/operations/land_inline.goindex d273684..e8dd0dc 100644--- a/internal/gitaly/service/operations/land_inline.go+++ b/internal/gitaly/service/operations/land_inline.go@@ -98,7 +98,7 @@ func (s *Server) landResolveInline(ctx context.Context, in *gitalypb.UserLandReq// An agent that may not update the branch gets nothing resolved, as out of the lane (the policy first):// the land goes out of the lane, which refuses it with the policy's message.reference := git.NewReferenceNameFromBranchName(string(in.GetBranch()))- if err := hook.CheckAgentPolicy(ctx, s.graft, fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {+ if err := hook.CheckAgentPolicy(ctx, s.graftInForce(), fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {return landInlineNotTried}diff --git a/internal/gitaly/service/operations/land_inline_test.go b/internal/gitaly/service/operations/land_inline_test.goindex c949c0e..6a0eb72 100644--- a/internal/gitaly/service/operations/land_inline_test.go+++ b/internal/gitaly/service/operations/land_inline_test.go@@ -2,6 +2,7 @@ package operationsimport ("fmt"+ "github.com/feder-cr/git-ai/internal/graft/policystore""strings""sync""testing"@@ -173,6 +174,7 @@ func TestLandResolveInline_neverForAnAgentThePolicyDenies(t *testing.T) {fx := newResolveFixture(t, rcfg)s := fx.server(t, rcfg)s.graft = config.Graft{Standalone: true, Policy: []config.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/other"}, Allow: true}}}+ s.graftPolicy = policystore.New(s.graft.Policy)ctx := identity.NewContext(fx.ctx, identity.Identity{Name: "agent-7", Source: identity.SourceAgent})l, err := landListConflicts(ctx, fx.repo, fx.tip, fx.commit, 1<<20)@@ -184,6 +186,7 @@ func TestLandResolveInline_neverForAnAgentThePolicyDenies(t *testing.T) {// The same agent where the policy lets it update the branch.s.graft.Policy = []config.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/**"}, Allow: true}}+ s.graftPolicy = policystore.New(s.graft.Policy)require.Equal(t, landInlineResolved, s.landResolveInline(ctx, fx.request("Land"), fx.tip, fx.commit, l, pre))require.Equal(t, 1, unionCalls(t, dir))}diff --git a/internal/gitaly/service/operations/land_policy_test.go b/internal/gitaly/service/operations/land_policy_test.goindex c11acdc..be1bd20 100644--- a/internal/gitaly/service/operations/land_policy_test.go+++ b/internal/gitaly/service/operations/land_policy_test.go@@ -1,6 +1,7 @@package operationsimport (+ "github.com/feder-cr/git-ai/internal/graft/policystore""testing""github.com/stretchr/testify/require"@@ -22,6 +23,7 @@ func TestLandPrecheckResolution_policyFirst(t *testing.T) {fx := newResolveFixture(t, rcfg)s := fx.server(t, rcfg)s.graft = gitalycfg.Graft{Standalone: true, Policy: []gitalycfg.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/other"}, Allow: true}}}+ s.graftPolicy = policystore.New(s.graft.Policy)ctx := identity.NewContext(fx.ctx, identity.Identity{Name: "agent-7", Source: identity.SourceAgent})in := fx.request("Land")in.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")@@ -34,6 +36,7 @@ func TestLandPrecheckResolution_policyFirst(t *testing.T) {// An agent the policy lets update the branch gets its resolution checked and verified.s.graft.Policy = []gitalycfg.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/**"}, Allow: true}}+ s.graftPolicy = policystore.New(s.graft.Policy)pc, err = s.landPrecheckResolution(ctx, in, fx.repo)require.NoError(t, err)require.NotNil(t, pc)diff --git a/internal/gitaly/service/operations/land_proposals_test.go b/internal/gitaly/service/operations/land_proposals_test.goindex 42de354..504ee01 100644--- a/internal/gitaly/service/operations/land_proposals_test.go+++ b/internal/gitaly/service/operations/land_proposals_test.go@@ -3,6 +3,7 @@ package operationsimport ("errors""fmt"+ "github.com/feder-cr/git-ai/internal/graft/policystore""os""strconv""strings"@@ -420,6 +421,7 @@ func TestResolveLandConflicts_policyFirst(t *testing.T) {fx := newResolveFixture(t, enabledResolver(argv))s := fx.server(t, enabledResolver(argv))s.graft = gitalycfg.Graft{Standalone: true, Policy: []gitalycfg.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/other"}, Allow: true}}}+ s.graftPolicy = policystore.New(s.graft.Policy)ctx := identity.NewContext(fx.ctx, identity.Identity{Name: "agent-7", Source: identity.SourceAgent})_, err := s.resolveLandConflicts(ctx, fx.request("Land"), fx.repo, fx.tip, fx.commit, fx.committer())@@ -433,6 +435,7 @@ func TestResolveLandConflicts_policyFirst(t *testing.T) {// An agent the policy lets update the branch gets its proposals.s.graft.Policy = []gitalycfg.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/**"}, Allow: true}}+ s.graftPolicy = policystore.New(s.graft.Policy)_, err = s.resolveLandConflicts(ctx, fx.request("Land"), fx.repo, fx.tip, fx.commit, fx.committer())var unresolved *landUnresolvedErrorrequire.ErrorAs(t, err, &unresolved)diff --git a/internal/gitaly/service/operations/land_reland.go b/internal/gitaly/service/operations/land_reland.goindex 5142a2f..53a2b42 100644--- a/internal/gitaly/service/operations/land_reland.go+++ b/internal/gitaly/service/operations/land_reland.go@@ -197,7 +197,7 @@ func (s *Server) landPrecheckResolution(ctx context.Context, in *gitalypb.UserLa// alone, so it comes first, as in landResolveAt. Otherwise a denied agent could hold the// repository's verify slot, and its tree would run in the operator's sandbox.reference := git.NewReferenceNameFromBranchName(string(in.GetBranch()))- if err := hook.CheckAgentPolicy(ctx, s.graft, fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {+ if err := hook.CheckAgentPolicy(ctx, s.graftInForce(), fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {return nil, err}diff --git a/internal/gitaly/service/operations/land_resolve.go b/internal/gitaly/service/operations/land_resolve.goindex 1eae939..e426ebd 100644--- a/internal/gitaly/service/operations/land_resolve.go+++ b/internal/gitaly/service/operations/land_resolve.go@@ -103,7 +103,7 @@ func (s *Server) landResolveAt(// An agent that may not update the branch gets nothing resolved, and no proposal is kept for// it: the policy decides on the actor and the reference alone, so it is checked first.reference := git.NewReferenceNameFromBranchName(string(in.GetBranch()))- if err := hook.CheckAgentPolicy(ctx, s.graft, fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {+ if err := hook.CheckAgentPolicy(ctx, s.graftInForce(), fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {return landListing{}, nil, &landPolicyDeniedError{err: err}}l, err := landListConflicts(ctx, repo, tip, commitID, s.resolveCfg.MaxFileBytesOrDefault())diff --git a/internal/gitaly/service/operations/land_resolve_test.go b/internal/gitaly/service/operations/land_resolve_test.goindex acd62b7..0904f8a 100644--- a/internal/gitaly/service/operations/land_resolve_test.go+++ b/internal/gitaly/service/operations/land_resolve_test.go@@ -27,6 +27,7 @@ import ("github.com/feder-cr/git-ai/internal/gitaly/service""github.com/feder-cr/git-ai/internal/graft/identity""github.com/feder-cr/git-ai/internal/graft/landlane"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/graft/resolver""github.com/feder-cr/git-ai/internal/testhelper""github.com/feder-cr/git-ai/internal/testhelper/testcfg"@@ -282,6 +283,7 @@ func (fx resolveFixture) server(t *testing.T, rcfg config.GraftResolver) *ServercatfileCache: cache,locator: locator,localRepoFactory: localrepo.NewFactory(testhelper.NewLogger(t), locator, gittest.NewCommandFactory(t, fx.cfg), cache),+ graftPolicy: policystore.New(nil),}}@@ -687,7 +689,7 @@ func TestResolveLandConflicts_refusedFailedAndDisabled(t *testing.T) {})t.Run("disabled", func(t *testing.T) {- s := &Server{gitConfig: fx.cfg.Git, resolveCfg: config.GraftResolver{}, conflictResolver: nil}+ s := &Server{gitConfig: fx.cfg.Git, resolveCfg: config.GraftResolver{}, conflictResolver: nil, graftPolicy: policystore.New(nil)}_, err := s.resolveLandConflicts(fx.ctx, fx.request("Land"), fx.repo, fx.tip, fx.commit, fx.committer())require.ErrorContains(t, err, "not enabled")diff --git a/internal/gitaly/service/operations/merge_to_ref.go b/internal/gitaly/service/operations/merge_to_ref.goindex 46d6daa..912f572 100644--- a/internal/gitaly/service/operations/merge_to_ref.go+++ b/internal/gitaly/service/operations/merge_to_ref.go@@ -154,7 +154,7 @@ func (s *Server) UserMergeToRef(ctx context.Context, request *gitalypb.UserMerge// implementation doesn't invoke hooks, so we don't either.// The reference-transaction hook enforces the standalone policy, but Git only// reports that it failed. Checking the policy here returns the denial itself.- if err := hook.CheckAgentPolicy(ctx, s.graft, fmt.Sprintf("%s %s %s\n", oldTargetOID, mergeOID, request.GetTargetRef())); err != nil {+ if err := hook.CheckAgentPolicy(ctx, s.graftInForce(), fmt.Sprintf("%s %s %s\n", oldTargetOID, mergeOID, request.GetTargetRef())); err != nil {return nil, err}diff --git a/internal/gitaly/service/operations/rebase_to_ref.go b/internal/gitaly/service/operations/rebase_to_ref.goindex 185827c..fd67d6f 100644--- a/internal/gitaly/service/operations/rebase_to_ref.go+++ b/internal/gitaly/service/operations/rebase_to_ref.go@@ -104,7 +104,7 @@ func (s *Server) UserRebaseToRef(ctx context.Context, request *gitalypb.UserReba// The reference-transaction hook enforces the standalone policy, but Git only// reports that it failed. Checking the policy here returns the denial itself.- if err := hook.CheckAgentPolicy(ctx, s.graft, fmt.Sprintf("%s %s %s\n", oldTargetOID, rebasedOID, request.GetTargetRef())); err != nil {+ if err := hook.CheckAgentPolicy(ctx, s.graftInForce(), fmt.Sprintf("%s %s %s\n", oldTargetOID, rebasedOID, request.GetTargetRef())); err != nil {return nil, err}diff --git a/internal/gitaly/service/operations/server.go b/internal/gitaly/service/operations/server.goindex 3059824..0c17a37 100644--- a/internal/gitaly/service/operations/server.go+++ b/internal/gitaly/service/operations/server.go@@ -15,6 +15,7 @@ import ("github.com/feder-cr/git-ai/internal/gitaly/storage""github.com/feder-cr/git-ai/internal/gitaly/transaction""github.com/feder-cr/git-ai/internal/graft/corestore"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/graft/resolver""github.com/feder-cr/git-ai/internal/grpc/client""github.com/feder-cr/git-ai/internal/log"@@ -25,15 +26,18 @@ import (//nolint:revive // This is unintentionally missing documentation.type Server struct {gitalypb.UnimplementedOperationServiceServer- logger log.Logger- hookManager hook.Manager- txManager transaction.Manager- locator storage.Locator- conns *client.Pool- catfileCache catfile.Cache- updater *updateref.UpdaterWithHooks- gitConfig config.Git- graft config.Graft+ logger log.Logger+ hookManager hook.Manager+ txManager transaction.Manager+ locator storage.Locator+ conns *client.Pool+ catfileCache catfile.Cache+ updater *updateref.UpdaterWithHooks+ gitConfig config.Git+ graft config.Graft+ // graftPolicy holds the standalone access policy in force (doc/graft/PLAN12.md); graft.Policy+ // is the one of the startup and is not read.+ graftPolicy *policystore.StorelocalRepoFactory localrepo.Factory// resolveCfg configures conflict resolution of UserLand.resolveCfg config.GraftResolver@@ -120,6 +124,7 @@ func NewServer(deps *service.Dependencies) *Server {updater: deps.GetUpdaterWithHooks(),gitConfig: deps.GetCfg().Git,graft: deps.GetCfg().Graft,+ graftPolicy: deps.GetGraftPolicy(),localRepoFactory: deps.GetRepositoryFactory(),resolveCfg: resolveCfg,conflictResolver: conflictResolver,@@ -162,3 +167,11 @@ func (s *Server) ensureStorageFresh(ctx context.Context, repo *gitalypb.Reposito}return s.storageSync.EnsureFresh(ctx, repo)}++// graftInForce returns the [graft] configuration with the standalone access policy in force: the+// policy checks of the RPCs decide with the policy the server holds now.+func (s *Server) graftInForce() config.Graft {+ graft := s.graft+ graft.Policy = s.graftPolicy.Current().Rules+ return graft+}diff --git a/internal/gitlab/standalone_client.go b/internal/gitlab/standalone_client.goindex 182cf8a..4676a4c 100644--- a/internal/gitlab/standalone_client.go+++ b/internal/gitlab/standalone_client.go@@ -8,13 +8,15 @@ import ("github.com/feder-cr/git-ai/internal/gitaly/config""github.com/feder-cr/git-ai/internal/graft/changelog"+ "github.com/feder-cr/git-ai/internal/graft/policystore""github.com/feder-cr/git-ai/internal/log")// standaloneClient is a Client for Graft's standalone mode. It never contacts// GitLab: access checks are answered from the ordered [graft] policy instead.type standaloneClient struct {- policy []config.GraftPolicyRule+ // policy holds the policy in force, which the server may reload (doc/graft/PLAN12.md).+ policy *policystore.Storelogger log.Logger}@@ -24,8 +26,14 @@ type standaloneClient struct {// changed reference is allowed by the first policy rule that applies to it;// a reference that no rule applies to is denied.func NewStandaloneClient(cfg config.Graft, logger log.Logger) Client {+ return NewStandaloneClientWithPolicy(policystore.New(cfg.Policy), logger)+}++// NewStandaloneClientWithPolicy is NewStandaloneClient for the policy that store holds, which the+// server reloads: every access check is answered with the policy in force when it runs.+func NewStandaloneClientWithPolicy(store *policystore.Store, logger log.Logger) Client {return &standaloneClient{- policy: append([]config.GraftPolicyRule(nil), cfg.Policy...),+ policy: store,logger: logger.WithField("component", "standalone_client"),}}@@ -35,7 +43,7 @@ func NewStandaloneClient(cfg config.Graft, logger log.Logger) Client {// malformed change set or an invalid glob in the policy is reported as an// error.func (c *standaloneClient) Allowed(_ context.Context, params AllowedParams) (bool, string, error) {- allowed, message, err := EvaluatePolicy(c.policy, params.GLID, params.Changes)+ allowed, message, err := EvaluatePolicy(c.policy.Current().Rules, params.GLID, params.Changes)if err != nil || allowed {return allowed, message, err}