Git designed for AI agents.
graft: PLAN12, and the policy store
Federico Elia157ea42cd711
diff --git a/doc/graft/PLAN12.md b/doc/graft/PLAN12.mdnew file mode 100644index 0000000..5c0c572--- /dev/null+++ b/doc/graft/PLAN12.md@@ -0,0 +1,167 @@+# PLAN12: live policy reload and a policy dry-run++Status: approved by the PM on 2026-10-23, with the additions marked (PM).++Scope: the standalone access policy (`[[graft.policy]]`) only. Agents, tokens, `agent_rpcs` and+every other key still need a restart.++## 1. Where the policy lives today (facts)++The policy is part of the server configuration (`config.Graft.Policy`), validated at load by+`config.Graft.Validate` (config_graft.go:541). It is copied by value into four readers at+construction, which is why a change needs a restart:++| reader | where | when it decides |+|---|---|---|+| standalone GitLab client (pre-receive `/allowed`) | `gitlab.NewStandaloneClient(cfg.Graft)`, serve.go:222; copy at standalone_client.go:28 | pre-receive of pushes and OperationService RPCs, before the references are locked |+| reference-transaction hook | `GitLabHookManager.cfg.Graft.Policy`, referencetransaction.go (graftPolicyDecision) | prepared phase, references locked, before the update is committed |+| `CheckAgentPolicy(ctx, graft, …)` | operations server field `graft config.Graft` (server.go:36): UserMergeToRef/RebaseToRef, land_inline, land_reland, land_resolve | before the RPC writes |+| land batch admission | `hook.EvaluateGraftPolicy(st.server.graft, …)`, land_batch_server.go:278 | before a member enters the running tip |++All four run in the gitaly server process (the hook binary calls back into HookService), so one+in-process store serves them all.++## 2. The invariant and the atomic swap++- One `policy.Store` per server process, created in serve.go from the startup configuration and+ injected into the four readers instead of the copied slices. It holds an+ `atomic.Pointer[Snapshot]`; `Snapshot{Rules []config.GraftPolicyRule, Generation uint64,+ SHA256 string}` is immutable once published.+- Invariant: **there is always exactly one valid policy in force.** The pointer is set before+ the server serves and is never nil; a reload builds and validates a complete new snapshot+ first and publishes it with one atomic store. There is no moment with no policy, or with a+ half-applied one.+- Every decision reads `store.Current()` once and decides with that snapshot only (a+ transaction with several references is judged by one generation).+- `config.Graft.Validate` stays the only validation, used at startup and on reload: one rule set,+ one validator.++## 3. An invalid file keeps the old policy++A reload re-reads the configuration file the server was started with, parses it with+`config.Load`, and validates the policy with `config.Graft.Validate`. Any failure (unreadable+file, TOML error, an invalid glob, an empty refs entry) leaves the current snapshot in force and:+- logs at ERROR `policy reload rejected` with the error and the file;+- counts `graft_policy_reloads_total{result="rejected"}`.++A valid file with the same rules (same SHA-256 of the canonical rule list) counts+`result="unchanged"` and publishes nothing. A valid, different file publishes the new snapshot,+logs at INFO `policy reloaded` with the old and new generation, hash and rule count, and counts+`result="applied"`. `graft_policy_generation` (gauge) and `graft_policy_info{sha256}` (1 for the+policy in force) let an operator check what each node runs. Other keys that differ from the+running configuration are named in a WARN (`needs a restart: graft.agent, …`) and not applied.++(PM) The new policy must also be consistent with the agents the server started with. The agents+are not reloaded: a file whose `[[graft.agent]]` entries differ from the running ones is named+in the WARN as needing a restart, and its agents are not applied. An actor of the new policy that+is a plain name (not a glob) and names no configured agent is reported in a WARN too, but does not+reject the policy: an actor can be the user ID of a caller with the shared token, which the policy+also decides on. Without agents every actor is such a user ID, and nothing is reported.++## 4. The trigger: SIGUSR1++- SIGHUP is taken: the default bootstrap treats it as shutdown (bootstrap_default.go:28) and the+ tableflip bootstrap as a graceful upgrade (bootstrap_tableflip.go:57). Changing its meaning+ would break existing operators.+- **Proposed: SIGUSR1** (unused by gitaly and by the Go runtime; gitaly-wrapper forwards every+ signal to the child, main.go:159). systemd: `ExecReload=kill -USR1 $MAINPID`.+- Rejected, a file watch: a save that is half written, an editor's rename, a Kubernetes+ ConfigMap's symlink swap each produce intermediate states; with "invalid keeps the old" they+ are safe but noisy, and a reload then happens when the file system says so, not when the+ operator decides. An explicit signal makes the moment of change the operator's, and+ `graft policy check` (section 6) runs before it. A watch can be added later on top of the+ same reload function if asked.+- Rejected for now, an admin RPC: new proto surface for one operation the signal covers.++Reloads are serialized (one at a time); a signal during a reload starts one more after it.++## 5. Which policy applies to an update in flight++Definition: **an agent's reference update is decided by the policy generation in force when the+reference-transaction hook runs in the prepared phase, while git holds the references' locks.**+That is the last check before the update commits, so:+- a tightening applies to every agent update that reaches the prepared phase after the swap,+ whatever its earlier checks allowed (the pre-receive or CheckAgentPolicy of the old policy only+ produce an earlier, clearer denial);+- a loosening applies to an update whose earlier checks run after the swap; one refused before+ the swap stays refused and the client retries (UserLand already reports it as a denial).++The one exception today is the land batch: the hook does not re-check a batch's members+(they were admitted in process). With a reload, a tightening between a member's admission and+the batch's commit would not apply to it. Fix: the batch records the generation it admitted+its members under, and carries it in the hooks payload of its combined update; the hook refuses+a batch update whose admission generation is not the current one (`policy changed during the+batch`), and the batch executor rebuilds (its existing rebuild path), admitting every member+again under the new snapshot. A member the new policy denies then fails alone, as today.++Callers that are not agents (shared token, unauthenticated) are checked only by pre-receive,+before the references are locked: a swap between their pre-receive and their commit can let one+update through under the old policy. They are administrative callers; this is documented, not+closed.++## 6. `graft policy check FILE` (dry-run)++- Offline part, always: parse FILE as a configuration (`config.Load`), validate its policy with+ `config.Graft.Validate`, print the rules with their numbers. Exit 2 on an invalid policy:+ exactly what the server would reject.+- Against recent changesets, with `-repo R` (repeatable) and `-address`: read the last N+ changesets of each repository (`ListChangesets`, default N = 1000, `--limit`), and for each+ reference update of an agent actor evaluate the candidate policy (`hook.EvaluateGraftPolicy`).+ Print the updates the candidate would deny, with the rule that would deny them, grouped by+ actor and reference; `--json` for scripts.+- Where the data comes from: the changeset log of each repository (file log or the storage+ core's table), through the existing RPC, so no new server surface. The actor of an entry is the+ agent of the token (LIMITATIONS, Security limitations).+- Cost: one streamed RPC per repository, N entries; evaluation is in memory, O(N × rules), a few+ milliseconds for N = 1000. It does not lock or write anything.+- What it cannot show: updates that were refused under the current policy are not in the log, so+ it shows what a candidate would newly deny among what happened, not what it would newly allow.+ Stated in its help text.++## 7. Multi-node and Praefect++- Each gitaly process has its own configuration and store; a reload is per node. Nodes that+ share a storage core (several nodes, one database) can run different generations for the time+ between their reloads. Each node exposes `graft_policy_info{sha256}`; the operations doc says+ to reload every node and compare the hash.+- Praefect is not part of standalone mode (LIMITATIONS): nothing to do there. A Praefect setup+ keeps the per-node behaviour above.+- graceful upgrades (tableflip) start a new process that reads the file at startup: it gets the+ file's policy, as today.++## 8. Tests++- Store: concurrent readers and reloads under -race (readers never see nil or a mixed snapshot;+ generations only grow).+- Reload: valid file → applied, metrics and log; same rules → unchanged; each kind of invalid+ file (unreadable, TOML error, bad glob, empty refs) → rejected, old policy still decides,+ metric and ERROR log; other changed keys → WARN, not applied.+- Signal: SIGUSR1 to a test server process (internal/graft/e2e realNode) reloads; SIGHUP keeps+ its current meaning.+- In flight, real server:+ - tightening: a land of an agent whose pre-receive passed under the old policy, held at the+ prepared phase by a test hook point, while the policy is reloaded to deny it → refused by+ the hook; the branch is unchanged;+ - loosening: an agent refused, the policy reloaded to allow it, the same land again → lands;+ - batch: a batch whose admission generation changes before its commit → the hook refuses the+ combined update, the batch rebuilds under the new policy, the newly denied member fails+ alone, the others land.+- (PM) An invalid policy reloaded while agents land: no decision is ever taken without a policy+ (no nil snapshot, no empty rule list where the startup policy had rules); every land is decided+ by the policy in force before the rejected reload.+- Concurrent lands during reloads: N agents landing in a loop while the policy alternates every+ few ms between two versions; every land either lands and was allowed by the generation the+ hook logged, or was refused; no land is recorded with an actor the policy of its generation+ denied (checked against the changeset log and the hook's log).+- `graft policy check`: invalid file exit 2; a candidate that denies a past update lists it with+ its rule; JSON output; a repository the caller may not read.+- Mutants: the hook reading a stale snapshot (copied at construction) → the tightening test+ fails; the batch generation check removed → the batch test fails.++## 9. Estimate and order++1. Store, injection into the four readers, reload function, metrics, logs: 1 day.+2. SIGUSR1 wiring, the batch generation check: 0.5 day.+3. Tests (store, reload, signal, in flight, concurrent, mutants): 1 day.+4. `graft policy check`: 0.5 day. Docs (CONFIGURATION, LIMITATIONS, operations), then an+ independent review.diff --git a/internal/graft/policystore/store.go b/internal/graft/policystore/store.gonew file mode 100644index 0000000..01b6385--- /dev/null+++ b/internal/graft/policystore/store.go@@ -0,0 +1,244 @@+// Package policystore holds the standalone access policy in force ([[graft.policy]]) and replaces+// it while the server runs (doc/graft/PLAN12.md).+//+// Every reader of the policy (the standalone access check of the pre-receive hook, the+// reference-transaction hook, the policy checks of the operation RPCs and the admission of a land+// batch) reads the Snapshot in force from one Store, once per decision. A Store always holds+// exactly one valid policy: the startup policy before the server serves, and afterwards each policy+// that Reload validated, published with one atomic store. An invalid configuration never replaces+// it.+package policystore++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "reflect"+ "slices"+ "strings"+ "sync"+ "sync/atomic"++ "github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/prometheus/client_golang/prometheus"+)++// Snapshot is one version of the policy. It is never changed once published.+type Snapshot struct {+ // Rules are the rules of the policy, in order.+ Rules []config.GraftPolicyRule+ // Generation numbers the versions of the policy of a Store: 1 at startup, one more for every+ // policy that Reload applies.+ Generation uint64+ // SHA256 is the hash of the rules (Hash), which tells an operator which policy a node runs.+ SHA256 string+}++// Result is the outcome of a reload.+type Result string++const (+ // Applied means that the new policy is in force.+ Applied Result = "applied"+ // Unchanged means that the new configuration has the policy in force.+ Unchanged Result = "unchanged"+ // Rejected means that the configuration could not be read or its policy is invalid: the+ // policy in force stays.+ Rejected Result = "rejected"+)++// Outcome describes a reload.+type Outcome struct {+ Result Result+ // Previous is the policy in force before the reload and Current the one after it, the same+ // Snapshot unless the reload applied a new policy.+ Previous, Current *Snapshot+ // NeedsRestart names the changes of the configuration, outside the policy, that a reload does+ // not apply.+ NeedsRestart []string+ // UnknownActors lists the actors of the new policy that name no configured agent. They are not+ // an error: an actor can be the user ID of a caller with the shared token.+ UnknownActors []string+}++// Store holds the policy in force.+type Store struct {+ current atomic.Pointer[Snapshot]+ // reload serializes reloads, so that generations follow each other.+ reload sync.Mutex++ reloads *prometheus.CounterVec+ generation prometheus.Gauge+ info *prometheus.GaugeVec+}++// New returns a Store whose policy is rules, as generation 1.+func New(rules []config.GraftPolicyRule) *Store {+ s := &Store{+ reloads: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "graft_policy_reloads_total",+ Help: "Reloads of the standalone access policy, by result (applied, unchanged, rejected).",+ }, []string{"result"}),+ generation: prometheus.NewGauge(prometheus.GaugeOpts{+ Name: "graft_policy_generation",+ Help: "Generation of the standalone access policy in force: 1 at startup, one more for every reload that applied a new policy.",+ }),+ info: prometheus.NewGaugeVec(prometheus.GaugeOpts{+ Name: "graft_policy_info",+ Help: "1 for the SHA-256 of the standalone access policy in force.",+ }, []string{"sha256"}),+ }+ s.publish(&Snapshot{Rules: clone(rules), Generation: 1, SHA256: Hash(rules)})+ return s+}++// Current returns the policy in force. It is never nil.+func (s *Store) Current() *Snapshot {+ return s.current.Load()+}++// Describe implements prometheus.Collector.+func (s *Store) Describe(descs chan<- *prometheus.Desc) {+ prometheus.DescribeByCollect(s, descs)+}++// Collect implements prometheus.Collector.+func (s *Store) Collect(metrics chan<- prometheus.Metric) {+ s.reloads.Collect(metrics)+ s.generation.Collect(metrics)+ s.info.Collect(metrics)+}++// Reject records a reload whose configuration could not be read: the policy in force stays.+func (s *Store) Reject() Outcome {+ s.reload.Lock()+ defer s.reload.Unlock()++ s.reloads.WithLabelValues(string(Rejected)).Inc()+ current := s.Current()+ return Outcome{Result: Rejected, Previous: current, Current: current}+}++// Reload replaces the policy in force with the policy of next, a configuration that was read+// again, when that policy is valid and different. running is the [graft] section the server+// started with: next must agree with it outside the policy for the server to be consistent, and+// what differs is reported in Outcome.NeedsRestart and not applied. An invalid policy returns its+// error with the Rejected result, and the policy in force stays.+func (s *Store) Reload(next config.Graft, running config.Graft) (Outcome, error) {+ s.reload.Lock()+ defer s.reload.Unlock()++ previous := s.Current()+ if err := next.Validate(); err != nil {+ s.reloads.WithLabelValues(string(Rejected)).Inc()+ return Outcome{Result: Rejected, Previous: previous, Current: previous}, err+ }++ outcome := Outcome{+ Previous: previous,+ Current: previous,+ NeedsRestart: needsRestart(next, running),+ UnknownActors: unknownActors(next.Policy, running.Agents),+ }++ hash := Hash(next.Policy)+ if hash == previous.SHA256 {+ outcome.Result = Unchanged+ s.reloads.WithLabelValues(string(Unchanged)).Inc()+ return outcome, nil+ }++ outcome.Current = &Snapshot{Rules: clone(next.Policy), Generation: previous.Generation + 1, SHA256: hash}+ s.publish(outcome.Current)+ outcome.Result = Applied+ s.reloads.WithLabelValues(string(Applied)).Inc()+ return outcome, nil+}++// publish puts snapshot in force and updates the gauges.+func (s *Store) publish(snapshot *Snapshot) {+ if previous := s.current.Swap(snapshot); previous != nil {+ s.info.DeleteLabelValues(previous.SHA256)+ }+ s.generation.Set(float64(snapshot.Generation))+ s.info.WithLabelValues(snapshot.SHA256).Set(1)+}++// Hash returns the SHA-256 of rules in a canonical encoding: two policies with the same rules in+// the same order have the same hash, however their files are formatted.+func Hash(rules []config.GraftPolicyRule) string {+ canonical := make([]config.GraftPolicyRule, len(rules))+ for i, rule := range rules {+ canonical[i] = config.GraftPolicyRule{Actor: rule.Actor, Refs: rule.Refs, Allow: rule.Allow}+ if canonical[i].Refs == nil {+ canonical[i].Refs = []string{}+ }+ }+ encoded, err := json.Marshal(canonical)+ if err != nil {+ // The rules are strings and booleans: they always encode.+ panic(fmt.Sprintf("encoding policy rules: %v", err))+ }+ sum := sha256.Sum256(encoded)+ return hex.EncodeToString(sum[:])+}++// needsRestart names what differs between next and running outside the policy: a reload applies the+// policy only.+func needsRestart(next, running config.Graft) []string {+ var changed []string+ if !slices.Equal(next.Agents, running.Agents) {+ changed = append(changed, "graft.agent")+ }+ nextRest, runningRest := next, running+ nextRest.Policy, runningRest.Policy = nil, nil+ nextRest.Agents, runningRest.Agents = nil, nil+ if !reflect.DeepEqual(nextRest, runningRest) {+ changed = append(changed, "graft (other than graft.policy and graft.agent)")+ }+ return changed+}++// unknownActors returns the actors of rules that are plain names, not globs, and name none of+// agents. Without agents every actor is a user ID, so none is reported.+func unknownActors(rules []config.GraftPolicyRule, agents []config.GraftAgent) []string {+ if len(agents) == 0 {+ return nil+ }+ var unknown []string+ for _, rule := range rules {+ if rule.Actor == "" || strings.ContainsAny(rule.Actor, `*?[\`) {+ continue+ }+ known := slices.ContainsFunc(agents, func(agent config.GraftAgent) bool { return agent.Name == rule.Actor })+ if !known && !slices.Contains(unknown, rule.Actor) {+ unknown = append(unknown, rule.Actor)+ }+ }+ return unknown+}++func clone(rules []config.GraftPolicyRule) []config.GraftPolicyRule {+ out := make([]config.GraftPolicyRule, len(rules))+ for i, rule := range rules {+ out[i] = config.GraftPolicyRule{Actor: rule.Actor, Refs: slices.Clone(rule.Refs), Allow: rule.Allow}+ }+ return out+}++type admissionKey struct{}++// WithAdmissionGeneration returns ctx carrying the generation of the policy under which a land+// batch admitted its members. The hooks payload of the batch's combined update carries it, and the+// reference-transaction hook refuses the update when the policy changed since (PLAN12, section 5).+func WithAdmissionGeneration(ctx context.Context, generation uint64) context.Context {+ return context.WithValue(ctx, admissionKey{}, generation)+}++// AdmissionGeneration returns the generation of WithAdmissionGeneration, or 0.+func AdmissionGeneration(ctx context.Context) uint64 {+ generation, _ := ctx.Value(admissionKey{}).(uint64)+ return generation+}diff --git a/internal/graft/policystore/store_test.go b/internal/graft/policystore/store_test.gonew file mode 100644index 0000000..4fcddf8--- /dev/null+++ b/internal/graft/policystore/store_test.go@@ -0,0 +1,221 @@+package policystore++import (+ "context"+ "strings"+ "sync"+ "testing"++ "github.com/prometheus/client_golang/prometheus/testutil"+ "github.com/stretchr/testify/require"++ "github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/feder-cr/git-ai/internal/testhelper"+)++func TestMain(m *testing.M) {+ testhelper.Run(m)+}++var (+ allowMain = []config.GraftPolicyRule{{Actor: "planner", Refs: []string{"refs/heads/main"}, Allow: true}}+ denyAll = []config.GraftPolicyRule{{Actor: "*", Allow: false}}+)++func TestStore_startupPolicy(t *testing.T) {+ t.Parallel()++ s := New(allowMain)+ current := s.Current()+ require.Equal(t, allowMain, current.Rules)+ require.EqualValues(t, 1, current.Generation)+ require.Equal(t, Hash(allowMain), current.SHA256)+ require.Equal(t, 1.0, testutil.ToFloat64(s.generation))+ require.Equal(t, 1.0, testutil.ToFloat64(s.info.WithLabelValues(current.SHA256)))++ // The snapshot does not share the caller's slices.+ rules := []config.GraftPolicyRule{{Actor: "a", Refs: []string{"refs/heads/x"}, Allow: true}}+ s = New(rules)+ rules[0].Refs[0] = "refs/heads/y"+ require.Equal(t, "refs/heads/x", s.Current().Rules[0].Refs[0])+}++func TestStore_reload(t *testing.T) {+ t.Parallel()++ running := config.Graft{Standalone: true, Agents: []config.GraftAgent{{Name: "planner", Token: "t"}}, Policy: allowMain}+ s := New(running.Policy)+ first := s.Current()++ t.Run("same rules, another file layout", func(t *testing.T) {+ next := running+ next.Policy = []config.GraftPolicyRule{{Actor: "planner", Refs: []string{"refs/heads/main"}, Allow: true}}+ outcome, err := s.Reload(next, running)+ require.NoError(t, err)+ require.Equal(t, Unchanged, outcome.Result)+ require.Same(t, first, s.Current())+ })++ t.Run("an invalid policy keeps the one in force", func(t *testing.T) {+ for name, rules := range map[string][]config.GraftPolicyRule{+ "bad actor glob": {{Actor: "[", Allow: true}},+ "bad refs glob": {{Refs: []string{"refs/heads/["}, Allow: true}},+ "empty refs": {{Refs: []string{""}, Allow: false}},+ } {+ next := running+ next.Policy = rules+ outcome, err := s.Reload(next, running)+ require.Error(t, err, name)+ require.Equal(t, Rejected, outcome.Result, name)+ require.Same(t, first, s.Current(), name)+ }+ require.Equal(t, 3.0, testutil.ToFloat64(s.reloads.WithLabelValues(string(Rejected))))+ })++ t.Run("a new policy is applied", func(t *testing.T) {+ next := running+ next.Policy = denyAll+ outcome, err := s.Reload(next, running)+ require.NoError(t, err)+ require.Equal(t, Applied, outcome.Result)+ require.Same(t, first, outcome.Previous)+ require.Equal(t, denyAll, s.Current().Rules)+ require.EqualValues(t, 2, s.Current().Generation)+ require.Empty(t, outcome.NeedsRestart)+ require.Equal(t, 2.0, testutil.ToFloat64(s.generation))+ require.Equal(t, 1.0, testutil.ToFloat64(s.info.WithLabelValues(Hash(denyAll))))+ require.Equal(t, 1, testutil.CollectAndCount(s.info), "only the policy in force is reported")+ })++ t.Run("other changes need a restart and are not applied", func(t *testing.T) {+ next := running+ next.Policy = allowMain+ next.Agents = []config.GraftAgent{{Name: "planner", Token: "t"}, {Name: "builder", Token: "u"}}+ next.AgentRPCs = []string{"/gitaly.SSHService/SSHReceivePack"}+ outcome, err := s.Reload(next, running)+ require.NoError(t, err)+ require.Equal(t, Applied, outcome.Result)+ require.Equal(t, []string{"graft.agent", "graft (other than graft.policy and graft.agent)"}, outcome.NeedsRestart)+ require.EqualValues(t, 3, s.Current().Generation)+ })++ t.Run("actors that name no agent are reported", func(t *testing.T) {+ next := running+ next.Policy = []config.GraftPolicyRule{+ {Actor: "planner", Allow: true},+ {Actor: "builder", Allow: true},+ {Actor: "bot-*", Allow: true},+ {Actor: "builder", Allow: false},+ {Allow: false},+ }+ outcome, err := s.Reload(next, running)+ require.NoError(t, err)+ require.Equal(t, []string{"builder"}, outcome.UnknownActors)++ // Without agents every actor is a user ID.+ require.Empty(t, unknownActors(next.Policy, nil))+ })+}++func TestStore_reject(t *testing.T) {+ t.Parallel()++ s := New(allowMain)+ first := s.Current()+ outcome := s.Reject()+ require.Equal(t, Rejected, outcome.Result)+ require.Same(t, first, outcome.Current)+ require.Same(t, first, s.Current())+ require.Equal(t, 1.0, testutil.ToFloat64(s.reloads.WithLabelValues(string(Rejected))))+}++// TestStore_concurrentReadersAndReloads reads the policy while it is reloaded, valid and invalid+// policies alternating: a reader never sees nil, an empty policy or a generation that goes back,+// and every snapshot it sees is one of the published policies, whole.+func TestStore_concurrentReadersAndReloads(t *testing.T) {+ t.Parallel()++ running := config.Graft{Standalone: true, Policy: allowMain}+ s := New(allowMain)+ valid := map[string][]config.GraftPolicyRule{Hash(allowMain): allowMain, Hash(denyAll): denyAll}++ var wg sync.WaitGroup+ stop := make(chan struct{})+ errs := make(chan string, 8)+ for r := 0; r < 8; r++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ var last uint64+ for {+ select {+ case <-stop:+ return+ default:+ }+ current := s.Current()+ switch {+ case current == nil:+ errs <- "nil snapshot"+ return+ case len(current.Rules) == 0:+ errs <- "empty policy"+ return+ case current.Generation < last:+ errs <- "generation went back"+ return+ }+ rules, ok := valid[current.SHA256]+ if !ok || Hash(current.Rules) != current.SHA256 || len(rules) != len(current.Rules) {+ errs <- "a snapshot that was never published whole"+ return+ }+ last = current.Generation+ }+ }()+ }++ invalid := running+ invalid.Policy = []config.GraftPolicyRule{{Refs: []string{""}}}+ badGlob := running+ badGlob.Policy = []config.GraftPolicyRule{{Actor: "[", Allow: true}}+ for i := 0; i < 500; i++ {+ next := running+ next.Policy = allowMain+ if i%2 == 1 {+ next.Policy = denyAll+ }+ _, err := s.Reload(next, running)+ require.NoError(t, err)+ _, err = s.Reload(invalid, running)+ require.Error(t, err)+ _, err = s.Reload(badGlob, running)+ require.Error(t, err)+ }+ close(stop)+ wg.Wait()+ close(errs)+ for e := range errs {+ require.Fail(t, e)+ }+ // The first reload has the startup policy (unchanged); the 499 after it alternate.+ require.EqualValues(t, 500, s.Current().Generation)+}++func TestHash(t *testing.T) {+ t.Parallel()++ require.Equal(t, Hash([]config.GraftPolicyRule{{Actor: "a"}}), Hash([]config.GraftPolicyRule{{Actor: "a", Refs: []string{}}}))+ require.NotEqual(t, Hash(allowMain), Hash(denyAll))+ require.NotEqual(t, Hash([]config.GraftPolicyRule{{Actor: "a"}, {Actor: "b"}}), Hash([]config.GraftPolicyRule{{Actor: "b"}, {Actor: "a"}}), "order matters")+ require.Len(t, Hash(nil), 64)+ require.False(t, strings.ContainsAny(Hash(allowMain), "ABCDEF"))+}++func TestAdmissionGeneration(t *testing.T) {+ t.Parallel()++ ctx := context.Background()+ require.Zero(t, AdmissionGeneration(ctx))+ require.EqualValues(t, 7, AdmissionGeneration(WithAdmissionGeneration(ctx, 7)))+}