Skip to content

Git designed for AI agents.

graft: the policy evaluation moves to a portable package; graft builds for Windows again

Federico Elia3a0910104134
diff --git a/cmd/graft/policy.go b/cmd/graft/policy.go
index bd2e516..179475e 100644
--- a/cmd/graft/policy.go
+++ b/cmd/graft/policy.go
@@ -11,7 +11,7 @@ import (
"strings"
"github.com/feder-cr/git-ai/internal/gitaly/config"
- "github.com/feder-cr/git-ai/internal/gitaly/hook"
+ "github.com/feder-cr/git-ai/internal/graft/policyeval"
"github.com/feder-cr/git-ai/internal/graft/policystore"
"github.com/feder-cr/git-ai/sdk"
)
@@ -220,7 +220,7 @@ func policyCheckRepository(ctx context.Context, repo *sdk.Repo, graft config.Gra
}
reference := string(cs.GetReference())
for _, actor := range actors {
- allowed, reason, err := hook.EvaluateGraftPolicy(graft, actor, reference, cs.GetOldOid(), cs.GetNewOid())
+ allowed, reason, err := policyeval.EvaluateUpdate(graft.Policy, actor, reference, cs.GetOldOid(), cs.GetNewOid())
if err != nil {
return policyRepository{}, fmt.Errorf("changeset %d: %w", cs.GetSequence(), err)
}
diff --git a/internal/git/objectpool/disconnect_fanout_test.go b/internal/git/objectpool/disconnect_fanout_test.go
index 830a34b..a2e857b 100644
--- a/internal/git/objectpool/disconnect_fanout_test.go
+++ b/internal/git/objectpool/disconnect_fanout_test.go
@@ -19,10 +19,14 @@ type recordingWAL struct {
links []string
}
-func (w *recordingWAL) CreateDirectory(relativePath string) { w.directories = append(w.directories, relativePath) }
-func (w *recordingWAL) RemoveDirectoryEntry(string) {}
-func (w *recordingWAL) CreateFile(string, string) error { return nil }
-func (w *recordingWAL) CreateLink(sourcePath, destinationPath string) { w.links = append(w.links, destinationPath) }
+func (w *recordingWAL) CreateDirectory(relativePath string) {
+ w.directories = append(w.directories, relativePath)
+}
+func (w *recordingWAL) RemoveDirectoryEntry(string) {}
+func (w *recordingWAL) CreateFile(string, string) error { return nil }
+func (w *recordingWAL) CreateLink(sourcePath, destinationPath string) {
+ w.links = append(w.links, destinationPath)
+}
// TestDisconnect_fanOutDirectoryRemoved removes each loose object directory of the repository right
// before the first links into it, three times, as housekeeping may (git prune-packed removes empty
diff --git a/internal/gitaly/hook/graft_policy_export.go b/internal/gitaly/hook/graft_policy_export.go
deleted file mode 100644
index f1ba5ca..0000000
--- a/internal/gitaly/hook/graft_policy_export.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package hook
-
-import (
- "fmt"
-
- "github.com/feder-cr/git-ai/internal/gitaly/config"
-)
-
-// EvaluateGraftPolicy evaluates the standalone access policy for the update of reference from oldOID
-// to newOID by actor. It applies the same rules as the reference-transaction hook: references
-// outside refs/ and HEAD are not governed. When allowed is false, message holds the reason of the
-// denial. The caller decides whether the policy applies to the update, for example only to agent
-// callers, as the hook does.
-func EvaluateGraftPolicy(cfg config.Graft, actor string, reference, oldOID, newOID string) (bool, string, error) {
- changes := fmt.Sprintf("%s %s %s\n", oldOID, newOID, reference)
-
- message, err := graftPolicyDenial(cfg.Policy, actor, []byte(changes))
- if err != nil {
- return false, "", fmt.Errorf("evaluating graft policy: %w", err)
- }
-
- return message == "", message, nil
-}
diff --git a/internal/gitaly/hook/pending_transactions.go b/internal/gitaly/hook/pending_transactions.go
index ff6b83b..436b29a 100644
--- a/internal/gitaly/hook/pending_transactions.go
+++ b/internal/gitaly/hook/pending_transactions.go
@@ -6,7 +6,7 @@ import (
"time"
"github.com/feder-cr/git-ai/internal/git"
- "github.com/feder-cr/git-ai/internal/graft/changelog"
+ "github.com/feder-cr/git-ai/internal/graft/refchange"
)
const (
@@ -225,6 +225,6 @@ func referencesContained(inner, outer []byte) bool {
// updatedReference returns the reference of one line of the
// reference-transaction hook's input.
func updatedReference(line []byte) (string, bool) {
- _, _, reference, ok := changelog.ParseHookLine(string(line))
+ _, _, reference, ok := refchange.ParseHookLine(string(line))
return reference, ok
}
diff --git a/internal/gitaly/hook/referencetransaction.go b/internal/gitaly/hook/referencetransaction.go
index 9e0f4cb..0087c51 100644
--- a/internal/gitaly/hook/referencetransaction.go
+++ b/internal/gitaly/hook/referencetransaction.go
@@ -15,10 +15,11 @@ import (
"github.com/feder-cr/git-ai/internal/git/gitcmd"
"github.com/feder-cr/git-ai/internal/git/mvcc"
"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/changelog"
"github.com/feder-cr/git-ai/internal/graft/identity"
+ "github.com/feder-cr/git-ai/internal/graft/policyeval"
"github.com/feder-cr/git-ai/internal/graft/policystore"
+ "github.com/feder-cr/git-ai/internal/graft/refchange"
"github.com/feder-cr/git-ai/internal/log"
"github.com/feder-cr/git-ai/internal/structerr"
"github.com/feder-cr/git-ai/internal/transaction/voting"
@@ -563,7 +564,7 @@ func (m *GitLabHookManager) graftPolicyDecision(policy *policystore.Snapshot, en
return "", false, nil
}
- message, err = graftPolicyDenial(policy.Rules, meta.Actor, changes)
+ message, err = policyeval.Denial(policy.Rules, meta.Actor, changes)
if err != nil {
return "", true, fmt.Errorf("evaluating graft policy: %w", err)
}
@@ -595,7 +596,7 @@ func CheckAgentPolicy(ctx context.Context, graft config.Graft, changes string) e
return nil
}
- message, err := graftPolicyDenial(graft.Policy, id.Name, []byte(changes))
+ message, err := policyeval.Denial(graft.Policy, id.Name, []byte(changes))
if err != nil {
return structerr.NewInternal("evaluating graft policy: %w", err)
}
@@ -607,34 +608,6 @@ func CheckAgentPolicy(ctx context.Context, graft config.Graft, changes string) e
return nil
}
-// graftPolicyDenial returns the message of the denial of the update of the
-// governed references in changes by actor, or an empty message when the policy
-// allows the update. Only references under refs/ and HEAD are governed, see
-// isGovernedReference.
-func graftPolicyDenial(policy []config.GraftPolicyRule, actor string, changes []byte) (string, error) {
- var governed strings.Builder
- for _, line := range strings.Split(string(changes), "\n") {
- // Lines that are not well formed are kept, so that the policy rejects them.
- if _, _, reference, ok := changelog.ParseHookLine(line); ok && !isGovernedReference(reference) {
- continue
- }
-
- governed.WriteString(line)
- governed.WriteString("\n")
- }
-
- allowed, message, err := gitlab.EvaluatePolicy(policy, actor, governed.String())
- if err != nil {
- return "", err
- }
-
- if allowed {
- return "", nil
- }
-
- return message, nil
-}
-
// 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,
@@ -649,19 +622,13 @@ const GraftReservedRefPrefix = "refs/graft/"
// GraftReservedRefPrefix, or "".
func graftReservedDenial(changes []byte) string {
for _, line := range strings.Split(string(changes), "\n") {
- if _, _, reference, ok := changelog.ParseHookLine(line); ok && strings.HasPrefix(reference, GraftReservedRefPrefix) {
+ if _, _, reference, ok := refchange.ParseHookLine(line); ok && strings.HasPrefix(reference, GraftReservedRefPrefix) {
return fmt.Sprintf("%q is under %s, which is reserved for the server: agents may not update it", reference, GraftReservedRefPrefix)
}
}
return ""
}
-// isGovernedReference reports whether the standalone access policy governs an
-// update of reference: every reference under refs/, and HEAD.
-func isGovernedReference(reference string) bool {
- return reference == "HEAD" || strings.HasPrefix(reference, "refs/")
-}
-
// isForceDeletionsOnly determines whether the given changes only consist of force-deletions.
func isForceDeletionsOnly(objectHash git.ObjectHash, changes io.Reader) bool {
// forceDeletionPrefix is the prefix of a queued reference transaction which deletes a
diff --git a/internal/gitaly/service/operations/land_batch_server.go b/internal/gitaly/service/operations/land_batch_server.go
index 71aa799..16b7a13 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/policyeval"
"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"
@@ -282,7 +283,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(config.Graft{Policy: st.policy.Rules}, req.actor, reference.String(), oldOID.String(), newOID.String())
+ allowed, message, err := policyeval.EvaluateUpdate(st.policy.Rules, req.actor, reference.String(), oldOID.String(), newOID.String())
if err != nil {
return structerr.NewInternal("evaluating graft policy: %w", err)
}
diff --git a/internal/gitaly/service/operations/land_batch_test.go b/internal/gitaly/service/operations/land_batch_test.go
index a1b96a5..ca15f0a 100644
--- a/internal/gitaly/service/operations/land_batch_test.go
+++ b/internal/gitaly/service/operations/land_batch_test.go
@@ -12,10 +12,10 @@ import (
"github.com/feder-cr/git-ai/internal/git"
"github.com/feder-cr/git-ai/internal/git/gittest"
"github.com/feder-cr/git-ai/internal/gitaly/config"
- "github.com/feder-cr/git-ai/internal/gitaly/hook"
"github.com/feder-cr/git-ai/internal/gitaly/service"
"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/policyeval"
"github.com/feder-cr/git-ai/internal/graft/resolver"
"github.com/feder-cr/git-ai/internal/structerr"
"github.com/feder-cr/git-ai/internal/testhelper"
@@ -587,12 +587,12 @@ func TestEvaluateGraftPolicyForBatchedActors(t *testing.T) {
const zero = "0000000000000000000000000000000000000000"
const newOID = "1111111111111111111111111111111111111111"
- allowed, message, err := hook.EvaluateGraftPolicy(policy, "bot-1", "refs/heads/main", zero, newOID)
+ allowed, message, err := policyeval.EvaluateUpdate(policy.Policy, "bot-1", "refs/heads/main", zero, newOID)
require.NoError(t, err)
require.False(t, allowed)
require.Contains(t, message, "bot-1")
- allowed, message, err = hook.EvaluateGraftPolicy(policy, "alice", "refs/heads/main", zero, newOID)
+ allowed, message, err = policyeval.EvaluateUpdate(policy.Policy, "alice", "refs/heads/main", zero, newOID)
require.NoError(t, err)
require.True(t, allowed)
require.Empty(t, message)
diff --git a/internal/gitaly/service/operations/land_policy_reload_test.go b/internal/gitaly/service/operations/land_policy_reload_test.go
index 19575f8..3afe8f9 100644
--- a/internal/gitaly/service/operations/land_policy_reload_test.go
+++ b/internal/gitaly/service/operations/land_policy_reload_test.go
@@ -4,8 +4,8 @@ import (
"context"
"fmt"
"io"
- "strings"
"slices"
+ "strings"
"sync"
"sync/atomic"
"testing"
diff --git a/internal/gitlab/standalone_client.go b/internal/gitlab/standalone_client.go
index 4676a4c..f6c17a6 100644
--- a/internal/gitlab/standalone_client.go
+++ b/internal/gitlab/standalone_client.go
@@ -2,12 +2,9 @@ package gitlab
import (
"context"
- "fmt"
- "path"
- "strings"
"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/policyeval"
"github.com/feder-cr/git-ai/internal/graft/policystore"
"github.com/feder-cr/git-ai/internal/log"
)
@@ -43,7 +40,7 @@ func NewStandaloneClientWithPolicy(store *policystore.Store, logger log.Logger)
// 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.Current().Rules, params.GLID, params.Changes)
+ allowed, message, err := policyeval.Evaluate(c.policy.Current().Rules, params.GLID, params.Changes)
if err != nil || allowed {
return allowed, message, err
}
@@ -56,47 +53,6 @@ func (c *standaloneClient) Allowed(_ context.Context, params AllowedParams) (boo
return false, message, nil
}
-// EvaluatePolicy decides whether actor may apply changes under the ordered
-// [graft] policy. changes uses the "<old-oid> <new-oid> <ref>" per-line format
-// of the pre-receive and reference-transaction hooks. An empty policy allows
-// everything. Otherwise every changed reference must be allowed by the first
-// rule that applies to it, and a reference that no rule applies to is denied.
-// A denial is reported as (false, message, nil); a malformed change set or an
-// invalid glob in the policy is reported as an error.
-//
-// The pre-receive access check of the standalone client and the
-// reference-transaction hook both use it, so that a reference update is held to
-// the same policy whichever RPC performs it.
-func EvaluatePolicy(policy []config.GraftPolicyRule, actor, changes string) (bool, string, error) {
- if len(policy) == 0 {
- return true, "", nil
- }
-
- refs, err := parseChangedRefs(changes)
- if err != nil {
- return false, "", err
- }
-
- for _, ref := range refs {
- decision, err := decide(policy, actor, ref)
- if err != nil {
- return false, "", err
- }
-
- if decision.allowed {
- continue
- }
-
- if decision.rule < 0 {
- return false, fmt.Sprintf("policy denies %q to update %q: no matching rule", actor, ref), nil
- }
-
- return false, fmt.Sprintf("policy denies %q to update %q (rule %d)", actor, ref, decision.rule+1), nil
- }
-
- return true, "", nil
-}
-
// PreReceive always succeeds: there is no GitLab reference counter to increase.
func (c *standaloneClient) PreReceive(context.Context, string) (bool, error) {
return true, nil
@@ -120,156 +76,3 @@ func (c *standaloneClient) Check(context.Context) (*CheckInfo, error) {
APIVersion: "none",
}, nil
}
-
-// policyDecision is the outcome of evaluating the policy for one reference.
-type policyDecision struct {
- allowed bool
- // rule is the zero-based index of the deciding rule, or -1 when no rule applies.
- rule int
-}
-
-// decide returns the decision of the first rule that applies to actor and ref.
-// A reference that no rule applies to is denied.
-func decide(policy []config.GraftPolicyRule, actor, ref string) (policyDecision, error) {
- for i, rule := range policy {
- matched, err := ruleApplies(rule, actor, ref)
- if err != nil {
- return policyDecision{}, err
- }
-
- if matched {
- return policyDecision{allowed: rule.Allow, rule: i}, nil
- }
- }
-
- return policyDecision{allowed: false, rule: -1}, nil
-}
-
-// ruleApplies reports whether rule governs the update of ref by actor. An
-// empty or "*" actor matches everybody. Empty Refs match every reference.
-func ruleApplies(rule config.GraftPolicyRule, actor, ref string) (bool, error) {
- if rule.Actor != "" && rule.Actor != "*" {
- ok, err := path.Match(rule.Actor, actor)
- if err != nil {
- return false, fmt.Errorf("policy actor %q: %w", rule.Actor, err)
- }
-
- if !ok {
- return false, nil
- }
- }
-
- if len(rule.Refs) == 0 {
- return true, nil
- }
-
- for _, glob := range rule.Refs {
- ok, err := matchRef(glob, ref)
- if err != nil {
- return false, fmt.Errorf("policy ref %q: %w", glob, err)
- }
-
- if ok {
- return true, nil
- }
- }
-
- return false, nil
-}
-
-// matchRef matches a fully qualified reference name against a policy glob.
-// Globs use path.Match syntax. A trailing "/**" matches the prefix at any
-// depth: "refs/heads/**" matches "refs/heads/main" and "refs/heads/a/b" but
-// not "refs/heads" itself. Any other "**" suffix matches any remainder,
-// including "/": "refs/heads/release**" matches "refs/heads/release/1.0" and
-// "refs/heads/release-2". A bare "**" matches every reference.
-func matchRef(glob, ref string) (bool, error) {
- if glob == "**" {
- return true, nil
- }
-
- prefix, deep := strings.CutSuffix(glob, "/**")
- if !deep {
- if loose, ok := strings.CutSuffix(glob, "**"); ok {
- return matchRefPrefix(loose, ref)
- }
-
- return path.Match(glob, ref)
- }
-
- // Validate the pattern up front: path.Match only reports a malformed
- // pattern when it gets to examine it against a candidate.
- if _, err := path.Match(prefix, ""); err != nil {
- return false, err
- }
-
- // Every "/" in ref ends a candidate directory prefix of ref. Any of them
- // matching the glob prefix means ref lies at or below that directory.
- for i := 0; i < len(ref); i++ {
- if ref[i] != '/' {
- continue
- }
-
- ok, err := path.Match(prefix, ref[:i])
- if err != nil {
- return false, err
- }
-
- if ok {
- return true, nil
- }
- }
-
- return false, nil
-}
-
-// matchRefPrefix reports whether some prefix of ref (possibly ref itself)
-// matches the path.Match pattern prefix, so that the rest of ref is matched by
-// a trailing "**".
-func matchRefPrefix(prefix, ref string) (bool, error) {
- if _, err := path.Match(prefix, ""); err != nil {
- return false, err
- }
-
- for i := len(ref); i >= 0; i-- {
- ok, err := path.Match(prefix, ref[:i])
- if err != nil {
- return false, err
- }
-
- if ok {
- return true, nil
- }
- }
-
- return false, nil
-}
-
-// asciiWhitespace is the whitespace that parseChangedRefs trims around a line.
-const asciiWhitespace = " \t\n\v\f\r"
-
-// parseChangedRefs extracts the reference names from a change set in the
-// "<old-oid> <new-oid> <ref>" per-line format used by the hooks. The reference
-// is taken verbatim, see changelog.ParseHookLine, so that a reference whose
-// name holds Unicode whitespace is matched by its real name. Only ASCII
-// whitespace, which reference names cannot hold, is trimmed around a line.
-// Blank lines are skipped; any other line that is not well formed is an error.
-func parseChangedRefs(changes string) ([]string, error) {
- var refs []string
-
- for _, line := range strings.Split(changes, "\n") {
- line = strings.Trim(line, asciiWhitespace)
- if line == "" {
- continue
- }
-
- _, _, reference, ok := changelog.ParseHookLine(line)
- if !ok {
- return nil, fmt.Errorf("malformed change %q: expected \"<old> <new> <ref>\"", line)
- }
-
- refs = append(refs, reference)
- }
-
- return refs, nil
-}
diff --git a/internal/gitlab/standalone_client_test.go b/internal/gitlab/standalone_client_test.go
index dac5bc2..cb02a11 100644
--- a/internal/gitlab/standalone_client_test.go
+++ b/internal/gitlab/standalone_client_test.go
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/feder-cr/git-ai/internal/gitaly/config"
+ "github.com/feder-cr/git-ai/internal/graft/policyeval"
"github.com/feder-cr/git-ai/internal/testhelper"
"github.com/stretchr/testify/require"
)
@@ -385,60 +386,6 @@ func TestStandaloneClient_Allowed_IgnoresOtherParams(t *testing.T) {
require.Empty(t, msg)
}
-// TestEvaluatePolicy checks the policy evaluation that the reference-transaction
-// hook shares with Allowed: it must decide exactly like the standalone client.
-func TestEvaluatePolicy(t *testing.T) {
- t.Parallel()
-
- policy := []config.GraftPolicyRule{
- {Actor: "planner", Refs: []string{"refs/heads/main"}, Allow: true},
- {Refs: []string{"refs/heads/main"}, Allow: false},
- {Refs: []string{"refs/heads/**"}, Allow: true},
- }
- client := NewStandaloneClient(config.Graft{Policy: policy}, testhelper.SharedLogger(t))
-
- for _, tc := range []struct {
- desc string
- policy []config.GraftPolicyRule
- actor string
- changes string
- allowed bool
- message string
- err string
- }{
- {desc: "empty policy allows", actor: "builder", changes: changesFor("refs/heads/main"), allowed: true},
- {desc: "privileged actor allowed", policy: policy, actor: "planner", changes: changesFor("refs/heads/main"), allowed: true},
- {desc: "open branch allowed", policy: policy, actor: "builder", changes: changesFor("refs/heads/feature"), allowed: true},
- {desc: "protected branch denied", policy: policy, actor: "builder", changes: changesFor("refs/heads/feature", "refs/heads/main"), message: `policy denies "builder" to update "refs/heads/main" (rule 2)`},
- {desc: "ungoverned reference denied", policy: policy, actor: "builder", changes: changesFor("refs/tags/v1"), message: `policy denies "builder" to update "refs/tags/v1": no matching rule`},
- {desc: "malformed changes", policy: policy, actor: "builder", changes: "only two\n", err: "malformed change"},
- {desc: "reference with Unicode whitespace allowed by its name", policy: policy, actor: "builder", changes: changesFor("refs/heads/a\u00a0b", "refs/heads/x\u0085y"), allowed: true},
- {desc: "reference with Unicode whitespace denied by its name", policy: policy, actor: "builder", changes: changesFor("refs/tags/v\u2000main"), message: `policy denies "builder" to update "refs/tags/v\u2000main": no matching rule`},
- {desc: "reference that is not valid UTF-8 allowed by its name", policy: policy, actor: "builder", changes: changesFor("refs/heads/caf\xe9"), allowed: true},
- {desc: "tab-separated change is malformed", policy: policy, actor: "builder", changes: testOldOID + "\t" + testNewOID + "\trefs/heads/feature\n", err: "malformed change"},
- } {
- t.Run(tc.desc, func(t *testing.T) {
- t.Parallel()
-
- allowed, message, err := EvaluatePolicy(tc.policy, tc.actor, tc.changes)
- if tc.err != "" {
- require.ErrorContains(t, err, tc.err)
- return
- }
- require.NoError(t, err)
- require.Equal(t, tc.allowed, allowed)
- require.Equal(t, tc.message, message)
-
- if tc.policy != nil {
- clientAllowed, clientMessage, err := client.Allowed(testhelper.Context(t), AllowedParams{GLID: tc.actor, Changes: tc.changes})
- require.NoError(t, err)
- require.Equal(t, allowed, clientAllowed)
- require.Equal(t, message, clientMessage)
- }
- })
- }
-}
-
func TestStandaloneClient_Allowed_DoesNotShareConfigPolicy(t *testing.T) {
t.Parallel()
@@ -531,63 +478,57 @@ func TestStandaloneClient_OtherCallbacks(t *testing.T) {
})
}
-func TestMatchRef(t *testing.T) {
+// TestStandaloneClient_AllowedDecidesAsEvaluate checks the policy evaluation that the
+// reference-transaction hook shares with Allowed (policyeval.Evaluate): the standalone client must
+// decide exactly like it.
+func TestStandaloneClient_AllowedDecidesAsEvaluate(t *testing.T) {
t.Parallel()
+ policy := []config.GraftPolicyRule{
+ {Actor: "planner", Refs: []string{"refs/heads/main"}, Allow: true},
+ {Refs: []string{"refs/heads/main"}, Allow: false},
+ {Refs: []string{"refs/heads/**"}, Allow: true},
+ }
+ client := NewStandaloneClient(config.Graft{Policy: policy}, testhelper.SharedLogger(t))
+
for _, tc := range []struct {
- glob string
- ref string
- matches bool
- err bool
+ desc string
+ policy []config.GraftPolicyRule
+ actor string
+ changes string
+ allowed bool
+ message string
+ err string
}{
- {glob: "refs/heads/main", ref: "refs/heads/main", matches: true},
- {glob: "refs/heads/main", ref: "refs/heads/dev", matches: false},
- {glob: "refs/heads/*", ref: "refs/heads/main", matches: true},
- {glob: "refs/heads/*", ref: "refs/heads/a/main", matches: false},
- {glob: "refs/heads/**", ref: "refs/heads/main", matches: true},
- {glob: "refs/heads/**", ref: "refs/heads/a/b/c", matches: true},
- {glob: "refs/heads/**", ref: "refs/heads", matches: false},
- {glob: "refs/heads/**", ref: "refs/tags/v1", matches: false},
- {glob: "refs/heads/**", ref: "refs/headsx/main", matches: false},
- {glob: "refs/*/**", ref: "refs/tags/v1/x", matches: true},
- {glob: "refs/*/**", ref: "refs/tags/v1", matches: true},
- {glob: "**", ref: "refs/heads/main", matches: true},
- {glob: "**", ref: "main", matches: true},
- {glob: "refs/heads/release**", ref: "refs/heads/release/1.0", matches: true},
- {glob: "refs/heads/release**", ref: "refs/heads/release-2", matches: true},
- {glob: "refs/heads/release**", ref: "refs/heads/release", matches: true},
- {glob: "refs/heads/release**", ref: "refs/heads/main", matches: false},
- {glob: "refs/*/rel**", ref: "refs/heads/rel/a/b", matches: true},
- {glob: "refs/heads/[**", ref: "refs/heads/main", err: true},
- {glob: "refs/heads/[", ref: "refs/heads/main", err: true},
- {glob: "refs/heads/[/**", ref: "refs/heads/main", err: true},
- {glob: "refs/heads/[/**", ref: "x", err: true},
+ {desc: "empty policy allows", actor: "builder", changes: changesFor("refs/heads/main"), allowed: true},
+ {desc: "privileged actor allowed", policy: policy, actor: "planner", changes: changesFor("refs/heads/main"), allowed: true},
+ {desc: "open branch allowed", policy: policy, actor: "builder", changes: changesFor("refs/heads/feature"), allowed: true},
+ {desc: "protected branch denied", policy: policy, actor: "builder", changes: changesFor("refs/heads/feature", "refs/heads/main"), message: `policy denies "builder" to update "refs/heads/main" (rule 2)`},
+ {desc: "ungoverned reference denied", policy: policy, actor: "builder", changes: changesFor("refs/tags/v1"), message: `policy denies "builder" to update "refs/tags/v1": no matching rule`},
+ {desc: "malformed changes", policy: policy, actor: "builder", changes: "only two\n", err: "malformed change"},
+ {desc: "reference with Unicode whitespace allowed by its name", policy: policy, actor: "builder", changes: changesFor("refs/heads/a\u00a0b", "refs/heads/x\u0085y"), allowed: true},
+ {desc: "reference with Unicode whitespace denied by its name", policy: policy, actor: "builder", changes: changesFor("refs/tags/v\u2000main"), message: `policy denies "builder" to update "refs/tags/v\u2000main": no matching rule`},
+ {desc: "reference that is not valid UTF-8 allowed by its name", policy: policy, actor: "builder", changes: changesFor("refs/heads/caf\xe9"), allowed: true},
+ {desc: "tab-separated change is malformed", policy: policy, actor: "builder", changes: testOldOID + "\t" + testNewOID + "\trefs/heads/feature\n", err: "malformed change"},
} {
- t.Run(fmt.Sprintf("%s:%s", tc.glob, tc.ref), func(t *testing.T) {
+ t.Run(tc.desc, func(t *testing.T) {
t.Parallel()
- matches, err := matchRef(tc.glob, tc.ref)
- if tc.err {
- require.Error(t, err)
+ allowed, message, err := policyeval.Evaluate(tc.policy, tc.actor, tc.changes)
+ if tc.err != "" {
+ require.ErrorContains(t, err, tc.err)
return
}
require.NoError(t, err)
- require.Equal(t, tc.matches, matches)
+ require.Equal(t, tc.allowed, allowed)
+ require.Equal(t, tc.message, message)
+
+ if tc.policy != nil {
+ clientAllowed, clientMessage, err := client.Allowed(testhelper.Context(t), AllowedParams{GLID: tc.actor, Changes: tc.changes})
+ require.NoError(t, err)
+ require.Equal(t, allowed, clientAllowed)
+ require.Equal(t, message, clientMessage)
+ }
})
}
}
-
-func TestParseChangedRefs(t *testing.T) {
- t.Parallel()
-
- refs, err := parseChangedRefs("")
- require.NoError(t, err)
- require.Empty(t, refs)
-
- refs, err = parseChangedRefs(changesFor("refs/heads/a", "refs/tags/b"))
- require.NoError(t, err)
- require.Equal(t, []string{"refs/heads/a", "refs/tags/b"}, refs)
-
- _, err = parseChangedRefs("only two\n")
- require.Error(t, err)
-}
diff --git a/internal/gitlab/standalone_policy_test.go b/internal/gitlab/standalone_policy_test.go
index 18a6611..e95f760 100644
--- a/internal/gitlab/standalone_policy_test.go
+++ b/internal/gitlab/standalone_policy_test.go
@@ -24,99 +24,6 @@ func policyTestChanges(refs ...string) string {
return b.String()
}
-// TestEvaluatePolicy_HEAD checks that HEAD is decided by the policy like any
-// other reference: it is allowed only by a rule that names it.
-func TestEvaluatePolicy_HEAD(t *testing.T) {
- t.Parallel()
-
- for _, tc := range []struct {
- desc string
- policy []config.GraftPolicyRule
- changes string
- allowed bool
- }{
- {
- desc: "HEAD is denied when only branch rules exist",
- policy: []config.GraftPolicyRule{{Refs: []string{"refs/heads/**"}, Allow: true}},
- changes: policyTestChanges("HEAD"),
- allowed: false,
- },
- {
- desc: "HEAD is allowed by a rule that names it",
- policy: []config.GraftPolicyRule{{Refs: []string{"HEAD"}, Allow: true}},
- changes: policyTestChanges("HEAD"),
- allowed: true,
- },
- {
- desc: "a wildcard rule covers HEAD",
- policy: []config.GraftPolicyRule{{Allow: true}},
- changes: policyTestChanges("HEAD"),
- allowed: true,
- },
- {
- desc: "HEAD and a branch are both needed",
- policy: []config.GraftPolicyRule{{Refs: []string{"refs/heads/**"}, Allow: true}, {Refs: []string{"HEAD"}, Allow: true}},
- changes: policyTestChanges("refs/heads/main", "HEAD"),
- allowed: true,
- },
- {
- desc: "one denied HEAD among allowed branches denies the change set",
- policy: []config.GraftPolicyRule{{Refs: []string{"refs/heads/**"}, Allow: true}},
- changes: policyTestChanges("refs/heads/main", "HEAD"),
- allowed: false,
- },
- } {
- t.Run(tc.desc, func(t *testing.T) {
- t.Parallel()
-
- allowed, _, err := EvaluatePolicy(tc.policy, "agent-a", tc.changes)
- require.NoError(t, err)
- require.Equal(t, tc.allowed, allowed)
- })
- }
-}
-
-// TestEvaluatePolicy_DenialMessages checks the denial messages. They describe
-// the policy decision and do not carry the "GitLab:" prefix of GitLab denials.
-func TestEvaluatePolicy_DenialMessages(t *testing.T) {
- t.Parallel()
-
- policy := []config.GraftPolicyRule{
- {Actor: "agent-*", Refs: []string{"refs/heads/feature/**"}, Allow: true},
- {Actor: "agent-*", Refs: []string{"refs/heads/main"}, Allow: false},
- }
-
- for _, tc := range []struct {
- desc string
- actor string
- changes string
- wantMessage string
- }{
- {
- desc: "explicit deny names the rule",
- actor: "agent-a",
- changes: policyTestChanges("refs/heads/main"),
- wantMessage: `policy denies "agent-a" to update "refs/heads/main" (rule 2)`,
- },
- {
- desc: "no matching rule",
- actor: "agent-a",
- changes: policyTestChanges("HEAD"),
- wantMessage: `policy denies "agent-a" to update "HEAD": no matching rule`,
- },
- } {
- t.Run(tc.desc, func(t *testing.T) {
- t.Parallel()
-
- allowed, message, err := EvaluatePolicy(policy, tc.actor, tc.changes)
- require.NoError(t, err)
- require.False(t, allowed)
- require.Equal(t, tc.wantMessage, message)
- require.False(t, strings.HasPrefix(message, "GitLab:"))
- })
- }
-}
-
// TestStandaloneClient_DenialIsNotGitLabMessage checks the standalone client's
// denial for an update performed with the policy.
func TestStandaloneClient_DenialIsNotGitLabMessage(t *testing.T) {
@@ -136,25 +43,3 @@ func TestStandaloneClient_DenialIsNotGitLabMessage(t *testing.T) {
require.NotEmpty(t, message)
require.False(t, strings.HasPrefix(message, "GitLab:"))
}
-
-// TestEvaluatePolicy_InvalidInput checks that a malformed change set and an
-// invalid glob are reported as errors, not as decisions.
-func TestEvaluatePolicy_InvalidInput(t *testing.T) {
- t.Parallel()
-
- t.Run("malformed change", func(t *testing.T) {
- t.Parallel()
-
- allowed, _, err := EvaluatePolicy([]config.GraftPolicyRule{{Allow: true}}, "agent-a", "garbage\n")
- require.ErrorContains(t, err, "malformed change")
- require.False(t, allowed)
- })
-
- t.Run("invalid ref glob", func(t *testing.T) {
- t.Parallel()
-
- allowed, _, err := EvaluatePolicy([]config.GraftPolicyRule{{Refs: []string{"refs/[heads"}, Allow: true}}, "agent-a", policyTestChanges("HEAD"))
- require.Error(t, err)
- require.False(t, allowed)
- })
-}
diff --git a/internal/graft/changelog/log.go b/internal/graft/changelog/log.go
index 0433778..f9d7c62 100644
--- a/internal/graft/changelog/log.go
+++ b/internal/graft/changelog/log.go
@@ -17,6 +17,8 @@ import (
"syscall"
"time"
"unicode/utf8"
+
+ "github.com/feder-cr/git-ai/internal/graft/refchange"
)
const (
@@ -1086,11 +1088,11 @@ func List(repoPath string, after uint64, limit int) ([]Entry, error) {
// references such as refs/keep-around/*, refs/tmp/* and refs/environments/*,
// symbolic HEAD updates, and the symbolic reference lines that Git 2.46 and
// later report ("ref:<target>") are therefore not recorded. Lines are parsed
-// with ParseHookLine, and lines it rejects are skipped.
+// with refchange.ParseHookLine, and lines it rejects are skipped.
func ParseUpdates(input []byte) []Update {
var updates []Update
for _, line := range strings.Split(string(input), "\n") {
- oldOID, newOID, reference, ok := ParseHookLine(line)
+ oldOID, newOID, reference, ok := refchange.ParseHookLine(line)
if !ok {
continue
}
@@ -1112,36 +1114,3 @@ func ParseUpdates(input []byte) []Update {
return updates
}
-
-// ParseHookLine parses one line of the input of the reference-transaction,
-// pre-receive and post-receive hooks, "<old-value> <new-value> <reference>",
-// without its newline. Git separates the fields with single ASCII spaces and
-// the reference is everything after the second one, kept verbatim: reference
-// names may hold any byte that is not ASCII, including Unicode whitespace such
-// as U+00A0 and bytes that are not valid UTF-8, so the line must not be split on
-// whitespace in general. A trailing carriage return is ignored.
-//
-// ok is false when the line does not have this form: when a field is missing or
-// empty, or when a field holds an ASCII space or control character, which Git
-// does not allow in reference names and object IDs.
-func ParseHookLine(line string) (oldValue, newValue, reference string, ok bool) {
- parts := strings.SplitN(strings.TrimSuffix(line, "\r"), " ", 3)
- if len(parts) != 3 {
- return "", "", "", false
- }
-
- for _, part := range parts {
- if part == "" || strings.ContainsFunc(part, isASCIISpaceOrControl) {
- return "", "", "", false
- }
- }
-
- return parts[0], parts[1], parts[2], true
-}
-
-// isASCIISpaceOrControl reports whether r is the ASCII space or an ASCII control
-// character. Bytes that are not valid UTF-8 decode to utf8.RuneError, which is
-// neither.
-func isASCIISpaceOrControl(r rune) bool {
- return r <= ' ' || r == 0x7f
-}
diff --git a/internal/graft/changelog/log_fuzz_test.go b/internal/graft/changelog/log_fuzz_test.go
index b3b8cf8..9e31cd4 100644
--- a/internal/graft/changelog/log_fuzz_test.go
+++ b/internal/graft/changelog/log_fuzz_test.go
@@ -7,62 +7,13 @@ import (
"testing"
"time"
"unicode/utf8"
+
+ "github.com/feder-cr/git-ai/internal/graft/refchange"
)
const fuzzZeroOID = "0000000000000000000000000000000000000000"
const fuzzOID = "1111111111111111111111111111111111111111"
-// FuzzParseHookLine fuzzes the parser of the reference-transaction hook lines.
-// An accepted line must be exactly the three fields joined by single spaces.
-func FuzzParseHookLine(f *testing.F) {
- for _, seed := range []string{
- fuzzZeroOID + " " + fuzzOID + " refs/heads/main",
- fuzzOID + " " + fuzzZeroOID + " refs/tags/v1.0.0",
- fuzzOID + " " + fuzzOID + " refs/heads/main\r",
- "refs/heads/a b",
- fuzzOID + " " + fuzzOID + " refs/heads/café/\xff\xfe",
- fuzzOID + " " + fuzzOID + " refs/heads/with space",
- "ref:refs/heads/main",
- fuzzOID + " " + fuzzOID,
- " ",
- "",
- fuzzOID + "\t" + fuzzOID + " refs/heads/main",
- fuzzOID + " " + fuzzOID + " ",
- } {
- f.Add(seed)
- }
-
- f.Fuzz(func(t *testing.T, line string) {
- oldValue, newValue, reference, ok := ParseHookLine(line)
-
- if !ok {
- if oldValue != "" || newValue != "" || reference != "" {
- t.Fatalf("rejected line returned fields: %q %q %q", oldValue, newValue, reference)
- }
- return
- }
-
- if oldValue == "" || newValue == "" || reference == "" {
- t.Fatalf("accepted line with an empty field: %q %q %q", oldValue, newValue, reference)
- }
-
- for _, field := range []string{oldValue, newValue} {
- if strings.ContainsFunc(field, isASCIISpaceOrControl) {
- t.Fatalf("accepted object ID with an ASCII space or control character: %q", field)
- }
- }
-
- if got, want := oldValue+" "+newValue+" "+reference, strings.TrimSuffix(line, "\r"); got != want {
- t.Fatalf("fields do not reassemble the line: got %q, want %q", got, want)
- }
-
- o2, n2, r2, ok2 := ParseHookLine(line)
- if o2 != oldValue || n2 != newValue || r2 != reference || ok2 != ok {
- t.Fatal("non-deterministic parse")
- }
- })
-}
-
// FuzzParseUpdates fuzzes the parser of the hook input, which holds one line per
// reference update. Only branches and tags are returned, and no update is a
// no-op.
@@ -94,7 +45,7 @@ func FuzzParseUpdates(f *testing.F) {
}
line := u.OldOID + " " + u.NewOID + " " + u.Reference
- if _, _, _, ok := ParseHookLine(line); !ok {
+ if _, _, _, ok := refchange.ParseHookLine(line); !ok {
t.Fatalf("returned update does not reassemble into a valid line: %+v", u)
}
}
diff --git a/internal/graft/changelog/log_test.go b/internal/graft/changelog/log_test.go
index 2ed0590..5569d1e 100644
--- a/internal/graft/changelog/log_test.go
+++ b/internal/graft/changelog/log_test.go
@@ -659,41 +659,6 @@ func TestParseUpdates(t *testing.T) {
}
}
-func TestParseHookLine(t *testing.T) {
- t.Parallel()
-
- for _, tc := range []struct {
- desc string
- line string
- reference string
- ok bool
- }{
- {desc: "update", line: oidA + " " + oidB + " refs/heads/main", reference: "refs/heads/main", ok: true},
- {desc: "symbolic values", line: "ref:refs/heads/a ref:refs/heads/b HEAD", reference: "HEAD", ok: true},
- {desc: "no-break space", line: oidA + " " + oidB + " refs/heads/a\u00a0b", reference: "refs/heads/a\u00a0b", ok: true},
- {desc: "next line", line: oidA + " " + oidB + " refs/heads/x\u0085y", reference: "refs/heads/x\u0085y", ok: true},
- {desc: "trailing Unicode whitespace", line: oidA + " " + oidB + " refs/heads/z\u2028", reference: "refs/heads/z\u2028", ok: true},
- {desc: "invalid UTF-8", line: oidA + " " + oidB + " refs/heads/caf\xe9", reference: "refs/heads/caf\xe9", ok: true},
- {desc: "trailing carriage return", line: oidA + " " + oidB + " refs/heads/main\r", reference: "refs/heads/main", ok: true},
- {desc: "empty", line: ""},
- {desc: "two fields", line: oidA + " " + oidB},
- {desc: "empty reference", line: oidA + " " + oidB + " "},
- {desc: "space in the reference", line: oidA + " " + oidB + " refs/heads/main extra"},
- {desc: "tab separators", line: oidA + "\t" + oidB + "\trefs/heads/main"},
- {desc: "control character in the reference", line: oidA + " " + oidB + " refs/heads/a\x01b"},
- {desc: "DEL in the reference", line: oidA + " " + oidB + " refs/heads/a\x7fb"},
- {desc: "leading space", line: " " + oidA + " " + oidB + " refs/heads/main"},
- } {
- t.Run(tc.desc, func(t *testing.T) {
- t.Parallel()
-
- _, _, reference, ok := ParseHookLine(tc.line)
- require.Equal(t, tc.ok, ok)
- require.Equal(t, tc.reference, reference)
- })
- }
-}
-
func TestAppend_referencesThatAreNotValidUTF8AreStoredLosslessly(t *testing.T) {
t.Parallel()
diff --git a/internal/graft/corestore/voter/voter.go b/internal/graft/corestore/voter/voter.go
index 975ffdf..621fb55 100644
--- a/internal/graft/corestore/voter/voter.go
+++ b/internal/graft/corestore/voter/voter.go
@@ -42,6 +42,7 @@ import (
"github.com/feder-cr/git-ai/internal/graft/corestore"
"github.com/feder-cr/git-ai/internal/graft/corestore/gitops"
"github.com/feder-cr/git-ai/internal/graft/corestore/localrefs"
+ "github.com/feder-cr/git-ai/internal/graft/refchange"
"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"
@@ -1047,7 +1048,7 @@ func parseInput(changes []byte, hash git.ObjectHash) ([]inputUpdate, error) {
continue
}
- oldValue, newValue, name, ok := changelog.ParseHookLine(line)
+ oldValue, newValue, name, ok := refchange.ParseHookLine(line)
if !ok {
return nil, fmt.Errorf("line %q is not <old> <new> <ref>", line)
}
diff --git a/internal/graft/corestore/voter/voter_test.go b/internal/graft/corestore/voter/voter_test.go
index 71e445d..f0861bd 100644
--- a/internal/graft/corestore/voter/voter_test.go
+++ b/internal/graft/corestore/voter/voter_test.go
@@ -800,7 +800,7 @@ func TestInvalidReferenceNames(t *testing.T) {
"refs/heads/a@{1}",
"refs/heads/a\x01b",
} {
- // changelog.ParseHookLine already rejects a line whose name has a
+ // refchange.ParseHookLine already rejects a line whose name has a
// control character, before the name itself is validated.
lineRejected := strings.ContainsFunc(name, func(r rune) bool { return r < 0x20 || r == 0x7f })
diff --git a/internal/gitaly/hook/graft_policy_export_spec_test.go b/internal/graft/policyeval/evaluate_update_spec_test.go
similarity index 61%
rename from internal/gitaly/hook/graft_policy_export_spec_test.go
rename to internal/graft/policyeval/evaluate_update_spec_test.go
index e7f535d..958b54f 100644
--- a/internal/gitaly/hook/graft_policy_export_spec_test.go
+++ b/internal/graft/policyeval/evaluate_update_spec_test.go
@@ -1,6 +1,6 @@
-package hook
+package policyeval
-// Black-box spec test for the exported wrapper EvaluateGraftPolicy (WP22),
+// Black-box spec test for the exported wrapper EvaluateUpdate (WP22),
// written from doc/graft/PLAN3.md only.
import (
@@ -15,11 +15,11 @@ const (
specWP22NewOID = "1111111111111111111111111111111111111111"
)
-// The spec says EvaluateGraftPolicy is an exported wrapper over graftPolicyDenial
+// The spec says EvaluateUpdate is an exported wrapper over Denial
// with the same semantics. With an empty graft configuration (no policy
// configured) an update must be allowed, with an empty message and no error.
-func TestSpecEvaluateGraftPolicyEmptyConfigAllows(t *testing.T) {
- allowed, message, err := EvaluateGraftPolicy(config.Graft{}, "alice", "refs/heads/main", specWP22ZeroOID, specWP22NewOID)
+func TestSpecEvaluateUpdateEmptyConfigAllows(t *testing.T) {
+ allowed, message, err := EvaluateUpdate(nil, "alice", "refs/heads/main", specWP22ZeroOID, specWP22NewOID)
require.NoError(t, err, "evaluating a well-formed update must not return an error")
require.True(t, allowed, "with no graft policy configured the update must be allowed")
require.Empty(t, message, "an allowed update must not carry a denial message")
@@ -27,10 +27,10 @@ func TestSpecEvaluateGraftPolicyEmptyConfigAllows(t *testing.T) {
// The wrapper is a pure function of its inputs: repeated evaluation of the same
// update must give the same answer.
-func TestSpecEvaluateGraftPolicyIsDeterministic(t *testing.T) {
+func TestSpecEvaluateUpdateIsDeterministic(t *testing.T) {
cfg := config.Graft{}
- a1, m1, err1 := EvaluateGraftPolicy(cfg, "alice", "refs/heads/main", specWP22ZeroOID, specWP22NewOID)
- a2, m2, err2 := EvaluateGraftPolicy(cfg, "alice", "refs/heads/main", specWP22ZeroOID, specWP22NewOID)
+ a1, m1, err1 := EvaluateUpdate(cfg.Policy, "alice", "refs/heads/main", specWP22ZeroOID, specWP22NewOID)
+ a2, m2, err2 := EvaluateUpdate(cfg.Policy, "alice", "refs/heads/main", specWP22ZeroOID, specWP22NewOID)
require.Equal(t, err1, err2)
require.Equal(t, a1, a2, "same inputs must give the same allowed value")
require.Equal(t, m1, m2, "same inputs must give the same message")
diff --git a/internal/graft/policyeval/policyeval.go b/internal/graft/policyeval/policyeval.go
new file mode 100644
index 0000000..421e5ea
--- /dev/null
+++ b/internal/graft/policyeval/policyeval.go
@@ -0,0 +1,257 @@
+// Package policyeval evaluates the standalone access policy ([[graft.policy]]) for reference
+// updates. The pre-receive access check of the standalone client, the reference-transaction hook,
+// the admission of a land batch and graft policy check all decide with it, so that an update is
+// held to the same policy whoever checks it. It depends on no part of the server, so that the
+// clients build for every platform.
+package policyeval
+
+import (
+ "fmt"
+ "path"
+ "strings"
+
+ "github.com/feder-cr/git-ai/internal/gitaly/config"
+ "github.com/feder-cr/git-ai/internal/graft/refchange"
+)
+
+// EvaluateUpdate evaluates policy for the update of reference from oldOID to newOID by actor. It
+// applies the same rules as the reference-transaction hook: references outside refs/ and HEAD are
+// not governed. When allowed is false, message holds the reason of the denial. The caller decides
+// whether the policy applies to the update, for example only to agent callers, as the hook does.
+func EvaluateUpdate(policy []config.GraftPolicyRule, actor, reference, oldOID, newOID string) (bool, string, error) {
+ changes := fmt.Sprintf("%s %s %s\n", oldOID, newOID, reference)
+
+ message, err := Denial(policy, actor, []byte(changes))
+ if err != nil {
+ return false, "", fmt.Errorf("evaluating graft policy: %w", err)
+ }
+
+ return message == "", message, nil
+}
+
+// Denial returns the message of the denial of the update of the governed references in changes
+// by actor, or an empty message when the policy allows the update. Only references under refs/
+// and HEAD are governed, see isGovernedReference.
+func Denial(policy []config.GraftPolicyRule, actor string, changes []byte) (string, error) {
+ var governed strings.Builder
+ for _, line := range strings.Split(string(changes), "\n") {
+ // Lines that are not well formed are kept, so that the policy rejects them.
+ if _, _, reference, ok := refchange.ParseHookLine(line); ok && !isGovernedReference(reference) {
+ continue
+ }
+
+ governed.WriteString(line)
+ governed.WriteString("\n")
+ }
+
+ allowed, message, err := Evaluate(policy, actor, governed.String())
+ if err != nil {
+ return "", err
+ }
+
+ if allowed {
+ return "", nil
+ }
+
+ return message, nil
+}
+
+// isGovernedReference reports whether the standalone access policy governs an
+// update of reference: every reference under refs/, and HEAD.
+func isGovernedReference(reference string) bool {
+ return reference == "HEAD" || strings.HasPrefix(reference, "refs/")
+}
+
+// Evaluate decides whether actor may apply changes under the ordered
+// [graft] policy. changes uses the "<old-oid> <new-oid> <ref>" per-line format
+// of the pre-receive and reference-transaction hooks. An empty policy allows
+// everything. Otherwise every changed reference must be allowed by the first
+// rule that applies to it, and a reference that no rule applies to is denied.
+// A denial is reported as (false, message, nil); a malformed change set or an
+// invalid glob in the policy is reported as an error.
+//
+// The pre-receive access check of the standalone client and the
+// reference-transaction hook both use it, so that a reference update is held to
+// the same policy whichever RPC performs it.
+func Evaluate(policy []config.GraftPolicyRule, actor, changes string) (bool, string, error) {
+ if len(policy) == 0 {
+ return true, "", nil
+ }
+
+ refs, err := parseChangedRefs(changes)
+ if err != nil {
+ return false, "", err
+ }
+
+ for _, ref := range refs {
+ decision, err := decide(policy, actor, ref)
+ if err != nil {
+ return false, "", err
+ }
+
+ if decision.allowed {
+ continue
+ }
+
+ if decision.rule < 0 {
+ return false, fmt.Sprintf("policy denies %q to update %q: no matching rule", actor, ref), nil
+ }
+
+ return false, fmt.Sprintf("policy denies %q to update %q (rule %d)", actor, ref, decision.rule+1), nil
+ }
+
+ return true, "", nil
+}
+
+// policyDecision is the outcome of evaluating the policy for one reference.
+type policyDecision struct {
+ allowed bool
+ // rule is the zero-based index of the deciding rule, or -1 when no rule applies.
+ rule int
+}
+
+// decide returns the decision of the first rule that applies to actor and ref.
+// A reference that no rule applies to is denied.
+func decide(policy []config.GraftPolicyRule, actor, ref string) (policyDecision, error) {
+ for i, rule := range policy {
+ matched, err := ruleApplies(rule, actor, ref)
+ if err != nil {
+ return policyDecision{}, err
+ }
+
+ if matched {
+ return policyDecision{allowed: rule.Allow, rule: i}, nil
+ }
+ }
+
+ return policyDecision{allowed: false, rule: -1}, nil
+}
+
+// ruleApplies reports whether rule governs the update of ref by actor. An
+// empty or "*" actor matches everybody. Empty Refs match every reference.
+func ruleApplies(rule config.GraftPolicyRule, actor, ref string) (bool, error) {
+ if rule.Actor != "" && rule.Actor != "*" {
+ ok, err := path.Match(rule.Actor, actor)
+ if err != nil {
+ return false, fmt.Errorf("policy actor %q: %w", rule.Actor, err)
+ }
+
+ if !ok {
+ return false, nil
+ }
+ }
+
+ if len(rule.Refs) == 0 {
+ return true, nil
+ }
+
+ for _, glob := range rule.Refs {
+ ok, err := matchRef(glob, ref)
+ if err != nil {
+ return false, fmt.Errorf("policy ref %q: %w", glob, err)
+ }
+
+ if ok {
+ return true, nil
+ }
+ }
+
+ return false, nil
+}
+
+// matchRef matches a fully qualified reference name against a policy glob.
+// Globs use path.Match syntax. A trailing "/**" matches the prefix at any
+// depth: "refs/heads/**" matches "refs/heads/main" and "refs/heads/a/b" but
+// not "refs/heads" itself. Any other "**" suffix matches any remainder,
+// including "/": "refs/heads/release**" matches "refs/heads/release/1.0" and
+// "refs/heads/release-2". A bare "**" matches every reference.
+func matchRef(glob, ref string) (bool, error) {
+ if glob == "**" {
+ return true, nil
+ }
+
+ prefix, deep := strings.CutSuffix(glob, "/**")
+ if !deep {
+ if loose, ok := strings.CutSuffix(glob, "**"); ok {
+ return matchRefPrefix(loose, ref)
+ }
+
+ return path.Match(glob, ref)
+ }
+
+ // Validate the pattern up front: path.Match only reports a malformed
+ // pattern when it gets to examine it against a candidate.
+ if _, err := path.Match(prefix, ""); err != nil {
+ return false, err
+ }
+
+ // Every "/" in ref ends a candidate directory prefix of ref. Any of them
+ // matching the glob prefix means ref lies at or below that directory.
+ for i := 0; i < len(ref); i++ {
+ if ref[i] != '/' {
+ continue
+ }
+
+ ok, err := path.Match(prefix, ref[:i])
+ if err != nil {
+ return false, err
+ }
+
+ if ok {
+ return true, nil
+ }
+ }
+
+ return false, nil
+}
+
+// matchRefPrefix reports whether some prefix of ref (possibly ref itself)
+// matches the path.Match pattern prefix, so that the rest of ref is matched by
+// a trailing "**".
+func matchRefPrefix(prefix, ref string) (bool, error) {
+ if _, err := path.Match(prefix, ""); err != nil {
+ return false, err
+ }
+
+ for i := len(ref); i >= 0; i-- {
+ ok, err := path.Match(prefix, ref[:i])
+ if err != nil {
+ return false, err
+ }
+
+ if ok {
+ return true, nil
+ }
+ }
+
+ return false, nil
+}
+
+// asciiWhitespace is the whitespace that parseChangedRefs trims around a line.
+const asciiWhitespace = " \t\n\v\f\r"
+
+// parseChangedRefs extracts the reference names from a change set in the
+// "<old-oid> <new-oid> <ref>" per-line format used by the hooks. The reference
+// is taken verbatim, see refchange.ParseHookLine, so that a reference whose
+// name holds Unicode whitespace is matched by its real name. Only ASCII
+// whitespace, which reference names cannot hold, is trimmed around a line.
+// Blank lines are skipped; any other line that is not well formed is an error.
+func parseChangedRefs(changes string) ([]string, error) {
+ var refs []string
+
+ for _, line := range strings.Split(changes, "\n") {
+ line = strings.Trim(line, asciiWhitespace)
+ if line == "" {
+ continue
+ }
+
+ _, _, reference, ok := refchange.ParseHookLine(line)
+ if !ok {
+ return nil, fmt.Errorf("malformed change %q: expected \"<old> <new> <ref>\"", line)
+ }
+
+ refs = append(refs, reference)
+ }
+
+ return refs, nil
+}
diff --git a/internal/gitlab/policy_fuzz_test.go b/internal/graft/policyeval/policyeval_fuzz_test.go
similarity index 93%
rename from internal/gitlab/policy_fuzz_test.go
rename to internal/graft/policyeval/policyeval_fuzz_test.go
index 6c6bf35..7aa2154 100644
--- a/internal/gitlab/policy_fuzz_test.go
+++ b/internal/graft/policyeval/policyeval_fuzz_test.go
@@ -1,11 +1,11 @@
-package gitlab
+package policyeval
import (
"strings"
"testing"
"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/refchange"
)
// FuzzParseChangedRefs fuzzes the parser of the change set that the standalone
@@ -39,7 +39,7 @@ func FuzzParseChangedRefs(f *testing.F) {
t.Fatal("empty reference returned")
}
- if _, _, _, ok := changelog.ParseHookLine(fuzzPolicyOID + " " + fuzzPolicyOID + " " + ref); !ok {
+ if _, _, _, ok := refchange.ParseHookLine(fuzzPolicyOID + " " + fuzzPolicyOID + " " + ref); !ok {
t.Fatalf("reference %q does not form a valid hook line", ref)
}
}
@@ -95,10 +95,10 @@ func FuzzMatchRef(f *testing.F) {
})
}
-// FuzzEvaluatePolicy fuzzes the policy decision for a change set. An allowed
+// FuzzEvaluate fuzzes the policy decision for a change set. An allowed
// change set must be made of references that the single rule of the policy
// allows, and a denial must come with a message.
-func FuzzEvaluatePolicy(f *testing.F) {
+func FuzzEvaluate(f *testing.F) {
f.Add(fuzzPolicyOID+" "+fuzzPolicyOID+" refs/heads/main\n", "agent-1", true, "refs/heads/**")
f.Add(fuzzPolicyOID+" "+fuzzPolicyOID+" refs/heads/main\n", "agent-1", false, "refs/heads/main")
f.Add(fuzzPolicyOID+" "+fuzzPolicyOID+" refs/tags/v1\n", "agent-1", true, "refs/heads/**")
@@ -112,7 +112,7 @@ func FuzzEvaluatePolicy(f *testing.F) {
policy = []config.GraftPolicyRule{{Actor: "*", Refs: []string{refGlob}, Allow: allow}}
}
- allowed, message, err := EvaluatePolicy(policy, actor, changes)
+ allowed, message, err := Evaluate(policy, actor, changes)
if err != nil {
if allowed {
t.Fatal("allowed together with an error")
diff --git a/internal/graft/policyeval/policyeval_test.go b/internal/graft/policyeval/policyeval_test.go
new file mode 100644
index 0000000..a336d32
--- /dev/null
+++ b/internal/graft/policyeval/policyeval_test.go
@@ -0,0 +1,210 @@
+package policyeval
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/feder-cr/git-ai/internal/gitaly/config"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ testOldOID = "1111111111111111111111111111111111111111"
+ testNewOID = "2222222222222222222222222222222222222222"
+ policyTestOld = "0000000000000000000000000000000000000000"
+ policyTestNew = "2222222222222222222222222222222222222222"
+)
+
+// changesFor builds a change set in the "<old> <new> <ref>" per-line format.
+func changesFor(refs ...string) string {
+ out := ""
+ for _, ref := range refs {
+ out += testOldOID + " " + testNewOID + " " + ref + "\n"
+ }
+ return out
+}
+
+func policyTestChanges(refs ...string) string {
+ var b strings.Builder
+ for _, ref := range refs {
+ fmt.Fprintf(&b, "%s %s %s\n", policyTestOld, policyTestNew, ref)
+ }
+ return b.String()
+}
+
+func TestMatchRef(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ glob string
+ ref string
+ matches bool
+ err bool
+ }{
+ {glob: "refs/heads/main", ref: "refs/heads/main", matches: true},
+ {glob: "refs/heads/main", ref: "refs/heads/dev", matches: false},
+ {glob: "refs/heads/*", ref: "refs/heads/main", matches: true},
+ {glob: "refs/heads/*", ref: "refs/heads/a/main", matches: false},
+ {glob: "refs/heads/**", ref: "refs/heads/main", matches: true},
+ {glob: "refs/heads/**", ref: "refs/heads/a/b/c", matches: true},
+ {glob: "refs/heads/**", ref: "refs/heads", matches: false},
+ {glob: "refs/heads/**", ref: "refs/tags/v1", matches: false},
+ {glob: "refs/heads/**", ref: "refs/headsx/main", matches: false},
+ {glob: "refs/*/**", ref: "refs/tags/v1/x", matches: true},
+ {glob: "refs/*/**", ref: "refs/tags/v1", matches: true},
+ {glob: "**", ref: "refs/heads/main", matches: true},
+ {glob: "**", ref: "main", matches: true},
+ {glob: "refs/heads/release**", ref: "refs/heads/release/1.0", matches: true},
+ {glob: "refs/heads/release**", ref: "refs/heads/release-2", matches: true},
+ {glob: "refs/heads/release**", ref: "refs/heads/release", matches: true},
+ {glob: "refs/heads/release**", ref: "refs/heads/main", matches: false},
+ {glob: "refs/*/rel**", ref: "refs/heads/rel/a/b", matches: true},
+ {glob: "refs/heads/[**", ref: "refs/heads/main", err: true},
+ {glob: "refs/heads/[", ref: "refs/heads/main", err: true},
+ {glob: "refs/heads/[/**", ref: "refs/heads/main", err: true},
+ {glob: "refs/heads/[/**", ref: "x", err: true},
+ } {
+ t.Run(fmt.Sprintf("%s:%s", tc.glob, tc.ref), func(t *testing.T) {
+ t.Parallel()
+
+ matches, err := matchRef(tc.glob, tc.ref)
+ if tc.err {
+ require.Error(t, err)
+ return
+ }
+ require.NoError(t, err)
+ require.Equal(t, tc.matches, matches)
+ })
+ }
+}
+
+func TestParseChangedRefs(t *testing.T) {
+ t.Parallel()
+
+ refs, err := parseChangedRefs("")
+ require.NoError(t, err)
+ require.Empty(t, refs)
+
+ refs, err = parseChangedRefs(changesFor("refs/heads/a", "refs/tags/b"))
+ require.NoError(t, err)
+ require.Equal(t, []string{"refs/heads/a", "refs/tags/b"}, refs)
+
+ _, err = parseChangedRefs("only two\n")
+ require.Error(t, err)
+}
+
+// TestEvaluatePolicy_HEAD checks that HEAD is decided by the policy like any
+// other reference: it is allowed only by a rule that names it.
+func TestEvaluate_HEAD(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ policy []config.GraftPolicyRule
+ changes string
+ allowed bool
+ }{
+ {
+ desc: "HEAD is denied when only branch rules exist",
+ policy: []config.GraftPolicyRule{{Refs: []string{"refs/heads/**"}, Allow: true}},
+ changes: policyTestChanges("HEAD"),
+ allowed: false,
+ },
+ {
+ desc: "HEAD is allowed by a rule that names it",
+ policy: []config.GraftPolicyRule{{Refs: []string{"HEAD"}, Allow: true}},
+ changes: policyTestChanges("HEAD"),
+ allowed: true,
+ },
+ {
+ desc: "a wildcard rule covers HEAD",
+ policy: []config.GraftPolicyRule{{Allow: true}},
+ changes: policyTestChanges("HEAD"),
+ allowed: true,
+ },
+ {
+ desc: "HEAD and a branch are both needed",
+ policy: []config.GraftPolicyRule{{Refs: []string{"refs/heads/**"}, Allow: true}, {Refs: []string{"HEAD"}, Allow: true}},
+ changes: policyTestChanges("refs/heads/main", "HEAD"),
+ allowed: true,
+ },
+ {
+ desc: "one denied HEAD among allowed branches denies the change set",
+ policy: []config.GraftPolicyRule{{Refs: []string{"refs/heads/**"}, Allow: true}},
+ changes: policyTestChanges("refs/heads/main", "HEAD"),
+ allowed: false,
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ allowed, _, err := Evaluate(tc.policy, "agent-a", tc.changes)
+ require.NoError(t, err)
+ require.Equal(t, tc.allowed, allowed)
+ })
+ }
+}
+
+// TestEvaluatePolicy_DenialMessages checks the denial messages. They describe
+// the policy decision and do not carry the "GitLab:" prefix of GitLab denials.
+func TestEvaluate_DenialMessages(t *testing.T) {
+ t.Parallel()
+
+ policy := []config.GraftPolicyRule{
+ {Actor: "agent-*", Refs: []string{"refs/heads/feature/**"}, Allow: true},
+ {Actor: "agent-*", Refs: []string{"refs/heads/main"}, Allow: false},
+ }
+
+ for _, tc := range []struct {
+ desc string
+ actor string
+ changes string
+ wantMessage string
+ }{
+ {
+ desc: "explicit deny names the rule",
+ actor: "agent-a",
+ changes: policyTestChanges("refs/heads/main"),
+ wantMessage: `policy denies "agent-a" to update "refs/heads/main" (rule 2)`,
+ },
+ {
+ desc: "no matching rule",
+ actor: "agent-a",
+ changes: policyTestChanges("HEAD"),
+ wantMessage: `policy denies "agent-a" to update "HEAD": no matching rule`,
+ },
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ allowed, message, err := Evaluate(policy, tc.actor, tc.changes)
+ require.NoError(t, err)
+ require.False(t, allowed)
+ require.Equal(t, tc.wantMessage, message)
+ require.False(t, strings.HasPrefix(message, "GitLab:"))
+ })
+ }
+}
+
+// TestEvaluatePolicy_InvalidInput checks that a malformed change set and an
+// invalid glob are reported as errors, not as decisions.
+func TestEvaluate_InvalidInput(t *testing.T) {
+ t.Parallel()
+
+ t.Run("malformed change", func(t *testing.T) {
+ t.Parallel()
+
+ allowed, _, err := Evaluate([]config.GraftPolicyRule{{Allow: true}}, "agent-a", "garbage\n")
+ require.ErrorContains(t, err, "malformed change")
+ require.False(t, allowed)
+ })
+
+ t.Run("invalid ref glob", func(t *testing.T) {
+ t.Parallel()
+
+ allowed, _, err := Evaluate([]config.GraftPolicyRule{{Refs: []string{"refs/[heads"}, Allow: true}}, "agent-a", policyTestChanges("HEAD"))
+ require.Error(t, err)
+ require.False(t, allowed)
+ })
+}
diff --git a/internal/graft/policyeval/testhelper_test.go b/internal/graft/policyeval/testhelper_test.go
new file mode 100644
index 0000000..ac35168
--- /dev/null
+++ b/internal/graft/policyeval/testhelper_test.go
@@ -0,0 +1,11 @@
+package policyeval
+
+import (
+ "testing"
+
+ "github.com/feder-cr/git-ai/internal/testhelper"
+)
+
+func TestMain(m *testing.M) {
+ testhelper.Run(m)
+}
diff --git a/internal/graft/refchange/refchange.go b/internal/graft/refchange/refchange.go
new file mode 100644
index 0000000..b722fc6
--- /dev/null
+++ b/internal/graft/refchange/refchange.go
@@ -0,0 +1,38 @@
+// Package refchange parses the reference updates that Git gives its hooks. It has no dependency
+// beyond the standard library, so that clients built for any platform can use it.
+package refchange
+
+import "strings"
+
+// ParseHookLine parses one line of the input of the reference-transaction,
+// pre-receive and post-receive hooks, "<old-value> <new-value> <reference>",
+// without its newline. Git separates the fields with single ASCII spaces and
+// the reference is everything after the second one, kept verbatim: reference
+// names may hold any byte that is not ASCII, including Unicode whitespace such
+// as U+00A0 and bytes that are not valid UTF-8, so the line must not be split on
+// whitespace in general. A trailing carriage return is ignored.
+//
+// ok is false when the line does not have this form: when a field is missing or
+// empty, or when a field holds an ASCII space or control character, which Git
+// does not allow in reference names and object IDs.
+func ParseHookLine(line string) (oldValue, newValue, reference string, ok bool) {
+ parts := strings.SplitN(strings.TrimSuffix(line, "\r"), " ", 3)
+ if len(parts) != 3 {
+ return "", "", "", false
+ }
+
+ for _, part := range parts {
+ if part == "" || strings.ContainsFunc(part, isASCIISpaceOrControl) {
+ return "", "", "", false
+ }
+ }
+
+ return parts[0], parts[1], parts[2], true
+}
+
+// isASCIISpaceOrControl reports whether r is the ASCII space or an ASCII control
+// character. Bytes that are not valid UTF-8 decode to utf8.RuneError, which is
+// neither.
+func isASCIISpaceOrControl(r rune) bool {
+ return r <= ' ' || r == 0x7f
+}
diff --git a/internal/graft/refchange/refchange_test.go b/internal/graft/refchange/refchange_test.go
new file mode 100644
index 0000000..3e126d7
--- /dev/null
+++ b/internal/graft/refchange/refchange_test.go
@@ -0,0 +1,101 @@
+package refchange
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ oidA = "1111111111111111111111111111111111111111"
+ oidB = "2222222222222222222222222222222222222222"
+ fuzzZeroOID = "0000000000000000000000000000000000000000"
+ fuzzOID = "1111111111111111111111111111111111111111"
+)
+
+func TestParseHookLine(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ line string
+ reference string
+ ok bool
+ }{
+ {desc: "update", line: oidA + " " + oidB + " refs/heads/main", reference: "refs/heads/main", ok: true},
+ {desc: "symbolic values", line: "ref:refs/heads/a ref:refs/heads/b HEAD", reference: "HEAD", ok: true},
+ {desc: "no-break space", line: oidA + " " + oidB + " refs/heads/a\u00a0b", reference: "refs/heads/a\u00a0b", ok: true},
+ {desc: "next line", line: oidA + " " + oidB + " refs/heads/x\u0085y", reference: "refs/heads/x\u0085y", ok: true},
+ {desc: "trailing Unicode whitespace", line: oidA + " " + oidB + " refs/heads/z\u2028", reference: "refs/heads/z\u2028", ok: true},
+ {desc: "invalid UTF-8", line: oidA + " " + oidB + " refs/heads/caf\xe9", reference: "refs/heads/caf\xe9", ok: true},
+ {desc: "trailing carriage return", line: oidA + " " + oidB + " refs/heads/main\r", reference: "refs/heads/main", ok: true},
+ {desc: "empty", line: ""},
+ {desc: "two fields", line: oidA + " " + oidB},
+ {desc: "empty reference", line: oidA + " " + oidB + " "},
+ {desc: "space in the reference", line: oidA + " " + oidB + " refs/heads/main extra"},
+ {desc: "tab separators", line: oidA + "\t" + oidB + "\trefs/heads/main"},
+ {desc: "control character in the reference", line: oidA + " " + oidB + " refs/heads/a\x01b"},
+ {desc: "DEL in the reference", line: oidA + " " + oidB + " refs/heads/a\x7fb"},
+ {desc: "leading space", line: " " + oidA + " " + oidB + " refs/heads/main"},
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ _, _, reference, ok := ParseHookLine(tc.line)
+ require.Equal(t, tc.ok, ok)
+ require.Equal(t, tc.reference, reference)
+ })
+ }
+}
+
+// FuzzParseHookLine fuzzes the parser of the reference-transaction hook lines.
+// An accepted line must be exactly the three fields joined by single spaces.
+func FuzzParseHookLine(f *testing.F) {
+ for _, seed := range []string{
+ fuzzZeroOID + " " + fuzzOID + " refs/heads/main",
+ fuzzOID + " " + fuzzZeroOID + " refs/tags/v1.0.0",
+ fuzzOID + " " + fuzzOID + " refs/heads/main\r",
+ "refs/heads/a b",
+ fuzzOID + " " + fuzzOID + " refs/heads/café/\xff\xfe",
+ fuzzOID + " " + fuzzOID + " refs/heads/with space",
+ "ref:refs/heads/main",
+ fuzzOID + " " + fuzzOID,
+ " ",
+ "",
+ fuzzOID + "\t" + fuzzOID + " refs/heads/main",
+ fuzzOID + " " + fuzzOID + " ",
+ } {
+ f.Add(seed)
+ }
+
+ f.Fuzz(func(t *testing.T, line string) {
+ oldValue, newValue, reference, ok := ParseHookLine(line)
+
+ if !ok {
+ if oldValue != "" || newValue != "" || reference != "" {
+ t.Fatalf("rejected line returned fields: %q %q %q", oldValue, newValue, reference)
+ }
+ return
+ }
+
+ if oldValue == "" || newValue == "" || reference == "" {
+ t.Fatalf("accepted line with an empty field: %q %q %q", oldValue, newValue, reference)
+ }
+
+ for _, field := range []string{oldValue, newValue} {
+ if strings.ContainsFunc(field, isASCIISpaceOrControl) {
+ t.Fatalf("accepted object ID with an ASCII space or control character: %q", field)
+ }
+ }
+
+ if got, want := oldValue+" "+newValue+" "+reference, strings.TrimSuffix(line, "\r"); got != want {
+ t.Fatalf("fields do not reassemble the line: got %q, want %q", got, want)
+ }
+
+ o2, n2, r2, ok2 := ParseHookLine(line)
+ if o2 != oldValue || n2 != newValue || r2 != reference || ok2 != ok {
+ t.Fatal("non-deterministic parse")
+ }
+ })
+}
diff --git a/internal/graft/refchange/testhelper_test.go b/internal/graft/refchange/testhelper_test.go
new file mode 100644
index 0000000..47f337f
--- /dev/null
+++ b/internal/graft/refchange/testhelper_test.go
@@ -0,0 +1,11 @@
+package refchange
+
+import (
+ "testing"
+
+ "github.com/feder-cr/git-ai/internal/testhelper"
+)
+
+func TestMain(m *testing.M) {
+ testhelper.Run(m)
+}