From 71b68933305fe0ca31178562a4faa6205ec98902 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 13 Nov 2026 17:39:28 -0500 Subject: [PATCH 01/12] refactor(repos): add the trace signing key preflight and convergence step EnsureTraceSigningKeys plans the trace signing key of each selected GitHub repository before repos.yaml is written: a fresh install, recovery when FULLSEND_TRACE_SIGNING_KEY is missing or FULLSEND_TRACE_SIGNING_KEY_ID is absent or names a retained key, or a rotation on request. It records the installation ID and public keys in the repository's repos.yaml entry, carving a glob-covered repository into its own entry. Before any edit it refuses an entry that contradicts the committed trace_context or the key ID variable, a key ID variable that is not 16 lowercase hex characters, and a read-only manifest that must record a key. GitLab repositories are skipped without any read. convergeTraceSigningKey writes a plan before the scaffold or config commit. It reads FULLSEND_TRACE_SIGNING_KEY_ID again and stops unless its presence and value are unchanged, then deletes it, writes the seed and sets it to the new key ID, each step only after the one before succeeds. Nothing calls EnsureTraceSigningKeys yet. Signed-off-by: Dharit Shah --- internal/forge/forge.go | 8 + internal/repos/converge.go | 27 + .../managed_config_blocked_install_test.go | 2 +- internal/repos/managed_config_writeback.go | 2 +- internal/repos/manifest_edit.go | 29 +- internal/repos/manifest_signoff_test.go | 2 +- internal/repos/trace_context_helpers_test.go | 39 +- internal/repos/trace_keys.go | 608 +++++++++++++ internal/repos/trace_keys_converge_test.go | 713 +++++++++++++++ internal/repos/trace_keys_test.go | 827 ++++++++++++++++++ .../scaffold/scaffold_env_consistency_test.go | 1 + 11 files changed, 2236 insertions(+), 22 deletions(-) create mode 100644 internal/repos/trace_keys.go create mode 100644 internal/repos/trace_keys_converge_test.go create mode 100644 internal/repos/trace_keys_test.go diff --git a/internal/forge/forge.go b/internal/forge/forge.go index f8f9c69e38..14e5719e6f 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -179,6 +179,14 @@ const ( // SecretTraceSigningKey is the trace-context signing key (ADR 0154). // config.TraceSigningKeySecret is the same literal. SecretTraceSigningKey = "FULLSEND_TRACE_SIGNING_KEY" + // VarTraceSigningKeyID is the repository variable in which repos install + // records which key SecretTraceSigningKey holds, because a secret cannot + // be read back: the key ID (tracecontext.FormatKeyID) of the seed install + // last confirmed writing (ADR 0154). Install deletes it before a seed + // write and sets it after, so it never names a key whose seed the secret + // no longer holds, apart from overlapping installs. It holds no key + // material. Install writes it on GitHub only. + VarTraceSigningKeyID = "FULLSEND_TRACE_SIGNING_KEY_ID" // Legacy uninstall-only variables — GitLab. VarLegacyBotTokenSecret = "FULLSEND_BOT_TOKEN_SECRET" diff --git a/internal/repos/converge.go b/internal/repos/converge.go index f6029c38e7..1ad3695f9c 100644 --- a/internal/repos/converge.go +++ b/internal/repos/converge.go @@ -103,6 +103,13 @@ type ConvergeConfig struct { JiraClientID string JiraClientSecret string + // TraceKeyPlans holds the trace signing key writes planned by + // EnsureTraceSigningKeys, keyed "owner/repo" (ADR 0154). A repository + // with a plan gets FULLSEND_TRACE_SIGNING_KEY and + // FULLSEND_TRACE_SIGNING_KEY_ID before its scaffold or config commit + // (convergeTraceSigningKey). Never logged or reported. + TraceKeyPlans map[string]*TraceKeyPlan + // ReviewAppClientID is the OAuth client ID of the review agent's // GitHub App, pre-resolved by the caller for ReviewAppClientIDAppSet. // It seeds the per-repo resolution cache so repos on that app set @@ -1800,6 +1807,17 @@ func convergeRepo(ctx context.Context, _, staleVendoredActions = applyStaleVendoredPlan(installFiles, plan, cfg.DryRun, repoFullName, progress) } + // The trace signing key is written before Install, so the seed never + // trails the commit that delivers the config naming its key + // (ADR 0154). A dry run reports it; a failure stops the repository + // before Install. + traceActions := convergeTraceSigningKey(ctx, d, cfg, progress) + cr.Actions = append(cr.Actions, traceActions...) + if actionsError(traceActions) != nil { + cr.Error = actionsError(cr.Actions) + return cr + } + if cfg.DryRun { cr.Installed = true if resolved.Forge == ForgeGitLab { @@ -1938,6 +1956,15 @@ func convergeRepo(ctx context.Context, } cr.Actions = append(cr.Actions, convergeJiraPoll(ctx, d, cfg, jiraDelivery, progress)...) + // 2d'': The trace signing key (ADR 0154), before the commit that delivers + // the config naming it. A failure stops the repository here. + traceActions := convergeTraceSigningKey(ctx, d, cfg, progress) + cr.Actions = append(cr.Actions, traceActions...) + if actionsError(traceActions) != nil { + cr.Error = actionsError(cr.Actions) + return cr + } + // 2e: Commit all scaffold file changes in one atomic commit. // Variable/secret writes above are not rolled back on commit failure; // the next Converge run self-heals (writes become no-ops, commit retries). diff --git a/internal/repos/managed_config_blocked_install_test.go b/internal/repos/managed_config_blocked_install_test.go index 6793d0ef63..d3f17b199e 100644 --- a/internal/repos/managed_config_blocked_install_test.go +++ b/internal/repos/managed_config_blocked_install_test.go @@ -30,7 +30,7 @@ func assertNoForgeWrites(t *testing.T, fc *forge.FakeClient) { assert.Empty(t, fc.ForceCommittedFiles, "no forced commits") assert.Empty(t, fc.CreatedBranches, "no branches") assert.Empty(t, fc.CreatedProposals, "no PR/MR") - assert.Empty(t, fc.CreatedSecrets, "no secret writes") + assert.Zero(t, len(fc.CreatedSecrets), "no secret writes") assert.Empty(t, fc.DeletedSecrets, "no secret deletions") assert.Empty(t, fc.Variables, "no variable writes") assert.Empty(t, fc.UpdatedVariables, "no variable updates") diff --git a/internal/repos/managed_config_writeback.go b/internal/repos/managed_config_writeback.go index 795b494eed..1a0f9420a0 100644 --- a/internal/repos/managed_config_writeback.go +++ b/internal/repos/managed_config_writeback.go @@ -548,7 +548,7 @@ func newEntrySuggestion(m *Manifest, p pendingWriteback) RepoEntry { entry = *existing } else if platform := m.PlatformFor(p.rr.Forge); platform != nil { scratch := &PlatformConfig{Repos: slices.Clone(platform.Repos)} - if carved, _ := carveOutGlobEntry([]*PlatformConfig{scratch}, name); carved != nil { + if carved, _, _ := carveOutGlobEntry([]*PlatformConfig{scratch}, name); carved != nil { entry = *carved } } diff --git a/internal/repos/manifest_edit.go b/internal/repos/manifest_edit.go index ff8e17f660..7b73c50f7a 100644 --- a/internal/repos/manifest_edit.go +++ b/internal/repos/manifest_edit.go @@ -28,7 +28,7 @@ type ManifestRemoveResult struct { // carveOutForForge carves an explicit entry for name from the covering glob // in the discovered forge section, or from the first covering glob across // forges (GitHub before GitLab) when discovered is empty. It returns the new -// entry and the forge section it was added to. +// entry and the name of the glob entry it was copied from. func carveOutForForge(m *Manifest, name, discovered string) (*RepoEntry, string, error) { order := []string{ForgeGitHub, ForgeGitLab} if discovered != "" { @@ -39,22 +39,33 @@ func carveOutForForge(m *Manifest, name, discovered string) (*RepoEntry, string, if platform == nil { continue } - carved, err := carveOutGlobEntry([]*PlatformConfig{platform}, name) + carved, glob, err := carveOutGlobEntry([]*PlatformConfig{platform}, name) if err != nil { return nil, "", err } if carved != nil { - return carved, forgeName, nil + return carved, glob, nil } } return nil, "", nil } +// manifestEntryWhere names, for a progress line, the manifest entry of name +// that an edit went into: its existing entry when glob is "", else the new +// entry copied from the glob entry glob. A new entry no longer follows +// edits to its glob, so the line names both. +func manifestEntryWhere(name, glob string) string { + if glob == "" { + return "the manifest entry" + } + return fmt.Sprintf("the new manifest entry %s, copied from the glob entry %s", name, glob) +} + // carveOutGlobEntry appends an explicit entry for name copied from the first // glob entry (GitHub before GitLab, matching resolution order) that covers -// it, and returns a pointer to the new entry. It returns nil when no glob -// covers name. -func carveOutGlobEntry(platforms []*PlatformConfig, name string) (*RepoEntry, error) { +// it, and returns a pointer to the new entry and the glob entry's name. It +// returns nil when no glob covers name. +func carveOutGlobEntry(platforms []*PlatformConfig, name string) (*RepoEntry, string, error) { for _, platform := range platforms { if platform == nil { continue @@ -65,7 +76,7 @@ func carveOutGlobEntry(platforms []*PlatformConfig, name string) (*RepoEntry, er } ok, err := matchesPattern(entry.Name, name) if err != nil { - return nil, fmt.Errorf("invalid manifest repo pattern %q: %w", entry.Name, err) + return nil, "", fmt.Errorf("invalid manifest repo pattern %q: %w", entry.Name, err) } if !ok { continue @@ -82,10 +93,10 @@ func carveOutGlobEntry(platforms []*PlatformConfig, name string) (*RepoEntry, er explicit.Signoff = &s } platform.Repos = append(platform.Repos, explicit) - return &platform.Repos[len(platform.Repos)-1], nil + return &platform.Repos[len(platform.Repos)-1], entry.Name, nil } } - return nil, nil + return nil, "", nil } // RemoveFromManifest removes matching repo entries from all platform diff --git a/internal/repos/manifest_signoff_test.go b/internal/repos/manifest_signoff_test.go index a40a370114..678cc34912 100644 --- a/internal/repos/manifest_signoff_test.go +++ b/internal/repos/manifest_signoff_test.go @@ -265,7 +265,7 @@ func TestCarveOutGlobEntry_CopiesSignoff(t *testing.T) { signoff := true platform := &PlatformConfig{Repos: []RepoEntry{{Name: "acme/*", Signoff: &signoff}}} - carved, err := carveOutGlobEntry([]*PlatformConfig{platform}, "acme/api") + carved, _, err := carveOutGlobEntry([]*PlatformConfig{platform}, "acme/api") require.NoError(t, err) require.NotNil(t, carved) require.NotNil(t, carved.Signoff) diff --git a/internal/repos/trace_context_helpers_test.go b/internal/repos/trace_context_helpers_test.go index 1d7e4c38ac..4fa52affcf 100644 --- a/internal/repos/trace_context_helpers_test.go +++ b/internal/repos/trace_context_helpers_test.go @@ -4,32 +4,45 @@ import ( "bytes" "crypto/ed25519" "encoding/base64" + "encoding/hex" "fmt" "strings" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" ) -// traceInstallA is a trace installation ID: 32 lowercase hex characters, -// not all zero. -const traceInstallA = "0f1e2d3c4b5a69788796a5b4c3d2e1f0" +// Trace installation IDs: 32 lowercase hex characters, not all zero. +const ( + traceInstallA = "0f1e2d3c4b5a69788796a5b4c3d2e1f0" + traceInstallB = "a1b2c3d4e5f60718293a4b5c6d7e8f90" +) -// traceKey is a deterministic Ed25519 public key built with the standard -// library, so fixtures and expected values never come from the code under -// test. +// traceKey is a deterministic Ed25519 pair built with the standard library, +// so fixtures and expected values never come from the code under test. type traceKey struct { - pub ed25519.PublicKey + seed []byte + pub ed25519.PublicKey } func newTraceKey(b byte) traceKey { seed := bytes.Repeat([]byte{b}, ed25519.SeedSize) - return traceKey{pub: ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey)} + return traceKey{seed: seed, pub: ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey)} } -func (k traceKey) pubB64() string { return base64.StdEncoding.EncodeToString(k.pub) } +func (k traceKey) seedB64() string { return base64.StdEncoding.EncodeToString(k.seed) } +func (k traceKey) pubB64() string { return base64.StdEncoding.EncodeToString(k.pub) } +func (k traceKey) id() string { return traceKeyID(k.pub) } + +// traceKeyID is pub's key ID as 16 lowercase hex characters. +func traceKeyID(pub ed25519.PublicKey) string { + id := tracecontext.KeyID(pub) + return hex.EncodeToString(id[:]) +} // traceBlock renders a complete trace_context block. func traceBlock(installationID string, active traceKey, retained ...traceKey) string { @@ -45,10 +58,16 @@ func traceBlock(installationID string, active traceKey, retained ...traceKey) st return b.String() } -// assertNoTraceValues fails when s shows the installation ID or a public key. +// assertNoTraceValues fails when s shows a seed, an installation ID or a +// public key. The seed checks come first and never print s, so a leaked +// seed stops the test before an assertion that prints s. func assertNoTraceValues(t *testing.T, s string, keys ...traceKey) { t.Helper() + for _, k := range keys { + require.False(t, strings.Contains(s, k.seedB64()), "the seed of key %s is shown", k.id()) + } assert.NotContains(t, s, traceInstallA) + assert.NotContains(t, s, traceInstallB) for _, k := range keys { assert.NotContains(t, s, k.pubB64()) } diff --git a/internal/repos/trace_keys.go b/internal/repos/trace_keys.go new file mode 100644 index 0000000000..e7c32d7a82 --- /dev/null +++ b/internal/repos/trace_keys.go @@ -0,0 +1,608 @@ +package repos + +import ( + "bytes" + "context" + "crypto/ed25519" + "errors" + "fmt" + "slices" + "strings" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/preset" + "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" +) + +// TraceKeysConfig configures EnsureTraceSigningKeys. Manifest, +// ManifestPath, RepoFilter and ExcludeRepos mean what they mean in +// ManagedConfigWritebackConfig. +type TraceKeysConfig struct { + Manifest *Manifest + ManifestPath string + // Deferred reports that the caller persists the edited manifest, so + // progress says Persisted rather than Would persist. + Deferred bool + RepoFilter []string + ExcludeRepos []string + // Rotate is --rotate-trace-signing-key: generate a new active key even + // when the installed one is healthy. On an existing install without a + // trace_context block the first rotation provisions the keys. + Rotate bool +} + +// traceKeyReason is why EnsureTraceSigningKeys plans a key. +type traceKeyReason string + +const ( + reasonFreshInstall traceKeyReason = "fresh install" + reasonRecovery traceKeyReason = "recovery" + reasonRotation traceKeyReason = "rotation" +) + +// TraceKeyPlan is one repository's pending trace-key write. Key holds the +// new seed. KeyIDVar and KeyIDVarExists are what the preflight read from +// FULLSEND_TRACE_SIGNING_KEY_ID: convergence writes nothing unless a second +// read returns the same. KeyIDVar is a key ID, never key material. +type TraceKeyPlan struct { + Key tracecontext.SigningKey + // Reason is why the key is planned: a fresh install, a recovery or a + // rotation. + Reason traceKeyReason + KeyIDVar string + KeyIDVarExists bool +} + +// Trace-key preflight refusals. They name the repository and key IDs, never +// key material or the value of FULLSEND_TRACE_SIGNING_KEY_ID. +var ( + ErrTraceManifestStale = errors.New("repos.yaml does not match the repository's trace keys") + ErrTraceManifestReadOnly = errors.New("repos.yaml is read-only") + ErrTraceKeyIDInvalid = errors.New(forge.VarTraceSigningKeyID + " is not a key ID") +) + +// EnsureTraceSigningKeys plans the trace signing keys of the selected +// repositories (ADR 0154) before the manifest is persisted, so convergence +// writes them before its scaffold or config commit +// (ConvergeConfig.TraceKeyPlans). GitLab repositories get no key and are not +// read; progress says so. For each other selected repository it reads the +// committed .fullsend/config.yaml trace_context and +// FULLSEND_TRACE_SIGNING_KEY_ID and, when they decide the outcome, the +// fullsend workflow marker and whether FULLSEND_TRACE_SIGNING_KEY exists. +// Then it: +// - refuses with ErrTraceKeyIDInvalid, before any edit, a variable that is +// not 16 lowercase hex characters; +// - refuses with ErrTraceManifestStale, before any edit, an entry whose +// installation_id differs from the committed one, that lacks a committed +// key, or that has no trace_context while the committed config has one; +// a variable set beside an entry without trace_context, or naming a key +// the entry does not list; and an installation_id another entry uses. +// The committed block of an ended installation is not compared with the +// entry: a keyless entry's block once no fullsend workflow, seed or +// variable remains (a full uninstall, which keeps the committed config +// on GitHub), and another installation's block while no fullsend +// workflow is on the default branch; +// - plans "recovery" when the secret is missing or the variable is absent +// or names a retained key, "rotation" for Rotate, and "fresh install" +// for a keyless entry without a fullsend workflow; a healthy install, +// and an existing install without trace_context, get no plan; +// - refuses with ErrTraceManifestReadOnly, before any edit, a plan that a +// read-only manifest cannot record, except a fresh install without +// Rotate, which goes ahead without keys and says so; +// - otherwise generates a key (and, for an entry without keys, an +// installation ID) from crypto/rand, retains the previous active key, +// records the block in the manifest entry (carving an explicit entry out +// of a glob like EnsureManagedConfigDefaults) and returns a plan keyed +// "owner/repo". +// +// EnsureTraceSigningKeys never writes repos.yaml; the caller persists the +// edited manifest (repos install does so through its compare-before-write +// guard). Deferred reports that the caller persists it, so progress says +// Persisted rather than Would persist. Repositories that fail +// RequireInferenceAuth are skipped. Progress names installation and key IDs, +// and the glob a new entry was copied from, never the seed. +func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients ForgeClientFactory, progress ProgressFunc) (map[string]*TraceKeyPlan, error) { + m := cfg.Manifest + selected, err := selectManifestRepos(ctx, m, clients, cfg.RepoFilter) + if err != nil { + return nil, err + } + readOnly := ManifestReadOnly(m, cfg.ManifestPath) + var repos []*traceRepo + var gitlab []string + var errs []error + for _, rr := range withoutRepos(selected, cfg.ExcludeRepos) { + if rr.Forge == ForgeGitLab { + gitlab = append(gitlab, rr.Owner+"/"+rr.Repo) + continue + } + // Convergence fails a repository without inference + // authentication before its key writes, so it gains no key. + if m.ResolveConfigForEntry(rr.Owner, rr.Repo, rr.Forge, rr.Entry).RequireInferenceAuth() != nil { + continue + } + t, err := readTraceRepo(ctx, m, clients, rr, cfg.Rotate) + if err != nil { + errs = append(errs, err) + continue + } + repos = append(repos, t) + } + if err := errors.Join(errs...); err != nil { + return nil, err + } + + var edited []string + for _, t := range repos { + // A fresh install goes ahead without keys when the manifest cannot + // record them. An explicit rotation still needs the edit. + if readOnly && !cfg.Rotate && t.reason == reasonFreshInstall { + t.reason, t.readOnlySkip = "", true + } + if t.reason != "" { + edited = append(edited, t.name()) + } + } + if readOnly && len(edited) > 0 { + return nil, fmt.Errorf("%w: recording the trace keys of %s needs a repos.yaml edit; repos.yaml and the trace keys were not changed: re-run with a writable local manifest", + ErrTraceManifestReadOnly, strings.Join(edited, ", ")) + } + for _, name := range gitlab { + progress(name, "manifest", "Trace signing keys not provisioned: repos install does not provision them on GitLab yet") + } + for _, t := range repos { + if t.readOnlySkip { + // The notice names the repository in the run it asks for, so + // that run does not rotate the other selected repositories. + progress(t.name(), "manifest", "Trace signing keys not provisioned: repos.yaml is read-only; "+ + "a later repos install "+t.name()+" --rotate-trace-signing-key with a writable manifest provisions them") + } + if t.ended { + // An entry left without an installation renders no trace_context. + fate := "the repos.yaml entry's installation replaces it and stops trusting" + if t.block == nil && t.reason == "" { + fate = "install's commit removes it, so the repository stops trusting" + } + progress(t.name(), "manifest", fmt.Sprintf("The committed %s has the trace_context of the ended installation %s: %s %s", + preset.OverlayPath, tracecontext.FormatInstallationID(t.installed.installation), fate, keyIDs(t.installed.ids()))) + } + } + if len(edited) == 0 { + return nil, nil + } + + plans := make(map[string]*TraceKeyPlan, len(edited)) + for _, t := range repos { + if t.reason == "" { + continue + } + key, err := t.provision() + if err != nil { + return nil, fmt.Errorf("%s: %w", t.name(), err) + } + p := &TraceKeyPlan{Key: key, Reason: t.reason} + if t.recordedKeyID != nil { + p.KeyIDVar, p.KeyIDVarExists = tracecontext.FormatKeyID(*t.recordedKeyID), true + } + plans[t.name()] = p + entry := findExplicitEntry(m, t.name()) + if entry == nil { + carved, glob, err := carveOutForForge(m, t.name(), t.rr.Forge) + if err != nil { + return nil, fmt.Errorf("%s: %w", t.name(), err) + } + if carved == nil { + return nil, fmt.Errorf("no manifest entry or glob covers %q", t.name()) + } + entry, t.carvedFrom = carved, glob + } + entry.Config = entry.Config.WithTraceContext(t.next) + } + if err := validateManifestManaged(m); err != nil { + return nil, fmt.Errorf("validating manifest after recording trace keys: %w", err) + } + + verb := "Would persist" + if cfg.Deferred { + verb = "Persisted" + } + for _, t := range repos { + if p := plans[t.name()]; p != nil { + where := manifestEntryWhere(t.name(), t.carvedFrom) + progress(t.name(), "manifest", fmt.Sprintf("%s config.trace_context in %s: installation ID %s, new active key ID %s (%s)", + verb, where, t.next.InstallationID, tracecontext.FormatKeyID(p.Key.KeyID()), p.Reason)) + } + } + return plans, nil +} + +// traceKeySet is a validated trace_context block's installation ID and +// verification keys, so they are compared as bytes. +type traceKeySet struct { + installation [16]byte + active [8]byte + keys map[[8]byte]ed25519.PublicKey // active and retained, by key ID +} + +// parseTraceKeySet parses tc; a nil block yields a nil set. Errors name the +// field, never the value. +func parseTraceKeySet(tc *config.TraceContextConfig) (*traceKeySet, error) { + if tc == nil { + return nil, nil + } + installation, err := tc.Installation() + if err != nil { + return nil, err + } + active, err := tc.ActiveKey() + if err != nil { + return nil, err + } + keys, err := tc.KeySet() + if err != nil { + return nil, err + } + return &traceKeySet{installation: installation, active: tracecontext.KeyID(active), keys: keys}, nil +} + +// has reports whether s holds exactly pub under id. +func (s *traceKeySet) has(id [8]byte, pub ed25519.PublicKey) bool { + k, ok := s.keys[id] + return ok && bytes.Equal(k, pub) +} + +// ids returns the hex IDs of s's keys, sorted. +func (s *traceKeySet) ids() []string { + ids := make([]string, 0, len(s.keys)) + for id := range s.keys { + ids = append(ids, tracecontext.FormatKeyID(id)) + } + slices.Sort(ids) + return ids +} + +// keyIDs names hex key IDs for a message: "key ID a" or "key IDs a, b". +func keyIDs(ids []string) string { + if len(ids) == 1 { + return "key ID " + ids[0] + } + return "key IDs " + strings.Join(ids, ", ") +} + +// traceRepo is one selected repository's trace-key state, read before any +// manifest edit. +type traceRepo struct { + rr ResolvedRepo + // block is the repos.yaml entry's trace_context (a copy), or nil; + // manifest and installed are the parsed entry and committed blocks. + block *config.TraceContextConfig + manifest *traceKeySet + installed *traceKeySet + // reason is why a key is planned; "" plans none. + reason traceKeyReason + // readOnlySkip reports a fresh install that goes ahead without keys + // because the manifest is read-only. + readOnlySkip bool + // ended reports that installed belongs to an installation that ended, + // as with a full uninstall. The installation in the repos.yaml entry, + // or the one a fresh install adds, replaces it; when the entry gets + // none, install's commit removes it. + ended bool + // next is the entry's new block. + next *config.TraceContextConfig + // carvedFrom names the glob entry that the repository's new explicit + // entry was copied from, or is "" when it already had its own entry. + carvedFrom string + // recordedKeyID is the key ID FULLSEND_TRACE_SIGNING_KEY_ID names, or + // nil when the variable is absent. + recordedKeyID *[8]byte +} + +func (t *traceRepo) name() string { return t.rr.Owner + "/" + t.rr.Repo } + +// readTraceRepo reads rr's committed trace_context and +// FULLSEND_TRACE_SIGNING_KEY_ID and, when they decide the outcome, its +// workflow marker and secret; refuses a malformed variable or an entry +// they contradict; and decides whether a key is planned. +func readTraceRepo(ctx context.Context, m *Manifest, clients ForgeClientFactory, rr ResolvedRepo, rotate bool) (*traceRepo, error) { + t := &traceRepo{rr: rr} + name := t.name() + if w := rr.Entry.Config.Writer(); w != nil { + t.block = w.TraceContext() + } + var err error + if t.manifest, err = parseTraceKeySet(t.block); err != nil { + return nil, fmt.Errorf("%s: repos.yaml entry: %w", name, err) + } + fc, err := clients.ConfigFor(rr.Forge) + if err != nil { + return nil, fmt.Errorf("creating %q client for %s: %w", rr.Forge, name, err) + } + client := fc.Client + committed, err := installedTraceContext(ctx, client, rr.Owner, rr.Repo, rr.Forge) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + if t.installed, err = parseTraceKeySet(committed); err != nil { + return nil, fmt.Errorf("%s: committed %s: %w", name, preset.OverlayPath, err) + } + value, recorded, err := client.GetRepoVariable(ctx, rr.Owner, rr.Repo, forge.VarTraceSigningKeyID) + if err != nil { + return nil, fmt.Errorf("%s: reading %s: %w", name, forge.VarTraceSigningKeyID, err) + } + var keyID [8]byte + if recorded { + // The value is never echoed: only install writes the variable, so + // anything else in it is unexpected input. + if keyID, err = tracecontext.ParseKeyID(value); err != nil { + return nil, fmt.Errorf("%w for %s: its value is not 16 lowercase hex characters; repos.yaml and the trace keys were not changed: "+ + "delete the repository variable %s, then run repos install again", ErrTraceKeyIDInvalid, name, forge.VarTraceSigningKeyID) + } + } + + // The workflow marker tells an existing install from a fresh one, and an + // ended installation's committed block from one the entry contradicts. + hasWorkflow := false + otherInstallation := t.manifest != nil && t.installed != nil && t.installed.installation != t.manifest.installation + if t.manifest == nil || otherInstallation { + if _, _, hasWorkflow, err = readWorkflowMarker(ctx, client, rr.Owner, rr.Repo, fc); err != nil { + return nil, fmt.Errorf("%s: checking workflow file: %w", name, err) + } + } + // The secret decides an entry with keys, and whether a keyless entry's + // committed block belongs to a fully uninstalled repository. + secretExists := false + if t.manifest != nil || (t.installed != nil && !hasWorkflow && !recorded) { + if secretExists, err = client.RepoSecretExists(ctx, rr.Owner, rr.Repo, forge.SecretTraceSigningKey); err != nil { + return nil, fmt.Errorf("%s: checking secret %s: %w", name, forge.SecretTraceSigningKey, err) + } + } + // A full uninstall leaves no workflow, seed or variable, but on GitHub it + // keeps the committed block, so the repository is a fresh install of a + // new installation. That block, like another installation's block while + // no fullsend workflow is on the default branch, stays committed until + // the commit of the install that enrolled the repository again lands, by + // default through a pull request. + t.ended = (t.manifest == nil && t.installed != nil && !hasWorkflow && !recorded && !secretExists) || + (otherInstallation && !hasWorkflow) + + var whys []string + if !t.ended { + whys = t.staleReasons() + } + // Only a variable naming one of the entry's keys can come from a run + // with this repos.yaml; any other was written for another key set. + switch { + case recorded && t.manifest == nil: + whys = append(whys, forge.VarTraceSigningKeyID+" is set and the repos.yaml entry has no trace_context") + case recorded && t.manifest.keys[keyID] == nil: + whys = append(whys, forge.VarTraceSigningKeyID+" names a key the repos.yaml entry does not list") + } + if t.manifest != nil { + if other := traceInstallationUser(m, name, t.manifest.installation); other != "" { + whys = append(whys, fmt.Sprintf("its trace_context.installation_id is also used by the repos.yaml entry %s; every repository needs its own", other)) + } + } + if len(whys) > 0 { + return nil, fmt.Errorf("%w for %s: %s; repos.yaml and the trace keys were not changed: "+ + "run install with the repos.yaml the last install wrote, or restore the entry's trace_context from it", + ErrTraceManifestStale, name, strings.Join(whys, "; ")) + } + if recorded { + t.recordedKeyID = &keyID + } + + if t.manifest == nil { + // An entry without keys provisions them on a fresh install, and on + // an existing install only when the operator rotates. + switch { + case !hasWorkflow: + t.reason = reasonFreshInstall + case rotate: + t.reason = reasonRotation + } + return t, nil + } + // A variable that is absent (an interrupted write, a deleted malformed + // value, a torn-down install) or that names a retained key means the + // secret may not hold the active key. + switch { + case !secretExists, !recorded, keyID != t.manifest.active: + t.reason = reasonRecovery + case rotate: + t.reason = reasonRotation + } + return t, nil +} + +// staleReasons returns why the committed trace_context shows that t's +// repos.yaml entry is not the one the last install wrote, naming key IDs +// only. +func (t *traceRepo) staleReasons() []string { + in := t.installed + if in == nil { + return nil + } + if t.manifest == nil { + return []string{"the committed " + preset.OverlayPath + " has trace_context and the repos.yaml entry has none" + + " (install enrolls the repository again as a new installation only once no fullsend workflow, " + + forge.SecretTraceSigningKey + " or " + forge.VarTraceSigningKeyID + " remains, as after a finished repos uninstall)"} + } + var whys []string + if in.installation != t.manifest.installation { + whys = append(whys, "the committed trace_context.installation_id differs from the repos.yaml entry's") + } + var missing []string + for id, pub := range in.keys { + if !t.manifest.has(id, pub) { + missing = append(missing, tracecontext.FormatKeyID(id)) + } + } + if len(missing) > 0 { + slices.Sort(missing) + whys = append(whys, fmt.Sprintf("the committed %s trusts %s, which the repos.yaml entry does not list "+ + "(if you did not add the key, the committed file may have been edited: revert that change, and do not add the key to repos.yaml)", + preset.OverlayPath, keyIDs(missing))) + } + return whys +} + +// provision generates t's new active key into t.next, keeping the +// installation ID and retaining the previous active key, or starting a +// block with a new installation ID. +func (t *traceRepo) provision() (tracecontext.SigningKey, error) { + key, err := tracecontext.NewSigningKey(nil) + if err != nil { + return tracecontext.SigningKey{}, err + } + t.next = t.block + if t.next == nil { + id, err := tracecontext.NewInstallationID(nil) + if err != nil { + return tracecontext.SigningKey{}, err + } + t.next = &config.TraceContextConfig{ + InstallationID: tracecontext.FormatInstallationID(id), + SigningKey: &config.TraceSigningKeyRef{Secret: config.TraceSigningKeySecret}, + VerificationKeys: &config.TraceVerificationKeys{}, + } + } else { + t.next.VerificationKeys.Retained = append(t.next.VerificationKeys.Retained, t.next.VerificationKeys.Active) + } + t.next.VerificationKeys.Active = tracecontext.FormatVerificationKey(key.Public()) + return key, nil +} + +// installedTraceContext returns the trace_context of the committed +// .fullsend/config.yaml, or nil when the file or the block is absent. +func installedTraceContext(ctx context.Context, client forge.Client, owner, repo, forgeName string) (*config.TraceContextConfig, error) { + data, found, err := readExistingFile(ctx, client, owner, repo, preset.OverlayPath) + if err != nil { + return nil, fmt.Errorf("reading %s: %w", preset.OverlayPath, err) + } + if !found { + return nil, nil + } + if data, err = overlayForEvaluation(data, forgeName); err != nil { + return nil, err + } + r, err := config.ParsePerRepoConfig(data) + if err != nil { + return nil, fmt.Errorf("existing %s cannot be parsed: %w", preset.OverlayPath, err) + } + return r.TraceContext(), nil +} + +// traceInstallationUser returns the name of a manifest entry other than +// name whose trace_context uses installation, or "" when there is none. +// Unselected entries count: an installation ID identifies one install. +func traceInstallationUser(m *Manifest, name string, installation [16]byte) string { + for _, e := range m.AllRepos() { + w := e.Config.Writer() + if w == nil || strings.EqualFold(e.Name, name) { + continue + } + if tc := w.TraceContext(); tc != nil { + if id, err := tc.Installation(); err == nil && id == installation { + return e.Name + } + } + } + return "" +} + +// convergeTraceSigningKey writes the planned key of d's repository from +// cfg.TraceKeyPlans before the scaffold or config commit that delivers the +// config naming it (ADR 0154). It reads FULLSEND_TRACE_SIGNING_KEY_ID again +// and writes nothing unless the variable is still absent, or still present +// with the same value, as the preflight read it; otherwise another install +// or uninstall of the repository ran meanwhile. It then deletes the +// variable, writes FULLSEND_TRACE_SIGNING_KEY and sets the variable to the +// new key ID, each step only after the one before succeeded, so the variable +// never names a key whose seed the secret no longer holds, apart from +// overlapping runs. Nothing locks the read and +// the writes, so a run that writes after the read goes unseen. A +// repository without a plan gets no action. A dry run reports "would set" +// actions only, and errors are redacted with redactSecretValues. Callers +// stop the repository before its scaffold or config commit when an action +// is "error". +func convergeTraceSigningKey(ctx context.Context, d convergeDiscovery, cfg ConvergeConfig, progress ProgressFunc) []ComponentAction { + resolved := d.resolved + repoFullName := resolved.Owner + "/" + resolved.Repo + plan := cfg.TraceKeyPlans[repoFullName] + if plan == nil { + return nil + } + keyID := tracecontext.FormatKeyID(plan.Key.KeyID()) + secretAction := ComponentAction{Component: "secret:" + forge.SecretTraceSigningKey, Action: "update"} + keyIDAction := ComponentAction{Component: "var:" + forge.VarTraceSigningKeyID, Action: "update"} + if cfg.DryRun { + secretAction.Detail = fmt.Sprintf("would set %s (key ID %s)", forge.SecretTraceSigningKey, keyID) + keyIDAction.Detail = fmt.Sprintf("would set %s = %s", forge.VarTraceSigningKeyID, keyID) + progress(repoFullName, "dry-run", "Would set secret "+forge.SecretTraceSigningKey) + progress(repoFullName, "dry-run", "Would set variable "+forge.VarTraceSigningKeyID) + return []ComponentAction{secretAction, keyIDAction} + } + + client := resolved.ForgeConfig.Client + owner, repo := resolved.Owner, resolved.Repo + seed := plan.Key.EncodeSeed() + values := map[string]string{forge.SecretTraceSigningKey: seed} + notSet := func(why string) []ComponentAction { + secretAction.Action = "error" + secretAction.Detail = fmt.Sprintf("%s not set: %s", forge.SecretTraceSigningKey, redactSecretValues(why, values)) + return []ComponentAction{secretAction} + } + value, exists, err := client.GetRepoVariable(ctx, owner, repo, forge.VarTraceSigningKeyID) + if err != nil { + return notSet(fmt.Sprintf("reading %s: %s", forge.VarTraceSigningKeyID, err)) + } + if exists != plan.KeyIDVarExists || value != plan.KeyIDVar { + return notSet(fmt.Sprintf("%s changed after this run read it, as when another install or uninstall of %s runs at the same time; "+ + "once that run has finished, run repos install again (after another install, with the repos.yaml that install wrote)", forge.VarTraceSigningKeyID, repoFullName)) + } + if err := client.DeleteRepoVariable(ctx, owner, repo, forge.VarTraceSigningKeyID); err != nil { + return notSet(fmt.Sprintf("deleting %s: %s", forge.VarTraceSigningKeyID, err)) + } + if err := client.CreateRepoSecret(ctx, owner, repo, forge.SecretTraceSigningKey, seed); err != nil { + // A failed write may still have landed, as after a timeout. With the + // variable deleted, a retry from an older repos.yaml would then + // replace that key without retaining it. + secretAction.Action = "error" + secretAction.Detail = fmt.Sprintf("failed to set %s: %s; %s may now hold a key that only the repos.yaml this run wrote lists: "+ + "keep and commit that repos.yaml, and run repos install again with it", + forge.SecretTraceSigningKey, redactSecretValues(err.Error(), values), forge.SecretTraceSigningKey) + return []ComponentAction{secretAction} + } + secretAction.Detail = fmt.Sprintf("set %s (key ID %s)", forge.SecretTraceSigningKey, keyID) + progress(repoFullName, "sync", "Set secret "+forge.SecretTraceSigningKey) + if err := client.CreateOrUpdateRepoVariable(ctx, owner, repo, forge.VarTraceSigningKeyID, keyID); err != nil { + // With the variable absent, nothing on the forge tells an older + // repos.yaml from this run's, so a retry from an older copy would + // replace this key without retaining it. + keyIDAction.Action = "error" + keyIDAction.Detail = fmt.Sprintf("failed to set %s: %s; %s now holds a key that only the repos.yaml this run wrote lists: "+ + "keep and commit that repos.yaml, and run repos install again with it", + forge.VarTraceSigningKeyID, redactSecretValues(err.Error(), values), forge.SecretTraceSigningKey) + return []ComponentAction{secretAction, keyIDAction} + } + keyIDAction.Detail = fmt.Sprintf("set %s = %s", forge.VarTraceSigningKeyID, keyID) + progress(repoFullName, "sync", "Set variable "+forge.VarTraceSigningKeyID) + return []ComponentAction{secretAction, keyIDAction} +} + +// actionsError joins the details of the "error" actions into one error, +// or returns nil when no action failed. +func actionsError(actions []ComponentAction) error { + var details []string + for _, a := range actions { + if a.Action == "error" { + details = append(details, a.Detail) + } + } + if len(details) == 0 { + return nil + } + return fmt.Errorf("convergence errors: %s", strings.Join(details, "; ")) +} diff --git a/internal/repos/trace_keys_converge_test.go b/internal/repos/trace_keys_converge_test.go new file mode 100644 index 0000000000..32f8bfbc9f --- /dev/null +++ b/internal/repos/trace_keys_converge_test.go @@ -0,0 +1,713 @@ +package repos + +import ( + "bytes" + "context" + "crypto/ed25519" + "encoding/base64" + "errors" + "fmt" + "slices" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/preset" + "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" +) + +// traceFailClient fails one trace key step with an error that reflects +// echo, as a forge that echoes the value it was sent: "reread" (reading +// FULLSEND_TRACE_SIGNING_KEY_ID), "delete" (deleting it), "seed" (writing +// FULLSEND_TRACE_SIGNING_KEY) or "variable" (setting +// FULLSEND_TRACE_SIGNING_KEY_ID); "" fails none. It counts the reads of +// FULLSEND_TRACE_SIGNING_KEY_ID and the scaffold commits. Embedding the +// concrete fake keeps its optional interfaces visible. Tests plan with the +// plain fake and wrap it only for convergence, so no preflight read fails. +type traceFailClient struct { + *forge.FakeClient + step string + echo string + + mu sync.Mutex + rereads int + commits int +} + +func (c *traceFailClient) fail(step string) error { + if c.step != step { + return nil + } + return fmt.Errorf("forge rejected %s", c.echo) +} + +func (c *traceFailClient) GetRepoVariable(ctx context.Context, owner, repo, name string) (string, bool, error) { + if name == forge.VarTraceSigningKeyID { + c.mu.Lock() + c.rereads++ + c.mu.Unlock() + if err := c.fail("reread"); err != nil { + return "", false, err + } + } + return c.FakeClient.GetRepoVariable(ctx, owner, repo, name) +} + +func (c *traceFailClient) DeleteRepoVariable(ctx context.Context, owner, repo, name string) error { + if name == forge.VarTraceSigningKeyID { + if err := c.fail("delete"); err != nil { + return err + } + } + return c.FakeClient.DeleteRepoVariable(ctx, owner, repo, name) +} + +func (c *traceFailClient) CreateRepoSecret(ctx context.Context, owner, repo, name, value string) error { + if name == forge.SecretTraceSigningKey { + if err := c.fail("seed"); err != nil { + return err + } + } + return c.FakeClient.CreateRepoSecret(ctx, owner, repo, name, value) +} + +func (c *traceFailClient) CreateOrUpdateRepoVariable(ctx context.Context, owner, repo, name, value string) error { + if name == forge.VarTraceSigningKeyID { + if err := c.fail("variable"); err != nil { + return err + } + } + return c.FakeClient.CreateOrUpdateRepoVariable(ctx, owner, repo, name, value) +} + +// keyIDReads returns how many times convergence read +// FULLSEND_TRACE_SIGNING_KEY_ID. +func (c *traceFailClient) keyIDReads() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.rereads +} + +// committed returns how many scaffold commits convergence made. +func (c *traceFailClient) committed() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.commits +} + +// commit counts each scaffold commit and returns err without landing it, as +// a pull request that is not merged. +func (c *traceFailClient) commit(err error) ScaffoldCommitFunc { + return func(context.Context, string, string, []forge.TreeFile, bool, bool) error { + c.mu.Lock() + c.commits++ + c.mu.Unlock() + return err + } +} + +// land counts each scaffold commit and lands its files on the default +// branch, so the committed config can be read back. +func (c *traceFailClient) land() ScaffoldCommitFunc { + return func(ctx context.Context, owner, repo string, files []forge.TreeFile, _, _ bool) error { + c.mu.Lock() + c.commits++ + c.mu.Unlock() + _, err := c.CommitFiles(ctx, owner, repo, "install", files) + return err + } +} + +func convergeTrace(t *testing.T, client *traceFailClient, cfg ConvergeConfig, commit ScaffoldCommitFunc, progress *progressLog) *ConvergeBatchResult { + t.Helper() + result, err := Converge(context.Background(), cfg, newTestClientFactory(client), commit, progress.fn) + require.NoError(t, err) + return result +} + +// convergeOK converges and requires every repository to succeed, after +// checking that nothing reported shows seed. It returns the result and +// everything reported. +func convergeOK(t *testing.T, client *traceFailClient, cfg ConvergeConfig, commit ScaffoldCommitFunc, seed string) (*ConvergeBatchResult, []string) { + t.Helper() + progress := &progressLog{} + result := convergeTrace(t, client, cfg, commit, progress) + reported := traceReported(result, progress) + requireNoSeed(t, reported, seed) + require.Zero(t, len(result.Failed()), "convergence failed:\n%s", strings.Join(reported, "\n")) + return result, reported +} + +// traceSecretWrites returns the values written to FULLSEND_TRACE_SIGNING_KEY, +// in order. They are seeds: compare them, never print them. +func traceSecretWrites(fc *forge.FakeClient) []string { + var out []string + for _, s := range fc.CreatedSecrets { + if s.Name == forge.SecretTraceSigningKey { + out = append(out, s.Value) + } + } + return out +} + +// traceVarRecords returns how many records, such as fc.DeletedVariables or +// fc.Variables, name FULLSEND_TRACE_SIGNING_KEY_ID. +func traceVarRecords(records []forge.VariableRecord) int { + n := 0 + for _, v := range records { + if v.Name == forge.VarTraceSigningKeyID { + n++ + } + } + return n +} + +// keyIDVar returns acme/api's FULLSEND_TRACE_SIGNING_KEY_ID. +func keyIDVar(fc *forge.FakeClient) (string, bool) { + v, ok := fc.VariableValues["acme/api/"+forge.VarTraceSigningKeyID] + return v, ok +} + +// traceReported is everything convergence reported: errors, actions and +// progress lines. +func traceReported(result *ConvergeBatchResult, progress *progressLog) []string { + var out []string + for _, r := range result.Results { + if r.Error != nil { + out = append(out, r.Error.Error()) + } + for _, a := range r.Actions { + out = append(out, a.Component+" "+a.Action+" "+a.Detail) + } + } + return append(out, progress.all()...) +} + +// requireNoSeed fails, without printing anything reported, when a report +// shows seed. +func requireNoSeed(t *testing.T, reported []string, seed string) { + t.Helper() + for _, s := range reported { + require.False(t, strings.Contains(s, seed), "nothing reported shows the seed") + } +} + +// traceActions returns the actions of the trace key step, as "component +// action detail". +func traceActions(result *ConvergeBatchResult) []string { + var out []string + for _, r := range result.Results { + for _, a := range r.Actions { + if a.Action == "orphan" { + continue + } + if a.Component == "secret:"+forge.SecretTraceSigningKey || a.Component == "var:"+forge.VarTraceSigningKeyID { + out = append(out, a.Component+" "+a.Action+" "+a.Detail) + } + } + } + return out +} + +// assertTraceConverged checks the forge against tc: the key ID variable +// names the active key and the last seed written expands to it. +func assertTraceConverged(t *testing.T, fc *forge.FakeClient, tc *config.TraceContextConfig) { + t.Helper() + active, err := base64.StdEncoding.DecodeString(tc.VerificationKeys.Active) + require.NoError(t, err) + v, _ := keyIDVar(fc) + assert.Equal(t, traceKeyID(active), v, "the key ID variable names the active key") + writes := traceSecretWrites(fc) + require.True(t, len(writes) > 0, "no seed was written") + seed, err := base64.StdEncoding.DecodeString(writes[len(writes)-1]) + require.NoError(t, err) + require.True(t, len(seed) == ed25519.SeedSize, "the secret holds a 32-byte seed") + assert.True(t, bytes.Equal(active, ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey)), "the secret holds the active key's seed") +} + +// traceEligible returns tc's active and retained keys. +func traceEligible(tc *config.TraceContextConfig) []string { + return append([]string{tc.VerificationKeys.Active}, tc.VerificationKeys.Retained...) +} + +// A fresh install's key is written before Install, deleting the variable +// first. A dry run reports both writes and reads, deletes, writes and +// commits nothing. The real run deletes FULLSEND_TRACE_SIGNING_KEY_ID, writes +// the plan's seed (Install reuses the Vertex secrets, so it writes no other +// secret), sets the variable to the plan's key ID and commits. A second run +// plans nothing and, with the scaffold landed, is already current. A plan +// for another repository writes nothing for this one. +func TestTraceKeys_FreshThenReinstall(t *testing.T) { + fixture := func(t *testing.T) (*forge.FakeClient, ConvergeConfig) { + fc := newFakeClientForBatch("acme/api") + fc.Secrets["acme/api/"+forge.SecretGCPProjectID] = true + fc.Secrets["acme/api/"+forge.SecretGCPWIFProvider] = true + fc.VariableValues["acme/api/"+forge.VarGCPRegion] = "us-central1" + return fc, withoutInferenceInputs(convergeCfgWithDefaults(newConvergeManifest("acme/api"))) + } + + t.Run("plan for this repository", func(t *testing.T) { + fc, cfg := fixture(t) + plans, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}) + require.NoError(t, err) + p := requireTracePlan(t, plans, "acme/api") + seed := p.Key.EncodeSeed() + id := traceKeyID(p.Key.Public()) + tc := manifestTrace(t, cfg.Manifest, "acme/api") + cfg.TraceKeyPlans = plans + + dry := cfg + dry.DryRun = true + client := &traceFailClient{FakeClient: fc} + result, reported := convergeOK(t, client, dry, client.commit(nil), seed) + assert.Equal(t, wouldSetTrace(id), traceActions(result)) + assert.Equal(t, 1, countLines(reported, "acme/api dry-run Would set secret "+forge.SecretTraceSigningKey), strings.Join(reported, "\n")) + assert.Equal(t, 1, countLines(reported, "acme/api dry-run Would set variable "+forge.VarTraceSigningKeyID), strings.Join(reported, "\n")) + assert.Zero(t, client.keyIDReads(), "a dry run does not read the variable again") + assert.Zero(t, client.committed(), "a dry run commits nothing") + assertNoForgeWrites(t, fc) + + client = &traceFailClient{FakeClient: fc} + _, reported = convergeOK(t, client, cfg, client.land(), seed) + assert.Equal(t, 1, traceVarRecords(fc.DeletedVariables), "the variable is deleted before the seed write") + writes := traceSecretWrites(fc) + require.True(t, len(writes) == 1, "one seed write") + assert.True(t, writes[0] == seed, "the secret holds the plan's seed") + v, ok := keyIDVar(fc) + assert.True(t, ok, "the variable is set") + assert.Equal(t, id, v, "the variable names the plan's key") + for _, s := range fc.CreatedSecrets { + assert.False(t, slices.Contains(managedInferenceSecrets(), s.Name), "%s is reused, not written", s.Name) + } + assert.Equal(t, 1, client.committed()) + assert.Equal(t, 1, countLines(reported, "acme/api sync Set secret "+forge.SecretTraceSigningKey), strings.Join(reported, "\n")) + assert.Equal(t, 1, countLines(reported, "acme/api sync Set variable "+forge.VarTraceSigningKeyID), strings.Join(reported, "\n")) + assertTraceConverged(t, fc, tc) + + again, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}) + require.NoError(t, err) + assert.Empty(t, planNames(again), "the install is healthy") + cfg.TraceKeyPlans = again + client = &traceFailClient{FakeClient: fc} + progress := &progressLog{} + result = convergeTrace(t, client, cfg, client.land(), progress) + reported = traceReported(result, progress) + requireNoSeed(t, reported, seed) + require.Equal(t, 1, len(result.Results)) + assert.True(t, result.Results[0].AlreadyCurrent, "the second run is already current:\n%s", strings.Join(reported, "\n")) + assert.Zero(t, client.committed(), "the second run commits nothing") + assert.Equal(t, 1, traceVarRecords(fc.DeletedVariables), "the second run deletes no variable") + assert.Equal(t, 1, len(traceSecretWrites(fc)), "the second run writes no seed") + assert.Equal(t, tc.InstallationID, manifestTrace(t, cfg.Manifest, "acme/api").InstallationID) + }) + + t.Run("plan for another repository only", func(t *testing.T) { + fc, cfg := fixture(t) + other, err := tracecontext.ParseSigningSeed(newTraceKey(9).seedB64()) + require.NoError(t, err) + cfg.TraceKeyPlans = map[string]*TraceKeyPlan{"acme/other": {Key: other, Reason: reasonFreshInstall}} + client := &traceFailClient{FakeClient: fc} + result, _ := convergeOK(t, client, cfg, client.land(), newTraceKey(9).seedB64()) + assert.Empty(t, traceActions(result)) + assert.Zero(t, client.keyIDReads()) + assert.Zero(t, traceVarRecords(fc.DeletedVariables)) + assert.Zero(t, len(traceSecretWrites(fc)), "no seed write") + _, ok := keyIDVar(fc) + assert.False(t, ok, "no variable") + assert.Equal(t, 1, client.committed(), "the install still commits") + }) +} + +// wouldSetTrace is what a dry run reports for a plan with key ID id. +func wouldSetTrace(id string) []string { + return []string{ + "secret:" + forge.SecretTraceSigningKey + " update would set " + forge.SecretTraceSigningKey + " (key ID " + id + ")", + "var:" + forge.VarTraceSigningKeyID + " update would set " + forge.VarTraceSigningKeyID + " = " + id, + } +} + +// traceStepFixture is a repository whose key the preflight plans, with +// the Rotate flag that plans it. +type traceStepFixture struct { + name string + setup func(t *testing.T) (fc *forge.FakeClient, cfg ConvergeConfig, rotate bool) + // reenroll reports a re-enrollment after a full uninstall of + // installation traceInstallA, whose block stays committed until the + // install's commit lands. + reenroll bool +} + +// A failure at any trace key step, or at the commit, fails the repository +// before its commit and leaves the forge as that step leaves it: a failed +// read deletes nothing, a failed delete writes no seed, and after the delete +// FULLSEND_TRACE_SIGNING_KEY_ID stays absent until the new key's seed is +// written and the variable set. Nothing reported shows the seed, which the +// forge's error echoes. After a failed or unmerged commit, which leaves the +// key written, the next preflight plans nothing; while a re-enrollment's +// commit has not landed, it names the ended installation once. One plain +// retry converges, keeps the installation and every trusted key, and +// delivers the entry's block; a third preflight plans nothing and names no +// ended installation. +func TestTraceKeys_WriteStepFailureThenRetry(t *testing.T) { + old := newTraceKey(1) + fixtures := []traceStepFixture{ + {name: "fresh", setup: func(t *testing.T) (*forge.FakeClient, ConvergeConfig, bool) { + fc, cfg := traceFixture(t, false, "acme/api") + return fc, cfg, false + }}, + {name: "rotation", setup: func(t *testing.T) (*forge.FakeClient, ConvergeConfig, bool) { + fc, cfg := traceFixture(t, true, "acme/api") + healthyTrace(t, cfg.Manifest, fc, "acme/api", traceBlock(traceInstallA, old), old) + return fc, cfg, true + }}, + {name: "re-enrollment", reenroll: true, setup: func(t *testing.T) (*forge.FakeClient, ConvergeConfig, bool) { + fc, cfg := githubFullUninstall(t, old) + return fc, cfg, false + }}, + } + // wants is what the error of each failing step names. + wants := map[string]string{ + "reread": forge.SecretTraceSigningKey + " not set: reading " + forge.VarTraceSigningKeyID + ": forge rejected [redacted]", + "delete": forge.SecretTraceSigningKey + " not set: deleting " + forge.VarTraceSigningKeyID + ": forge rejected [redacted]", + "seed": "failed to set " + forge.SecretTraceSigningKey + ": forge rejected [redacted]; " + forge.SecretTraceSigningKey + " may now hold a key that only the repos.yaml this run wrote lists: keep and commit that repos.yaml, and run repos install again with it", + "variable": "failed to set " + forge.VarTraceSigningKeyID + ": forge rejected [redacted]; " + forge.SecretTraceSigningKey + " now holds a key that only the repos.yaml this run wrote lists: keep and commit that repos.yaml, and run repos install again with it", + "commit": "commit failed", + } + for _, fx := range fixtures { + for _, step := range []string{"none", "reread", "delete", "seed", "variable", "commit"} { + t.Run(fx.name+"/"+step, func(t *testing.T) { + fc, cfg, rotate := fx.setup(t) + first, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest, Rotate: rotate}) + require.NoError(t, err) + p := requireTracePlan(t, first, "acme/api") + seed, id := p.Key.EncodeSeed(), traceKeyID(p.Key.Public()) + before := manifestTrace(t, cfg.Manifest, "acme/api") + installation, eligible := before.InstallationID, traceEligible(before) + oldVar, oldVarSet := keyIDVar(fc) + cfg.TraceKeyPlans = first + + if rotate { + // The established path writes nothing in a dry run. + dry := cfg + dry.DryRun = true + client := &traceFailClient{FakeClient: fc} + result, _ := convergeOK(t, client, dry, client.land(), seed) + assert.Equal(t, wouldSetTrace(id), traceActions(result)) + assert.Zero(t, client.keyIDReads()) + assert.Zero(t, traceVarRecords(fc.DeletedVariables)) + assert.Zero(t, len(traceSecretWrites(fc)), "no seed write") + assert.Zero(t, client.committed()) + v, _ := keyIDVar(fc) + assert.Equal(t, old.id(), v) + } + + var commitErr error + if step == "commit" { + commitErr = errors.New("commit failed") + } + client := &traceFailClient{FakeClient: fc, step: step, echo: seed} + progress := &progressLog{} + result := convergeTrace(t, client, cfg, client.commit(commitErr), progress) + reported := traceReported(result, progress) + requireNoSeed(t, reported, seed) + v, set := keyIDVar(fc) + switch step { + case "reread", "delete": + if step == "reread" { + assert.Zero(t, traceVarRecords(fc.DeletedVariables), "nothing is deleted") + } + assert.Zero(t, len(traceSecretWrites(fc)), "no seed write") + assert.Equal(t, oldVarSet, set, "the variable is untouched") + assert.Equal(t, oldVar, v, "the variable is untouched") + case "seed": + assert.Zero(t, len(traceSecretWrites(fc)), "no seed write") + assert.False(t, set, "the variable stays absent") + case "variable": + assert.Equal(t, 1, len(traceSecretWrites(fc)), "one seed write") + assert.False(t, set, "the variable stays absent") + default: + assert.True(t, set, "the variable is set") + assert.Equal(t, id, v, "the variable names the new key") + } + if step == "none" { + require.Zero(t, len(result.Failed()), "install:\n%s", strings.Join(reported, "\n")) + } else { + failed := result.Failed() + require.Equal(t, 1, len(failed), "one failed repository:\n%s", strings.Join(reported, "\n")) + assert.Contains(t, failed[0].Error.Error(), wants[step]) + } + if step != "none" && step != "commit" { + assert.Zero(t, client.committed(), "the repository stops before its commit") + } + + progress = &progressLog{} + second, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + lines := progress.all() + requireNoSeed(t, lines, seed) + if step == "none" || step == "commit" { + assert.Empty(t, planNames(second), "the written key is healthy") + } + wantEnded := 0 + if fx.reenroll { + // The install's commit has not landed, so the retry + // still sees the ended installation's block. + wantEnded = 1 + } + assert.Equal(t, wantEnded, endedLines(lines, old), "ended installation lines:\n%s", strings.Join(lines, "\n")) + cfg.TraceKeyPlans = second + client = &traceFailClient{FakeClient: fc} + convergeOK(t, client, cfg, client.land(), seed) + after := manifestTrace(t, cfg.Manifest, "acme/api") + assert.Equal(t, installation, after.InstallationID, "the installation is kept") + assertTraceConverged(t, fc, after) + assert.Subset(t, traceEligible(after), eligible, "no key leaves the eligible set") + committed, err := installedTraceContext(context.Background(), fc, "acme", "api", ForgeGitHub) + require.NoError(t, err) + assert.Equal(t, after, committed, "the commit delivers the entry's block") + + progress = &progressLog{} + third, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + assert.Empty(t, planNames(third), "the install is healthy after one retry") + assert.Zero(t, countLines(progress.all(), "ended installation"), "the landed commit leaves no ended installation") + }) + } + } +} + +// Convergence reads FULLSEND_TRACE_SIGNING_KEY_ID again before its writes +// and writes nothing unless the variable is still absent, or still present +// with the same value, as the preflight read it: another install or +// uninstall that ran meanwhile fails the repository before any delete, +// write or commit, and the variable is left as that run left it. +func TestConverge_TraceKeyRereadComparesPresenceAndValue(t *testing.T) { + old, z := newTraceKey(1), newTraceKey(6) + set := func(value string) func(*forge.FakeClient) { + return func(fc *forge.FakeClient) { setKeyIDVar(fc, "acme/api", value) } + } + cases := []struct { + name string + // installed plans a rotation of a healthy install whose variable + // names old; otherwise a fresh install plans with it absent. + installed bool + change func(fc *forge.FakeClient) + // want is the variable after the run; "" with wantSet false is + // absent. + want string + wantSet bool + }{ + {name: "absent, then another key ID", change: set(z.id()), want: z.id(), wantSet: true}, + {name: "old key ID, then another", installed: true, change: set(z.id()), want: z.id(), wantSet: true}, + {name: "old key ID, then absent", installed: true, change: func(fc *forge.FakeClient) { + delete(fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID) + delete(fc.VariablesExist, "acme/api/"+forge.VarTraceSigningKeyID) + }}, + {name: "absent, then present but empty", change: set(""), want: "", wantSet: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fc, cfg := traceFixture(t, tc.installed, "acme/api") + if tc.installed { + healthyTrace(t, cfg.Manifest, fc, "acme/api", traceBlock(traceInstallA, old), old) + } + plans, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest, Rotate: tc.installed}) + require.NoError(t, err) + seed := requireTracePlan(t, plans, "acme/api").Key.EncodeSeed() + cfg.TraceKeyPlans = plans + tc.change(fc) + + client := &traceFailClient{FakeClient: fc} + progress := &progressLog{} + result := convergeTrace(t, client, cfg, client.commit(nil), progress) + reported := traceReported(result, progress) + requireNoSeed(t, reported, seed) + failed := result.Failed() + require.Equal(t, 1, len(failed), "one failed repository:\n%s", strings.Join(reported, "\n")) + assert.Contains(t, failed[0].Error.Error(), forge.SecretTraceSigningKey+" not set: "+forge.VarTraceSigningKeyID+ + " changed after this run read it, as when another install or uninstall of acme/api runs at the same time; "+ + "once that run has finished, run repos install again (after another install, with the repos.yaml that install wrote)") + assert.Zero(t, traceVarRecords(fc.DeletedVariables), "nothing is deleted") + assert.Zero(t, len(traceSecretWrites(fc)), "no seed write") + assert.Zero(t, traceVarRecords(fc.Variables), "no variable write") + assert.Zero(t, client.committed(), "nothing is committed") + v, ok := keyIDVar(fc) + assert.Equal(t, tc.wantSet, ok, "the variable is left as the other run left it") + assert.Equal(t, tc.want, v, "the variable is left as the other run left it") + }) + } +} + +// The real uninstall keeps the repos.yaml entry, as repos uninstall +// --uninstall-only does, and on GitHub the committed .fullsend/config.yaml; +// it deletes the seed. The next install keeps the installation, retains +// the old active key and writes a new key before its commit. +func TestTraceKeys_UninstallOnlyThenInstall(t *testing.T) { + old := newTraceKey(1) + fc, cfg := traceFixture(t, true, "acme/api") + healthyTrace(t, cfg.Manifest, fc, "acme/api", traceBlock(traceInstallA, old), old) + results, err := Uninstall(context.Background(), UninstallConfig{ + Manifest: cfg.Manifest, Repos: []string{"acme/api"}, Direct: true, MaxConcurrency: 1, + }, newTestClientFactory(fc), uninstallCommitFn(fc), nil) + require.NoError(t, err) + require.Len(t, results, 1) + require.True(t, results[0].Success, "uninstall: %v", results[0].Error) + assert.False(t, fc.Secrets["acme/api/"+forge.SecretTraceSigningKey], "uninstall deletes the seed") + + progress := &progressLog{} + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + p := requireTracePlan(t, plans, "acme/api") + assert.Equal(t, reasonRecovery, p.Reason) + // The committed block is the entry's own installation, so it has not + // ended although no fullsend workflow remains. + assert.Zero(t, countLines(progress.all(), "ended installation"), "the installation has not ended") + tc := manifestTrace(t, cfg.Manifest, "acme/api") + assert.Equal(t, traceInstallA, tc.InstallationID, "the installation ID is kept") + assert.Equal(t, []string{old.pubB64()}, tc.VerificationKeys.Retained, "the old active key is retained") + assertPlanKeyIsActive(t, p, tc) + + // Uninstall deleted the inference secrets too, so the reinstall supplies + // them again. + cfg = convergeCfgWithDefaults(cfg.Manifest) + cfg.TraceKeyPlans = plans + client := &traceFailClient{FakeClient: fc} + convergeOK(t, client, cfg, client.land(), p.Key.EncodeSeed()) + assert.Equal(t, 1, client.committed()) + assertTraceConverged(t, fc, tc) +} + +// githubFullUninstall returns acme/api as a finished full uninstall leaves +// it on GitHub after installation traceInstallA with active key old: no +// fullsend workflow, FULLSEND_TRACE_SIGNING_KEY or +// FULLSEND_TRACE_SIGNING_KEY_ID, the committed .fullsend/config.yaml with its +// trace_context still in place, and the repository declared again in +// repos.yaml without trace_context. The config supplies the inference +// secrets. +func githubFullUninstall(t *testing.T, old traceKey) (*forge.FakeClient, ConvergeConfig) { + t.Helper() + fc, cfg := traceFixture(t, false, "acme/api") + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, old)) + return fc, cfg +} + +// endedLines counts the progress lines that name the ended installation +// traceInstallA as one the entry's installation replaces, and old's key ID +// as one the repository stops trusting. +func endedLines(lines []string, old traceKey) int { + return countLines(lines, traceInstallA+": the repos.yaml entry's installation replaces it and stops trusting key ID "+old.id()) +} + +// After a full uninstall, which on GitHub leaves the committed +// .fullsend/config.yaml in place, the repository declared again without +// trace_context is a fresh install of a new installation: the preflight +// plans a new installation ID and key pair and names, once, the ended +// installation and the key IDs it stops trusting, sorted (the re-enrollment +// rows of TestTraceKeys_WriteStepFailureThenRetry converge it). While the +// workflow, the seed or the key ID variable remains, the uninstall is +// unfinished and the entry is refused. +func TestTraceKeys_GitHubReenrollAfterFullUninstall(t *testing.T) { + old, k4, k7 := newTraceKey(1), newTraceKey(4), newTraceKey(7) + cases := []struct { + name string + // leftover puts back what an unfinished uninstall leaves; nil is a + // finished one. + leftover func(fc *forge.FakeClient) + // ended, when set, replaces the ended block's keys, active first. + // stops is how the notice lists the keys. + ended []traceKey + stops string + }{ + {name: "full uninstall", stops: "key ID " + old.id()}, + // The keys go in descending key ID order, so a notice that lists + // them unsorted never matches, whatever the map order. + {name: "full uninstall with retained keys", ended: []traceKey{k7, k4, old}, + stops: "key IDs " + old.id() + ", " + k4.id() + ", " + k7.id()}, + {name: "workflow left", leftover: func(fc *forge.FakeClient) { + fc.FileContents["acme/api/.github/workflows/fullsend.yaml"] = []byte("name: fullsend") + }}, + {name: "seed left", leftover: func(fc *forge.FakeClient) { setTraceSecret(fc, "acme/api") }}, + {name: "variable left", leftover: func(fc *forge.FakeClient) { setKeyIDVar(fc, "acme/api", old.id()) }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fc, cfg := githubFullUninstall(t, old) + if tc.ended != nil { + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, tc.ended[0], tc.ended[1:]...)) + } + if tc.leftover != nil { + tc.leftover(fc) + err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, nil, old) + require.ErrorIs(t, err, ErrTraceManifestStale) + msg := err.Error() + assert.Contains(t, msg, "has trace_context and the repos.yaml entry has none (install enrolls the repository again "+ + "as a new installation only once no fullsend workflow, "+forge.SecretTraceSigningKey+" or "+forge.VarTraceSigningKeyID+" remains") + assert.True(t, strings.HasSuffix(msg, refusalRemedy), msg) + assert.NotContains(t, msg, old.id()) + return + } + + progress := &progressLog{} + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + p := requireTracePlan(t, plans, "acme/api") + lines := progress.all() + requireNoSeed(t, lines, p.Key.EncodeSeed()) + assert.Equal(t, reasonFreshInstall, p.Reason) + got := manifestTrace(t, cfg.Manifest, "acme/api") + assertTraceBlockComplete(t, got) + assert.NotEqual(t, traceInstallA, got.InstallationID, "a new installation starts") + assert.Empty(t, got.VerificationKeys.Retained, "the ended installation's key is not carried over") + assertPlanKeyIsActive(t, p, got) + assert.Equal(t, 1, countLines(lines, "acme/api manifest The committed "+preset.OverlayPath+" has the trace_context of the ended installation "+ + traceInstallA+": the repos.yaml entry's installation replaces it and stops trusting "+tc.stops), + "progress names the ended installation once:\n%s", strings.Join(lines, "\n")) + }) + } +} + +// A fully uninstalled repository enrolled again from a manifest install +// cannot write is a fresh install like any other. The preflight plans +// nothing, edits nothing and prints two lines: the read-only notice, and +// that install's commit removes the ended installation's block, since the +// entry records no installation to replace it. Install's commit leaves a +// .fullsend/config.yaml without trace_context. +func TestTraceKeys_GitHubReenrollFromReadOnlyManifest(t *testing.T) { + const url = "https://example.com/repos.yaml" + old := newTraceKey(1) + fc, cfg := githubFullUninstall(t, old) + before := manifestSnapshot(t, cfg.Manifest) + + progress := &progressLog{} + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, ManifestPath: url}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + assert.Empty(t, planNames(plans)) + assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest), "the entry is not edited") + assertNoForgeWrites(t, fc) + lines := progress.all() + out := strings.Join(lines, "\n") + assert.Len(t, lines, 2, "the notice and the ended installation:\n%s", out) + assert.Equal(t, 1, countLines(lines, "acme/api manifest Trace signing keys not provisioned: repos.yaml is read-only"), out) + assert.Equal(t, 1, countLines(lines, "acme/api manifest The committed "+preset.OverlayPath+" has the trace_context of the ended installation "+ + traceInstallA+": install's commit removes it, so the repository stops trusting key ID "+old.id()), out) + + client := &traceFailClient{FakeClient: fc} + progress = &progressLog{} + result := convergeTrace(t, client, cfg, client.land(), progress) + reported := traceReported(result, progress) + require.Zero(t, len(result.Failed()), "install:\n%s", strings.Join(reported, "\n")) + assert.Equal(t, 1, client.committed()) + assert.Empty(t, traceActions(result), "install writes no trace value") + committed, err := installedTraceContext(context.Background(), fc, "acme", "api", ForgeGitHub) + require.NoError(t, err) + assert.Nil(t, committed, "install's commit removes the ended block") +} diff --git a/internal/repos/trace_keys_test.go b/internal/repos/trace_keys_test.go new file mode 100644 index 0000000000..05c53fa650 --- /dev/null +++ b/internal/repos/trace_keys_test.go @@ -0,0 +1,827 @@ +package repos + +import ( + "bytes" + "context" + "crypto/ed25519" + "encoding/base64" + "errors" + "fmt" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/preset" +) + +// Seeds never reach an assertion that prints its arguments: tests compare +// them with assert.True or count them, and pass plans, keys and seed +// slices to no assertion that renders them. + +// traceFixture returns GitHub repositories, fresh or fully installed, with +// the convergence config that installs them. +func traceFixture(t *testing.T, installed bool, repos ...string) (*forge.FakeClient, ConvergeConfig) { + t.Helper() + fc := newFakeClientForBatch(repos...) + cfg := convergeCfgWithDefaults(newConvergeManifest(repos...)) + if !installed { + return fc, cfg + } + for _, r := range repos { + markTraceInstalled(t, fc, r) + } + return fc, withoutInferenceInputs(cfg) +} + +// markTraceInstalled makes name a current GitHub install: its workflow, the +// scaffold files, the variables and the inference secrets. +func markTraceInstalled(t *testing.T, fc *forge.FakeClient, name string) { + t.Helper() + owner, repo, _ := strings.Cut(name, "/") + markFullyInstalled(fc, owner, repo) + populateScaffoldContent(t, fc, owner, repo, "v1.0.0", "https://mint.example.com") +} + +func setManifestTrace(t *testing.T, m *Manifest, name, block string) { + t.Helper() + entry := findExplicitEntry(m, name) + require.NotNil(t, entry, "no manifest entry for %s", name) + entry.Config = mustManagedConfig(t, block) +} + +func setInstalledTrace(fc *forge.FakeClient, name, block string) { + fc.FileContents[name+"/"+preset.OverlayPath] = []byte(managedConfigMarker + block) +} + +func setTraceSecret(fc *forge.FakeClient, name string) { + fc.Secrets[name+"/"+forge.SecretTraceSigningKey] = true +} + +// setKeyIDVar sets name's FULLSEND_TRACE_SIGNING_KEY_ID to value. +func setKeyIDVar(fc *forge.FakeClient, name, value string) { + fc.VariableValues[name+"/"+forge.VarTraceSigningKeyID] = value + fc.VariablesExist[name+"/"+forge.VarTraceSigningKeyID] = true +} + +// healthyTrace makes name a healthy install of block: the manifest entry +// and the committed config carry it, the secret exists and the key ID +// variable names active. +func healthyTrace(t *testing.T, m *Manifest, fc *forge.FakeClient, name, block string, active traceKey) { + t.Helper() + setManifestTrace(t, m, name, block) + setInstalledTrace(fc, name, block) + setTraceSecret(fc, name) + setKeyIDVar(fc, name, active.id()) +} + +func ensureTrace(t *testing.T, fc forge.Client, cfg TraceKeysConfig) (map[string]*TraceKeyPlan, error) { + t.Helper() + return EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), noopProgress) +} + +// manifestTrace returns the trace_context of name's explicit manifest entry. +func manifestTrace(t *testing.T, m *Manifest, name string) *config.TraceContextConfig { + t.Helper() + entry := findExplicitEntry(m, name) + require.NotNil(t, entry, "%s has no explicit manifest entry", name) + require.True(t, entry.Config.IsSet(), "%s has no manifest config", name) + tc := entry.Config.Writer().TraceContext() + require.NotNil(t, tc, "%s has no trace_context in the manifest", name) + require.NotNil(t, tc.VerificationKeys, "%s has no verification keys", name) + return tc +} + +func manifestSnapshot(t *testing.T, m *Manifest) string { + t.Helper() + out, err := m.Marshal() + require.NoError(t, err) + return string(out) +} + +// requireTracePlan returns name's plan and checks that it holds a key. +func requireTracePlan(t *testing.T, plans map[string]*TraceKeyPlan, name string) *TraceKeyPlan { + t.Helper() + p := plans[name] + require.True(t, p != nil, "no trace key plan for %s (plans for %v)", name, planNames(plans)) + require.False(t, p.Key.IsZero(), "the plan for %s holds no key", name) + return p +} + +// planNames returns the repositories plans holds a plan for, sorted, so an +// assertion can show them without showing a key. +func planNames(plans map[string]*TraceKeyPlan) []string { + return slices.Sorted(maps.Keys(plans)) +} + +// assertPlanKeyIsActive checks that the plan key's public key is tc's +// active key and that the plan's seed expands to it. +func assertPlanKeyIsActive(t *testing.T, p *TraceKeyPlan, tc *config.TraceContextConfig) { + t.Helper() + pub := p.Key.Public() + assert.Equal(t, base64.StdEncoding.EncodeToString(pub), tc.VerificationKeys.Active) + seed, err := base64.StdEncoding.DecodeString(p.Key.EncodeSeed()) + require.NoError(t, err) + require.True(t, len(seed) == ed25519.SeedSize, "the plan holds a 32-byte seed") + assert.True(t, bytes.Equal(pub, ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey)), "the plan's seed expands to its public key") +} + +// assertTraceBlockComplete checks the generated parts of a block. +func assertTraceBlockComplete(t *testing.T, tc *config.TraceContextConfig) { + t.Helper() + assert.Regexp(t, `^[0-9a-f]{32}$`, tc.InstallationID) + assert.NotEqual(t, strings.Repeat("0", 32), tc.InstallationID) + require.NotNil(t, tc.SigningKey) + assert.Equal(t, forge.SecretTraceSigningKey, tc.SigningKey.Secret) + assert.NoError(t, config.ValidateTraceContext(tc)) +} + +// assertExplicitRoles checks that entry still declares exactly roles. +func assertExplicitRoles(t *testing.T, entry *RepoEntry, roles ...string) { + t.Helper() + require.NotNil(t, entry) + require.True(t, entry.Config.IsSet(), "%s has no config", entry.Name) + got, ok := entry.Config.ExplicitRoles() + assert.True(t, ok, "%s keeps its roles", entry.Name) + assert.Equal(t, roles, got, "%s keeps its roles", entry.Name) +} + +// progressLog collects progress lines as "repo phase message"; convergence +// reports concurrently. +type progressLog struct { + mu sync.Mutex + lines []string +} + +func (p *progressLog) fn(repo, phase, msg string) { + p.mu.Lock() + defer p.mu.Unlock() + p.lines = append(p.lines, repo+" "+phase+" "+msg) +} + +func (p *progressLog) all() []string { + p.mu.Lock() + defer p.mu.Unlock() + return slices.Clone(p.lines) +} + +// refuseTrace runs the preflight, which must refuse, and checks that the +// error shows no non-empty value of hidden and no value of keys, before any +// assertion that prints it, and that nothing was planned, edited, written +// or reported. It returns the error for the caller's own checks. +func refuseTrace(t *testing.T, fc *forge.FakeClient, cfg TraceKeysConfig, hidden []string, keys ...traceKey) error { + t.Helper() + before := manifestSnapshot(t, cfg.Manifest) + progress := &progressLog{} + plans, err := EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), progress.fn) + require.Error(t, err) + for _, v := range hidden { + require.False(t, v != "" && strings.Contains(err.Error(), v), "the error never shows a hidden value") + } + assertNoTraceValues(t, err.Error(), keys...) + assert.Empty(t, planNames(plans)) + assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest), "no entry is edited") + assertNoForgeWrites(t, fc) + assert.Empty(t, progress.all(), "a refusal reports nothing") + return err +} + +// countLines returns how many lines contain every one of parts. +func countLines(lines []string, parts ...string) int { + n := 0 + for _, l := range lines { + if !slices.ContainsFunc(parts, func(p string) bool { return !strings.Contains(l, p) }) { + n++ + } + } + return n +} + +// Two fresh repositories each get a new installation and key pair, recorded +// in their entries, which keep their other config; a healthy install beside +// them gets no plan. The forge is not written, and progress names the IDs, +// never the seed. +func TestEnsureTraceSigningKeys_FreshInstall(t *testing.T) { + for _, deferred := range []bool{false, true} { + t.Run(fmt.Sprintf("deferred=%t", deferred), func(t *testing.T) { + fc, cfg := traceFixture(t, false, "acme/api", "acme/web", "acme/ok") + markTraceInstalled(t, fc, "acme/ok") + healthyTrace(t, cfg.Manifest, fc, "acme/ok", traceBlock(traceInstallA, newTraceKey(1)), newTraceKey(1)) + // Config the entry already holds, such as what + // EnsureManagedConfigDefaults recorded, survives the edit. + findExplicitEntry(cfg.Manifest, "acme/api").Config = mustManagedConfig(t, "roles: [triage]\n") + progress := &progressLog{} + + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, Deferred: deferred}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + assert.Equal(t, []string{"acme/api", "acme/web"}, planNames(plans)) + assertNoForgeWrites(t, fc) + + verb := "Would persist" + if deferred { + verb = "Persisted" + } + lines := progress.all() + snapshot := manifestSnapshot(t, cfg.Manifest) + installations := map[string]bool{} + for _, name := range []string{"acme/api", "acme/web"} { + p := requireTracePlan(t, plans, name) + for _, s := range append(slices.Clone(lines), snapshot) { + require.False(t, strings.Contains(s, p.Key.EncodeSeed()), "the seed never leaves the plan") + } + assert.Equal(t, reasonFreshInstall, p.Reason) + assert.False(t, p.KeyIDVarExists, "no key ID variable was read") + assert.Equal(t, "", p.KeyIDVar) + + tc := manifestTrace(t, cfg.Manifest, name) + assertTraceBlockComplete(t, tc) + assertPlanKeyIsActive(t, p, tc) + assert.Empty(t, tc.VerificationKeys.Retained) + installations[tc.InstallationID] = true + assert.Equal(t, 1, countLines(lines, name+" manifest "+verb+" config.trace_context in the manifest entry: installation ID "+tc.InstallationID, + "new active key ID "+traceKeyID(p.Key.Public())+" (fresh install)"), "progress names the IDs:\n%s", strings.Join(lines, "\n")) + } + assert.Len(t, lines, 2, "one line per repository:\n%s", strings.Join(lines, "\n")) + assert.Len(t, installations, 2, "each repository gets its own installation ID") + assert.False(t, plans["acme/api"].Key.EncodeSeed() == plans["acme/web"].Key.EncodeSeed(), "each repository gets its own key") + assertExplicitRoles(t, findExplicitEntry(cfg.Manifest, "acme/api"), "triage") + }) + } +} + +// A repository that only a glob covers gets its own GitHub entry, copied +// from the first glob entry that covers it, and progress names that entry +// and that glob, since later edits to the glob no longer reach it; the globs +// and the repositories the run does not select are unchanged. +func TestEnsureTraceSigningKeys_GlobCoveredGetsExplicitEntry(t *testing.T) { + glob := func(name, ref, role string) RepoEntry { + return RepoEntry{Name: name, FullsendRef: ref, Config: mustManagedConfig(t, "roles: ["+role+"]\n")} + } + cases := []struct { + name string + globs []RepoEntry + // copied is the glob entry acme/api's entry is copied from. + copied string + }{ + {name: "one glob", globs: []RepoEntry{glob("acme/*", "v1.2.3", "triage")}, copied: "acme/*"}, + // acme/w* does not cover acme/api, and of the two that do, the + // first is copied. + {name: "first covering glob", globs: []RepoEntry{ + glob("acme/w*", "v0.0.1", "coder"), glob("acme/a*", "v1.2.3", "triage"), glob("acme/*", "v9.9.9", "coder"), + }, copied: "acme/a*"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := &Manifest{Version: 1, Defaults: testInferenceDefaults(), GitHub: &PlatformConfig{ + MintURL: "https://mint.example.com", Repos: slices.Clone(tc.globs), + }} + fc := newFakeClientForBatch("acme/api", "acme/web") + progress := &progressLog{} + + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, RepoFilter: []string{"acme/api"}}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + assert.Equal(t, []string{"acme/api"}, planNames(plans)) + p := requireTracePlan(t, plans, "acme/api") + lines := progress.all() + requireNoSeed(t, lines, p.Key.EncodeSeed()) + assert.Equal(t, []string{"acme/api manifest Would persist config.trace_context in the new manifest entry acme/api, " + + "copied from the glob entry " + tc.copied + ": installation ID " + manifestTrace(t, m, "acme/api").InstallationID + + ", new active key ID " + traceKeyID(p.Key.Public()) + " (fresh install)"}, lines) + + assert.Len(t, m.GitHub.Repos, len(tc.globs)+1, "one entry is carved out") + assert.Nil(t, findExplicitEntry(m, "acme/web"), "a sibling gains no entry") + for _, g := range tc.globs { + assert.Nil(t, findExplicitEntry(m, g.Name).Config.Writer().TraceContext(), "the glob entry %s carries no trace_context", g.Name) + } + assertExplicitRoles(t, findExplicitEntry(m, tc.copied), "triage") + + carved := findExplicitEntry(m, "acme/api") + require.NotNil(t, carved, "acme/api gets its own entry") + assert.Equal(t, "v1.2.3", carved.FullsendRef, "the carved entry keeps the settings of the glob it names") + assertExplicitRoles(t, carved, "triage") + assertPlanKeyIsActive(t, p, manifestTrace(t, m, "acme/api")) + }) + } +} + +// Repositories install skips get no key and no manifest edit: those it +// skips for adoption (ExcludeRepos, matched case-insensitively) and those +// without an effective inference.auth, whose convergence fails before any +// key write. +func TestEnsureTraceSigningKeys_SkippedReposGetNoKey(t *testing.T) { + cases := []struct { + name string + exclude []string + // noAuth leaves acme/web without inference.auth. + noAuth bool + }{ + {name: "excluded", exclude: []string{"ACME/web"}}, + {name: "no inference.auth", noAuth: true}, + } + for _, tc := range cases { + for _, glob := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/glob=%t", tc.name, glob), func(t *testing.T) { + web := RepoEntry{Name: "acme/web"} + if glob { + web.Name = "acme/w*" + } + m := newConvergeManifest("acme/api") + m.GitHub.Repos = append(m.GitHub.Repos, web) + if tc.noAuth { + m.Defaults.Inference = InferenceSettings{} + m.GitHub.Repos[0].Inference = InferenceSettings{Auth: InferenceAuthVertexWIF} + } + fc := newFakeClientForBatch("acme/api", "acme/web") + + plans, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: m, ExcludeRepos: tc.exclude}) + require.NoError(t, err) + assert.Equal(t, []string{"acme/api"}, planNames(plans)) + assert.Len(t, m.GitHub.Repos, 2, "no entry is carved out") + skipped := findExplicitEntry(m, web.Name) + require.NotNil(t, skipped) + assert.False(t, skipped.Config.IsSet(), "the skipped repository's entry gains no config") + }) + } + } +} + +// GitLab repositories get no key yet, with or without Rotate and with or +// without inference authentication: the preflight reads nothing for them, +// edits nothing, writes nothing and prints one line per repository. +func TestEnsureTraceSigningKeys_GitLabGetsNoKeyYet(t *testing.T) { + for _, auth := range []bool{true, false} { + for _, rotate := range []bool{false, true} { + t.Run(fmt.Sprintf("auth=%t/rotate=%t", auth, rotate), func(t *testing.T) { + fc := forge.NewFakeClient() + reads := newReadCountingClient(fc) + m := testGitLabManifest("acme/api") + if auth { + m.GitLab.Inference = InferenceSettings{Auth: InferenceAuthOpenAIAPIKey} + } + before := manifestSnapshot(t, m) + progress := &progressLog{} + + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, Rotate: rotate}, + newTestClientFactory(reads), progress.fn) + require.NoError(t, err) + assert.Empty(t, planNames(plans)) + assert.Zero(t, reads.total(), "nothing is read for a GitLab repository") + assert.Equal(t, before, manifestSnapshot(t, m)) + assertNoForgeWrites(t, fc) + lines := progress.all() + assert.Len(t, lines, 1, "one line:\n%s", strings.Join(lines, "\n")) + assert.Equal(t, 1, countLines(lines, "acme/api", "not provisioned", "GitLab"), "the line says GitLab keys are not provisioned:\n%s", strings.Join(lines, "\n")) + }) + } + } +} + +// A healthy install, whose secret exists and whose key ID variable names +// the active key, plans nothing and prints nothing, also from a read-only +// manifest. +func TestEnsureTraceSigningKeys_HealthyPlansNothing(t *testing.T) { + a, r := newTraceKey(1), newTraceKey(2) + for name, path := range map[string]string{"local": "", "https": "https://example.com/repos.yaml"} { + t.Run(name, func(t *testing.T) { + fc, cfg := traceFixture(t, true, "acme/api") + healthyTrace(t, cfg.Manifest, fc, "acme/api", traceBlock(traceInstallA, a, r), a) + before := manifestSnapshot(t, cfg.Manifest) + progress := &progressLog{} + + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, ManifestPath: path}, + newTestClientFactory(fc), progress.fn) + require.NoError(t, err) + assert.Empty(t, planNames(plans)) + assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest)) + assertNoForgeWrites(t, fc) + assert.Empty(t, progress.all()) + }) + } +} + +// Every unhealthy state gets a new active key as "recovery", which wins +// over Rotate, and a healthy install gets one as "rotation". The +// installation ID is kept, the previous active key is retained after the +// keys retained before, and the plan carries FULLSEND_TRACE_SIGNING_KEY_ID +// as the preflight read it. +func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { + a, r := newTraceKey(1), newTraceKey(2) + keyed := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a, r)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a, r)) + } + cases := []struct { + name string + // installed puts a fullsend workflow on the default branch. + installed bool + rotate bool + reason traceKeyReason + // keyIDVar is the variable's value in the fixture; "" is absent. + keyIDVar string + setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) + }{ + {name: "variable absent", installed: true, reason: reasonRecovery, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + keyed(t, m, fc) + setTraceSecret(fc, "acme/api") + }}, + {name: "variable and secret absent", installed: true, reason: reasonRecovery, setup: keyed}, + {name: "secret absent", installed: true, reason: reasonRecovery, keyIDVar: a.id(), setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + keyed(t, m, fc) + setKeyIDVar(fc, "acme/api", a.id()) + }}, + {name: "variable names a retained key", installed: true, reason: reasonRecovery, keyIDVar: r.id(), setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + // A run recorded a as active, then stopped before its seed + // write: the secret, the variable and the committed config + // still hold r. + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a, r)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, r)) + setTraceSecret(fc, "acme/api") + setKeyIDVar(fc, "acme/api", r.id()) + }}, + // After repos uninstall --uninstall-only on GitHub: the entry and + // the committed config keep the block, and nothing else remains. + {name: "after --uninstall-only", reason: reasonRecovery, setup: keyed}, + {name: "rotate a healthy install", installed: true, rotate: true, reason: reasonRotation, keyIDVar: a.id(), setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a, r), a) + }}, + } + for _, tc := range cases { + rotations := []bool{tc.rotate} + if tc.reason == reasonRecovery { + rotations = []bool{false, true} + } + for _, rotate := range rotations { + t.Run(fmt.Sprintf("%s/rotate=%t", tc.name, rotate), func(t *testing.T) { + fc, cfg := traceFixture(t, tc.installed, "acme/api") + tc.setup(t, cfg.Manifest, fc) + + plans, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest, Rotate: rotate}) + require.NoError(t, err) + p := requireTracePlan(t, plans, "acme/api") + assert.Equal(t, tc.reason, p.Reason) + assert.Equal(t, tc.keyIDVar, p.KeyIDVar) + assert.Equal(t, tc.keyIDVar != "", p.KeyIDVarExists) + + got := manifestTrace(t, cfg.Manifest, "acme/api") + assert.Equal(t, traceInstallA, got.InstallationID, "the installation ID is kept") + assertPlanKeyIsActive(t, p, got) + assert.Equal(t, []string{r.pubB64(), a.pubB64()}, got.VerificationKeys.Retained, + "the previous active key is retained after the earlier retained key") + assertNoForgeWrites(t, fc) + }) + } + } +} + +// An existing install without trace_context gets keys only when the +// operator rotates; the first rotation starts its installation. +func TestEnsureTraceSigningKeys_ExistingInstallKeysOnlyWithRotate(t *testing.T) { + for _, rotate := range []bool{false, true} { + t.Run(fmt.Sprintf("rotate=%t", rotate), func(t *testing.T) { + fc, cfg := traceFixture(t, true, "acme/api") + before := manifestSnapshot(t, cfg.Manifest) + + plans, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest, Rotate: rotate}) + require.NoError(t, err) + assertNoForgeWrites(t, fc) + if !rotate { + assert.Empty(t, planNames(plans)) + assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest)) + assert.False(t, findExplicitEntry(cfg.Manifest, "acme/api").Config.IsSet(), "the manifest entry gains no config") + return + } + p := requireTracePlan(t, plans, "acme/api") + assert.Equal(t, reasonRotation, p.Reason) + tc := manifestTrace(t, cfg.Manifest, "acme/api") + assertTraceBlockComplete(t, tc) + assertPlanKeyIsActive(t, p, tc) + assert.Empty(t, tc.VerificationKeys.Retained) + }) + } +} + +// From a read-only manifest (an HTTPS source, a remotely loaded manifest or +// a local file without write permission) a fresh install without Rotate +// goes ahead without keys and names the run that provisions them. Any +// other key write needs the repos.yaml edit, so the run stops before any +// edit, prints nothing and shows no generated value. +func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { + a, r := newTraceKey(1), newTraceKey(2) + const url = "https://example.com/repos.yaml" + healthy := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a, r), a) + } + cases := []struct { + name string + // installed puts a fullsend workflow on the default branch. + installed bool + // path is the manifest path; readOnlyFile is a local file without + // write permission. + path string + remote bool + rotate bool + setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) + // skipped is a fresh install that goes ahead without keys. + skipped bool + }{ + {name: "fresh install from https", path: url, skipped: true}, + {name: "fresh install from a remotely loaded manifest", remote: true, skipped: true}, + {name: "fresh install from a file without write permission", path: readOnlyFile, skipped: true}, + {name: "recovery", installed: true, path: url, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthy(t, m, fc) + delete(fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID) + delete(fc.VariablesExist, "acme/api/"+forge.VarTraceSigningKeyID) + }}, + {name: "rotation", installed: true, path: url, rotate: true, setup: healthy}, + {name: "rotation on a remotely loaded manifest", installed: true, remote: true, rotate: true, setup: healthy}, + {name: "fresh install with Rotate", path: url, rotate: true}, + {name: "re-enrollment after a full uninstall with Rotate", path: url, rotate: true, setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + // The committed block belongs to the ended installation. + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a)) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fc, cfg := traceFixture(t, tc.installed, "acme/api") + if tc.setup != nil { + tc.setup(t, cfg.Manifest, fc) + } + cfg.Manifest.sourceRemote = tc.remote + before := manifestSnapshot(t, cfg.Manifest) + path := tc.path + if path == readOnlyFile { + path = filepath.Join(t.TempDir(), "repos.yaml") + require.NoError(t, os.WriteFile(path, []byte(before), 0o444)) + } + progress := &progressLog{} + + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{ + Manifest: cfg.Manifest, ManifestPath: path, Rotate: tc.rotate, + }, newTestClientFactory(fc), progress.fn) + assert.Empty(t, planNames(plans)) + assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest), "the entry is not edited") + assertNoForgeWrites(t, fc) + lines := progress.all() + if tc.skipped { + require.NoError(t, err) + assert.Len(t, lines, 1, "one notice:\n%s", strings.Join(lines, "\n")) + assert.Equal(t, 1, countLines(lines, "acme/api manifest Trace signing keys not provisioned: repos.yaml is read-only; "+ + "a later repos install acme/api --rotate-trace-signing-key with a writable manifest provisions them"), + "the notice names the run that provisions the keys:\n%s", strings.Join(lines, "\n")) + return + } + require.ErrorIs(t, err, ErrTraceManifestReadOnly) + assertNoTraceValues(t, err.Error(), a, r) + assert.Contains(t, err.Error(), "acme/api") + assert.NotRegexp(t, `[0-9a-f]{16}`, err.Error(), "the error shows no installation ID and no key ID") + assert.Empty(t, lines, "a refusal reports nothing") + }) + } +} + +// readOnlyFile asks a test for a local manifest file without write +// permission. +const readOnlyFile = "read-only file" + +// A failed or invalid read refuses the run before any edit: the error +// names the repository and what was read, the fresh repository beside it +// gets no plan, and the GitLab repository beside them gets no notice. +func TestEnsureTraceSigningKeys_ReadErrorsRefuseBeforeAnyEdit(t *testing.T) { + a := newTraceKey(1) + failed := errors.New("the forge failed") + keyed := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a)) + } + cases := []struct { + name string + setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) + want string + }{ + {name: "committed config read fails", want: "acme/api: reading " + preset.OverlayPath + ": the forge failed", setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + fc.GetFileContentErrors = map[string]error{"acme/api/" + preset.OverlayPath: failed} + }}, + {name: "committed block invalid", want: "acme/api: committed " + preset.OverlayPath + ": trace_context.installation_id", setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + setInstalledTrace(fc, "acme/api", traceBlock(strings.Repeat("0", 32), a)) + }}, + {name: "key ID variable read fails", want: "acme/api: reading " + forge.VarTraceSigningKeyID + ": the forge failed", setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + fc.Errors = map[string]error{"GetRepoVariable": failed} + }}, + {name: "workflow read fails", want: "acme/api: checking workflow file: the forge failed", setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + fc.GetFileContentErrors = map[string]error{"acme/api/.github/workflows/fullsend.yaml": failed} + }}, + {name: "secret read fails", want: "acme/api: checking secret " + forge.SecretTraceSigningKey + ": the forge failed", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + keyed(t, m, fc) + fc.Errors = map[string]error{"RepoSecretExists": failed} + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fc, cfg := traceFixture(t, false, "acme/api", "acme/web") + cfg.Manifest.GitLab = testGitLabManifest("acme/lab").GitLab + tc.setup(t, cfg.Manifest, fc) + + err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, []string{strings.Repeat("0", 32)}, a) + assert.Contains(t, err.Error(), tc.want) + }) + } +} + +// A FULLSEND_TRACE_SIGNING_KEY_ID that is not 16 lowercase hex characters +// stops the run before any edit with its own error, which says to delete +// the variable and never shows its value. It wins over the refusal of a +// keyless entry beside a committed block. +func TestEnsureTraceSigningKeys_MalformedKeyIDVariableRefused(t *testing.T) { + a := newTraceKey(1) + malformed := []struct{ name, value string }{ + {"empty", ""}, + {"uppercase", "0123456789ABCDEF"}, + {"15 characters", "0123456789abcde"}, + {"trailing newline", "0123456789abcdef\n"}, + {"base64 seed", newTraceKey(9).seedB64()}, + } + type row struct { + name, value string + // keyless leaves acme/api's entry without trace_context beside a + // committed block. + keyless bool + } + var rows []row + for _, v := range malformed { + rows = append(rows, row{name: v.name, value: v.value}) + } + rows = append(rows, row{name: "keyless entry beside a committed block", value: malformed[1].value, keyless: true}) + for _, tc := range rows { + t.Run(tc.name, func(t *testing.T) { + fc, cfg := traceFixture(t, false, "acme/api", "acme/web") + markTraceInstalled(t, fc, "acme/api") + if tc.keyless { + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a)) + } else { + healthyTrace(t, cfg.Manifest, fc, "acme/api", traceBlock(traceInstallA, a), a) + } + setKeyIDVar(fc, "acme/api", tc.value) + + err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, []string{strings.TrimSpace(tc.value)}, a) + require.ErrorIs(t, err, ErrTraceKeyIDInvalid) + msg := err.Error() + assert.False(t, errors.Is(err, ErrTraceManifestStale), "a malformed value is not a repos.yaml mismatch") + assert.Contains(t, msg, "acme/api") + assert.Contains(t, msg, forge.VarTraceSigningKeyID) + assert.Contains(t, msg, "delete the repository variable") + assert.NotContains(t, msg, "restore the entry's trace_context") + }) + } +} + +// refusalRemedy ends every ErrTraceManifestStale refusal. +const refusalRemedy = "; repos.yaml and the trace keys were not changed: " + + "run install with the repos.yaml the last install wrote, or restore the entry's trace_context from it" + +// refusal is the ErrTraceManifestStale refusal of name for reasons. +func refusal(name string, reasons ...string) string { + return "repos.yaml does not match the repository's trace keys for " + name + ": " + strings.Join(reasons, "; ") + refusalRemedy +} + +// An entry that contradicts the committed trace_context, the key ID +// variable or another entry stops the run before any edit, with or without +// Rotate: the error names the repository, every reason with key IDs only +// and the restore remedy, and the fresh repository beside it gets no plan. +// The committed block of an ended installation is no reason, but the other +// checks still apply. +func TestEnsureTraceSigningKeys_ContradictingStateRefused(t *testing.T) { + a, b, n, x, z := newTraceKey(1), newTraceKey(2), newTraceKey(4), newTraceKey(5), newTraceKey(6) + r1, r2 := newTraceKey(7), newTraceKey(8) + twoMissing := []string{r1.id(), r2.id()} + slices.Sort(twoMissing) + const differs = "the committed trace_context.installation_id differs from the repos.yaml entry's" + trusts := func(ids string) string { + return "the committed " + preset.OverlayPath + " trusts " + ids + ", which the repos.yaml entry does not list " + + "(if you did not add the key, the committed file may have been edited: revert that change, and do not add the key to repos.yaml)" + } + unlisted := forge.VarTraceSigningKeyID + " names a key the repos.yaml entry does not list" + usedBy := func(other string) string { + return "its trace_context.installation_id is also used by the repos.yaml entry " + other + "; every repository needs its own" + } + // replaced makes acme/api's entry installation B, which replaced + // installation A, whose block is still committed; the seed and the + // variable are B's. + replaced := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallB, b)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a)) + setTraceSecret(fc, "acme/api") + setKeyIDVar(fc, "acme/api", b.id()) + } + cases := []struct { + name string + // noWorkflow leaves acme/api without a fullsend workflow on its + // default branch, so a committed block of another installation is + // an ended one. + noWorkflow bool + setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) + // reasons are acme/api's, in order; web are acme/web's when the + // run refuses it too. + reasons, web []string + // hidden is the variable's value, which the error never shows. + hidden string + }{ + {name: "a: committed installation_id differs", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a), a) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallB, a)) + }, reasons: []string{differs}}, + {name: "b: committed active key missing", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + // An older copy of repos.yaml that predates the last rotation. + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, n, a)) + setTraceSecret(fc, "acme/api") + }, reasons: []string{trusts("key ID " + n.id())}}, + {name: "c: one committed retained key missing", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a), a) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a, x)) + }, reasons: []string{trusts("key ID " + x.id())}}, + {name: "d: two committed keys missing", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a), a) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a, r1, r2)) + }, reasons: []string{trusts("key IDs " + strings.Join(twoMissing, ", "))}}, + {name: "e: committed block beside a keyless entry", setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a)) + }, reasons: []string{"the committed " + preset.OverlayPath + " has trace_context and the repos.yaml entry has none " + + "(install enrolls the repository again as a new installation only once no fullsend workflow, " + + forge.SecretTraceSigningKey + " or " + forge.VarTraceSigningKeyID + " remains, as after a finished repos uninstall)"}}, + {name: "f: key ID variable names a key the entry does not list", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a), a) + setKeyIDVar(fc, "acme/api", z.id()) + }, reasons: []string{unlisted}, hidden: z.id()}, + {name: "g: key ID variable beside a keyless entry", setup: func(_ *testing.T, _ *Manifest, fc *forge.FakeClient) { + setKeyIDVar(fc, "acme/api", z.id()) + }, reasons: []string{forge.VarTraceSigningKeyID + " is set and the repos.yaml entry has no trace_context"}, hidden: z.id()}, + {name: "h: an unselected GitLab entry uses the installation ID", setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a), a) + m.GitLab = &PlatformConfig{URL: "https://gitlab.example.com", Repos: []RepoEntry{ + {Name: "acme/lab", Config: mustManagedConfig(t, traceBlock(traceInstallA, b))}, + }} + }, reasons: []string{usedBy("acme/lab")}}, + {name: "ended block: fullsend workflow on the default branch", setup: replaced, + reasons: []string{differs, trusts("key ID " + a.id())}}, + {name: "ended block: key ID variable names a key the entry does not list", noWorkflow: true, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + replaced(t, m, fc) + setKeyIDVar(fc, "acme/api", a.id()) + }, reasons: []string{unlisted}, hidden: a.id()}, + {name: "ended block: another entry uses the installation ID", noWorkflow: true, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + replaced(t, m, fc) + setManifestTrace(t, m, "acme/web", traceBlock(traceInstallB, z)) + }, reasons: []string{usedBy("acme/web")}, web: []string{usedBy("acme/api")}}, + // After repos uninstall --uninstall-only: no workflow, but the + // committed block is the entry's own installation, so it is compared. + {name: "no workflow, same installation: committed key missing", noWorkflow: true, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, a, x)) + }, reasons: []string{trusts("key ID " + x.id())}}, + } + for _, tc := range cases { + for _, rotate := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/rotate=%t", tc.name, rotate), func(t *testing.T) { + fc, cfg := traceFixture(t, false, "acme/api", "acme/web") + if !tc.noWorkflow { + markTraceInstalled(t, fc, "acme/api") + } + tc.setup(t, cfg.Manifest, fc) + + err := refuseTrace(t, fc, TraceKeysConfig{ + Manifest: cfg.Manifest, RepoFilter: []string{"acme/api", "acme/web"}, Rotate: rotate, + }, []string{tc.hidden}, a, b, n, x, z, r1, r2) + require.ErrorIs(t, err, ErrTraceManifestStale) + want := refusal("acme/api", tc.reasons...) + if tc.web != nil { + want += "\n" + refusal("acme/web", tc.web...) + } + assert.Equal(t, want, err.Error()) + }) + } + } +} + +// traceInstallationUser skips the repository's own entry whatever the case +// of its name, as forges match repository names, and names another entry +// that uses the installation ID. Selection resolves an explicit entry under +// its own spelling, so only a direct call can pass another one. +func TestTraceInstallationUser_OwnEntryInAnyCase(t *testing.T) { + m := newConvergeManifest("Acme/API", "acme/web") + setManifestTrace(t, m, "Acme/API", traceBlock(traceInstallA, newTraceKey(1))) + installation, err := manifestTrace(t, m, "Acme/API").Installation() + require.NoError(t, err) + assert.Equal(t, "", traceInstallationUser(m, "acme/api", installation), "the repository's own entry") + + setManifestTrace(t, m, "acme/web", traceBlock(traceInstallA, newTraceKey(2))) + assert.Equal(t, "acme/web", traceInstallationUser(m, "acme/api", installation), "another entry") +} diff --git a/internal/scaffold/scaffold_env_consistency_test.go b/internal/scaffold/scaffold_env_consistency_test.go index 32ed6e5bb2..c50ac4a19e 100644 --- a/internal/scaffold/scaffold_env_consistency_test.go +++ b/internal/scaffold/scaffold_env_consistency_test.go @@ -52,6 +52,7 @@ func canonicalForgeEnvVars() map[string]struct{} { forge.SecretJiraClientID, forge.SecretJiraClientSecret, forge.SecretTraceSigningKey, + forge.VarTraceSigningKeyID, forge.VarLegacyBotTokenSecret, forge.VarLegacySA, forge.VarLegacyWIFProvider, From 387dc6a21d4b1022a0613ffadbe48202d3f5e529 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 13 Nov 2026 18:07:02 -0500 Subject: [PATCH 02/12] feat(#9060)!: provision and rotate GitHub trace signing keys in repos install repos install now plans trace signing keys after it records the install defaults and before it writes repos.yaml. It persists the trace_context edits with its other manifest edits, under the compare-before-write guard and the size limit, and convergence writes FULLSEND_TRACE_SIGNING_KEY and FULLSEND_TRACE_SIGNING_KEY_ID before the scaffold or config commit. - A fresh install from a writable repos.yaml gets a new installation ID and key pair. A later run writes a new pair, keeping the installation ID and retaining the previous public key, when the secret is missing or the key ID variable is missing or names a retained key. - --rotate-trace-signing-key writes a new pair for a healthy install and gives an existing install without trace_context its first keys. - Install stops before it writes repos.yaml or any key when an entry contradicts the committed trace_context or the key ID variable, when that variable is not a key ID, and when a read-only repos.yaml must record a key. From a read-only repos.yaml, a fresh install without the flag goes ahead without keys and says so. - The token-scope check and the sign-off identity lookup now run before install plans any repos.yaml edit, so a failure there leaves repos.yaml unchanged instead of recording a key that is never written. - Output shows installation and key IDs, never the seed. The progress line of the repos.yaml edit that copies a glob-covered repository into its own entry, whether the tracker default or the trace_context, names the new entry and the glob. When writing the seed or setting the key ID variable fails after the variable was deleted, the error says to keep and commit the repos.yaml the run wrote and to retry with it, since the seed may have been written. Repositories skipped for adoption get no key. GitLab repositories get no key yet, and install says so. - On GitHub, repos uninstall now deletes FULLSEND_TRACE_SIGNING_KEY_ID, so its Removed: line counts one more variable, and the orphan check counts the variable as managed. - repos uninstall --help says that only GitLab uninstall deletes .fullsend/config.yaml. BREAKING CHANGE: repos install now records each GitHub repository's trace signing keys as config.trace_context in its repos.yaml entry, on a fresh install from a writable repos.yaml and on the first --rotate-trace-signing-key run of an existing install. A repository that only a glob entry covers gets its own entry, copied from the glob, when that happens, so later edits to the glob entry do not reach it; edit its own entry instead. Keep and commit the repos.yaml edits install makes: a later install from a copy without them stops the run, except after a run that failed writing the seed or the key ID variable, when it replaces the key that run may have written without retaining it. If the copy with those edits is lost, rebuild the entry's trace_context from the block in the .fullsend/config.yaml that the last install committed. An entry that already declares trace_context by hand gets a new key pair, as a recovery, on its first install with this release; from a read-only repos.yaml that run stops. fullsend v0.37.0 through v0.55.0 refuse a repos.yaml that contains trace_context, and earlier releases cannot read this manifest format. v0.56.0 accepts it but does not manage FULLSEND_TRACE_SIGNING_KEY_ID: its repos status reports the variable as orphan drift and its repos uninstall leaves it, after which this release refuses the repository when it is declared again without keys, until the variable is deleted or the entry's trace_context is restored. Use a release with this change for every repos command on that manifest. Runs are unaffected: releases before v0.56.0 ignore the block in .fullsend/config.yaml, and v0.56.0 validates it. Signed-off-by: Dharit Shah --- internal/cli/repos.go | 114 ++++-- internal/cli/repos_inference_auth_test.go | 2 +- .../cli/repos_install_read_counts_test.go | 26 +- internal/cli/repos_managed_config_test.go | 17 +- internal/cli/repos_manifest_write_test.go | 30 +- internal/cli/repos_safety_order_test.go | 30 +- internal/cli/repos_trace_keys_test.go | 381 ++++++++++++++++++ internal/repos/drift.go | 6 + internal/repos/drift_test.go | 49 +++ .../repos/install_uninstall_parity_test.go | 24 +- internal/repos/managed_config_writeback.go | 13 +- .../repos/managed_config_writeback_test.go | 8 +- internal/repos/preflight_read_cache.go | 8 +- internal/repos/trace_keys_converge_test.go | 15 +- internal/repos/uninstall.go | 5 +- internal/repos/uninstall_test.go | 28 +- 16 files changed, 667 insertions(+), 89 deletions(-) create mode 100644 internal/cli/repos_trace_keys_test.go diff --git a/internal/cli/repos.go b/internal/cli/repos.go index 87cd607bff..5b10280825 100644 --- a/internal/cli/repos.go +++ b/internal/cli/repos.go @@ -396,6 +396,12 @@ type reposInstallConfig struct { jiraClientID string jiraClientSecret string + // rotateTraceSigningKey writes a new trace signing key pair and keeps + // the previous verification key as retained (ADR 0154); on an existing + // install without trace_context the first rotation provisions the + // keys. A one-run control: never persisted. + rotateTraceSigningKey bool + // GitLab-specific gitlabRoleRegistry string gitlabRoleTokens []string @@ -517,6 +523,22 @@ two credential sets are mutually exclusive; supplying one removes existing secrets of the other. When polling is false or omitted, Fullsend-owned poll resources are removed and the Jira secrets are left in place. +Trace signing keys (ADR 0154) are provisioned on GitHub only. A fresh +install generates a trace installation ID and an Ed25519 key pair, +records the installation ID and the public key in the repository's +repos.yaml entry as config.trace_context (a repository that only a glob +covers gets its own entry, copied from the glob), and writes the private +seed as the FULLSEND_TRACE_SIGNING_KEY secret and its key ID as the +FULLSEND_TRACE_SIGNING_KEY_ID variable. A later run writes a new pair, +keeping the installation ID and retaining the previous public key, when +the secret is missing, when that variable is missing or names a +retained key, and with --rotate-trace-signing-key, whose first use +gives an existing install its keys. From a read-only manifest a fresh +install without --rotate-trace-signing-key goes ahead without keys; any +other key write stops the run. Output shows installation and key IDs, +never the seed. Commit the repos.yaml changes install makes, and run one +install of a repository at a time. GitLab repositories get no keys yet. + The persistent-setting flags --roles, --fullsend-ref, --mint-url, --app-set, --inference-auth, --vendor, --signoff, --gitlab-url, --vertex-region and --forge were removed; using one fails with the repos.yaml key to set instead. @@ -557,6 +579,7 @@ GCP infrastructure (WIF, mint) must be provisioned separately via cmd.Flags().StringVar(&opts.jiraEmail, "jira-email", "", "Jira account email written as FULLSEND_JIRA_EMAIL to selected repos whose tracker.jira.poll.enabled is true (optional); an omitted value keeps the existing secret; command-line only, never written to repos.yaml") cmd.Flags().StringVar(&opts.jiraClientID, "jira-client-id", "", "Atlassian service account OAuth 2.0 client ID written as FULLSEND_JIRA_CLIENT_ID to selected repos whose tracker.jira.poll.enabled is true, instead of --jira-token; an omitted value keeps the existing secret; command-line only, never written to repos.yaml") cmd.Flags().StringVar(&opts.jiraClientSecret, "jira-client-secret", "", "Atlassian service account OAuth 2.0 client secret written as FULLSEND_JIRA_CLIENT_SECRET to selected repos whose tracker.jira.poll.enabled is true, instead of --jira-token; an omitted value keeps the existing secret; command-line only, never written to repos.yaml and never logged") + cmd.Flags().BoolVar(&opts.rotateTraceSigningKey, "rotate-trace-signing-key", false, "generate a new trace signing key pair for each selected GitHub repo, written as FULLSEND_TRACE_SIGNING_KEY with its public key recorded in repos.yaml, and keep the previous verification key as retained; on an existing install without trace_context, the first rotation provisions the keys; needs a writable repos.yaml; GitLab repos get no key yet") cmd.Flags().StringVar(&opts.gitlabRoleRegistry, "gitlab-role-registry", "", "path to administrator GitLab role registry JSON (custom roles; never secret values)") cmd.Flags().StringArrayVar(&opts.gitlabRoleTokens, "gitlab-role-token", nil, "administrator-provided GitLab role PAT (repeatable, role=token); values are never logged") cmd.Flags().BoolVar(&opts.rotateGitLabRoles, "rotate-gitlab-roles", false, "force-rotate GitLab role credentials even if they are not near expiry") @@ -772,12 +795,36 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { }) } - // The only manifest edit install still plans is the initial - // tracking writeback below. It is planned in memory (DryRun) with - // its progress output held in deferredOutput; the layered safety - // comparison then runs against the proposed manifest and presets, and - // only then is the manifest persisted, so a safety rejection leaves - // repos.yaml byte-identical and writes nothing to the forge (#8218). + // The token-scope check and the sign-off identity lookup only read, so + // they run before install plans any manifest edit: a failure leaves + // repos.yaml unchanged instead of recording a trace key whose seed is + // never written (ADR 0154). The manifest edits below carve glob-covered + // repositories into entries copied from their globs, so they change + // neither the targeted forges nor the sign-off settings. + targetedForges, err := manifest.DistinctForgesFor(opts.repoFilter) + if err != nil { + return fmt.Errorf("determining targeted forges: %w", err) + } + if err := checkAllForgeScopes(ctx, clients, printer, targetedForges); err != nil { + return err + } + + // Signoff comes from the manifest settings. Trailers are resolved once + // per forge before convergence (including dry runs) so a missing + // identity fails before any scaffold commit is made. + signOffTrailers, err := resolveRepoSignOffTrailers(ctx, clients, printer, manifest, + opts.repoFilter, opts.dryRun) + if err != nil { + return err + } + + // Install plans its manifest edits below in memory: the initial + // tracking writeback and the trace_context of fresh installs, + // recoveries and rotations (ADR 0154). Their progress output is held + // in deferredOutput; the layered safety comparison then runs against + // the proposed manifest and presets, and only then is the manifest + // persisted, so a safety rejection leaves repos.yaml byte-identical and + // writes nothing to the forge (#8218). var deferredOutput []func() deferOutput := func(f func()) { deferredOutput = append(deferredOutput, f) } manifestChanged := false @@ -804,6 +851,29 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { manifestChanged = true } + // Plan trace signing key writes (ADR 0154) and record their public keys + // in the manifest entries, under the same deferred-persist contract. A + // refusal, or a read-only manifest that must record a key, fails here, + // before the manifest write and any key write. A fresh install from a + // read-only manifest without --rotate-trace-signing-key goes ahead + // without keys and says so. + traceKeyPlans, traceErr := repos.EnsureTraceSigningKeys(ctx, repos.TraceKeysConfig{ + Manifest: manifest, + ManifestPath: opts.manifest, + Deferred: !opts.dryRun, + RepoFilter: opts.repoFilter, + ExcludeRepos: adoptionSkip, + Rotate: opts.rotateTraceSigningKey, + }, preflightClients, func(repo, _, msg string) { + deferOutput(func() { printer.StepInfo(fmt.Sprintf("[%s] %s", repo, msg)) }) + }) + if traceErr != nil { + return fmt.Errorf("planning trace signing keys: %w", traceErr) + } + if len(traceKeyPlans) > 0 { + manifestChanged = true + } + // The manifest loader converted any legacy tracker/create_issues config // to the tracker mapping in memory (#9075), so the rendered managed // overlays use the new shape. Persist the converted manifest with the @@ -839,12 +909,12 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { if manifestChanged && !opts.dryRun && opts.manifest != "" { // Another install that uses the same file may have rewritten it since // this run loaded it; writing now would drop its edits, such as a - // first-install tracker default it recorded. manifestChanged is set - // only for a writable manifest (each edit above refuses a read-only one - // or, like the legacy conversion, leaves it unwritten), so the file - // here is a local regular file. The comparison and the write are not - // atomic: a write that lands between them is overwritten. Lock the - // file if that window matters. + // first-install tracker default or the trace_context of a key it + // wrote. manifestChanged is set only for a writable manifest (each + // edit above refuses a read-only one or, like the legacy conversion, + // leaves it unwritten), so the file here is a local regular file. The + // comparison and the write are not atomic: a write that lands between + // them is overwritten. Lock the file if that window matters. current, readErr := os.ReadFile(opts.manifest) if readErr != nil { return fmt.Errorf("writing manifest: reading %s again before writing it: %w", opts.manifest, readErr) @@ -861,23 +931,6 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { flush() } - targetedForges, err := manifest.DistinctForgesFor(opts.repoFilter) - if err != nil { - return fmt.Errorf("determining targeted forges: %w", err) - } - if err := checkAllForgeScopes(ctx, clients, printer, targetedForges); err != nil { - return err - } - - // Signoff comes from the manifest settings. Trailers are resolved once - // per forge before convergence (including dry runs) so a missing - // identity fails before any scaffold commit is made. - signOffTrailers, err := resolveRepoSignOffTrailers(ctx, clients, printer, manifest, - opts.repoFilter, opts.dryRun) - if err != nil { - return err - } - upstreamRef, upstreamTag := resolveUpstreamRef() scaffoldCommitFn := func(ctx context.Context, owner, repo string, files []forge.TreeFile, direct bool, installed bool) error { @@ -973,6 +1026,7 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { JiraEmail: opts.jiraEmail, JiraClientID: opts.jiraClientID, JiraClientSecret: opts.jiraClientSecret, + TraceKeyPlans: traceKeyPlans, ReviewAppClientID: reviewAppClientID, ReviewAppClientIDAppSet: reviewAppSet, ReadVendoredWorkflow: readVendoredWorkflow, @@ -1496,7 +1550,7 @@ By default, tears down (removes workflow files via a pull request, deletes variables and secrets immediately) and then removes the repo entry from repos.yaml. The manifest entry is only removed if teardown succeeds. -File deletions (workflow YAML, .fullsend/config.yaml, and GitLab +File deletions (workflow YAML, and on GitLab .fullsend/config.yaml and the .gitlab-ci.yml unmerge) are delivered as a PR unless --direct is set. Variable and secret deletions are API operations and always happen immediately. Use --direct to push file deletions to the default branch. diff --git a/internal/cli/repos_inference_auth_test.go b/internal/cli/repos_inference_auth_test.go index e1234c04bf..904018a1a8 100644 --- a/internal/cli/repos_inference_auth_test.go +++ b/internal/cli/repos_inference_auth_test.go @@ -201,7 +201,7 @@ func TestRunReposInstall_GlobCoveredRepoMissingSelectionLeavesManifestUnchanged( require.NoError(t, readErr) assert.Equal(t, noAuthGlobManifestYAML, string(data), "a repository without an effective inference.auth gains no entry") assert.Empty(t, fc.Variables) - assert.Empty(t, fc.CreatedSecrets) + assert.Zero(t, len(fc.CreatedSecrets)) } // mixedInferenceAuthManifestYAML has one repository with a valid selection diff --git a/internal/cli/repos_install_read_counts_test.go b/internal/cli/repos_install_read_counts_test.go index 6af2831394..ee46043970 100644 --- a/internal/cli/repos_install_read_counts_test.go +++ b/internal/cli/repos_install_read_counts_test.go @@ -103,27 +103,32 @@ github: // FULLSEND_MINT_URL 3 → 2, FULLSEND_APP_SET 4 → 3. The remaining reads of // each key are convergence's own, made after the manifest write. Since // #9109 convergence also reads the managed Jira poll caller once, to keep -// it absent while Jira polling is disabled (27 and 26). +// it absent while Jira polling is disabled. The trace signing key +// preflight reads FULLSEND_TRACE_SIGNING_KEY_ID once, and an install reads +// it again right before it writes the key (ADR 0154): 29 reads for an +// install and 27 for a dry run. func TestRunReposInstall_PreflightReadsOnceConvergenceRechecks(t *testing.T) { overlayKey := "file:acme/api/" + preset.OverlayPath baseKey := "file:acme/api/" + preset.BasePath workflowKey := "file:acme/api/.github/workflows/fullsend.yaml" mintVarKey := "var:acme/api/" + forge.VarMintURL regionKey := "var:acme/api/" + forge.VarGCPRegion + keyIDVarKey := "var:acme/api/" + forge.VarTraceSigningKeyID cases := []struct { name string manifest string dryRun bool - // writeback is whether the install persists the initial - // tracking default (a manifest write before convergence). + // writeback is whether the install persists a manifest edit + // before convergence: the initial tracking default, or the + // trace_context every fresh install records (ADR 0154). writeback bool total int }{ - {name: "pristine no-preset install", manifest: githubUnmanagedManifestYAML, writeback: true, total: 27}, - {name: "pristine no-preset dry run", manifest: githubUnmanagedManifestYAML, dryRun: true, writeback: true, total: 26}, - {name: "behaviour-test manifest", manifest: behaviourTestManifestYAML, total: 27}, - {name: "behaviour-test manifest dry run", manifest: behaviourTestManifestYAML, dryRun: true, total: 26}, + {name: "pristine no-preset install", manifest: githubUnmanagedManifestYAML, writeback: true, total: 29}, + {name: "pristine no-preset dry run", manifest: githubUnmanagedManifestYAML, dryRun: true, writeback: true, total: 27}, + {name: "behaviour-test manifest", manifest: behaviourTestManifestYAML, writeback: true, total: 29}, + {name: "behaviour-test manifest dry run", manifest: behaviourTestManifestYAML, dryRun: true, writeback: true, total: 27}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -143,6 +148,13 @@ func TestRunReposInstall_PreflightReadsOnceConvergenceRechecks(t *testing.T) { assert.Equal(t, tc.total, counter.total(), "all reads: %v", counter.calls) // The undeclared region is looked up once, by convergence. assert.Equal(t, 1, counter.count(regionKey), "region reads: %v", counter.calls) + // The key ID variable is read once by the preflight and, before + // the key write, once more by an install. + wantKeyIDReads := 2 + if tc.dryRun { + wantKeyIDReads = 1 + } + assert.Equal(t, wantKeyIDReads, counter.count(keyIDVarKey), "key ID variable reads: %v", counter.calls) overlay := string(fc.FileContents[overlayPath("acme/api")]) reloaded, err := repos.LoadManifest(context.Background(), manifestPath) diff --git a/internal/cli/repos_managed_config_test.go b/internal/cli/repos_managed_config_test.go index 081270c000..b3c316c940 100644 --- a/internal/cli/repos_managed_config_test.go +++ b/internal/cli/repos_managed_config_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "os" + "regexp" "strings" "testing" @@ -243,15 +244,27 @@ func TestRunReposInstall_ManagedConfigFreshInstallDryRun(t *testing.T) { // A repository with no config key is still managed: the first install // persists the upstream tracking default in its manifest entry and -// renders exactly that into the marked sparse overlay (#8218). +// renders exactly that into the marked sparse overlay (#8218), next to +// the trace_context the fresh install generates (ADR 0154). func TestRunReposInstall_NoConfigKeyWritesSparseManagedOverlay(t *testing.T) { manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) fc := newInstallFakeClient("acme/api") require.NoError(t, runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc))) + manifest := mustReadFile(t, manifestPath) + installationID, active := traceValue(traceInstallationIDRe, manifest), traceValue(traceActiveKeyRe, manifest) + require.NotEmpty(t, installationID, "the fresh install records trace_context in repos.yaml") + require.NotEmpty(t, active) overlay := fc.FileContents[overlayPath("acme/api")] - assert.Equal(t, managedConfigMarker+"tracker:\n github:\n allowed_targets:\n repos:\n - fullsend-ai/fullsend\n - fullsend-ai/agents\n", string(overlay)) + // The trace values are random, and YAML quotes an installation ID that + // reads as a number, so they are masked in the whole-file comparison; + // TestRunReposInstall_TraceKeyOutputShowsIDsNeverSeed checks them against + // repos.yaml. + masked := regexp.MustCompile(`(?m)^( +(?:installation_id|active): ).+$`).ReplaceAllString(string(overlay), "${1}") + assert.Equal(t, managedConfigMarker+"tracker:\n github:\n allowed_targets:\n repos:\n - fullsend-ai/fullsend\n - fullsend-ai/agents\n"+ + "trace_context:\n installation_id: \n signing_key:\n secret: "+forge.SecretTraceSigningKey+ + "\n verification_keys:\n active: \n", masked) reloaded, err := repos.LoadManifest(context.Background(), manifestPath) require.NoError(t, err) diff --git a/internal/cli/repos_manifest_write_test.go b/internal/cli/repos_manifest_write_test.go index b7d8eefe42..dbb63a24c0 100644 --- a/internal/cli/repos_manifest_write_test.go +++ b/internal/cli/repos_manifest_write_test.go @@ -32,9 +32,11 @@ func (c *sharedManifestClient) GetFileContent(ctx context.Context, owner, repo, } // An install whose repos.yaml another install rewrote after this run loaded -// it does not overwrite the file, so the other install's edit survives: here -// each records the first-install tracker default of its own repository. A -// plain retry from the file then records this run's edit as well. +// it does not overwrite the file, so the other install's edits survive: here +// each records the first-install tracker default and the trace_context of +// its own repository. The refused run writes no secret or variable of its +// repository, and a plain retry from the file records this run's edits as +// well and provisions its key. func TestRunReposInstall_ManifestChangedMeanwhileIsNotOverwritten(t *testing.T) { const target = "- fullsend-ai/fullsend\n" manifestPath := writeTestManifest(t, twoRepoManifestYAML) @@ -54,13 +56,27 @@ func TestRunReposInstall_ManifestChangedMeanwhileIsNotOverwritten(t *testing.T) err := runReposInstall(context.Background(), opts) require.NoError(t, otherErr) + requireTraceKeyWritten(t, fc, "acme/web", otherFile) require.Equal(t, 1, strings.Count(otherFile, target), "the other install recorded the tracker default of acme/web") + webInstallation := traceValue(traceInstallationIDRe, otherFile) + require.NotEmpty(t, webInstallation, "the other install recorded the trace_context of acme/web") require.Error(t, err) assert.Contains(t, err.Error(), "changed after this run loaded it") - assert.Equal(t, otherFile, mustReadFile(t, manifestPath), "the other install's edit is kept") + assert.Equal(t, otherFile, mustReadFile(t, manifestPath), "the other install's edits are kept") + for _, s := range fc.CreatedSecrets { + assert.NotEqual(t, "acme/api", s.Owner+"/"+s.Repo, "the refused run writes no acme/api secret") + } + for _, v := range fc.Variables { + assert.NotEqual(t, "acme/api", v.Owner+"/"+v.Repo, "the refused run writes no acme/api variable") + } require.NoError(t, runReposInstall(context.Background(), only("acme/api")), "a plain retry from the file converges") - assert.Equal(t, 2, strings.Count(mustReadFile(t, manifestPath), target), "both tracker defaults are recorded") + final := mustReadFile(t, manifestPath) + requireTraceKeyWritten(t, fc, "acme/api", final) + requireTraceKeyWritten(t, fc, "acme/web", final) + assert.Equal(t, 2, strings.Count(final, target), "both tracker defaults are recorded") + assert.Len(t, traceInstallationIDRe.FindAllString(final, -1), 2, "both entries record trace_context") + assert.Contains(t, final, webInstallation, "acme/web's trace_context survives") } // A repos.yaml that cannot be read again just before the write stops install @@ -122,8 +138,8 @@ func TestRunReposInstall_ManifestFromPipeIsReadOnly(t *testing.T) { // An install that would rewrite repos.yaml past the size limit that loading // a manifest enforces is refused before it writes the file or anything to the // forge, in a dry run as well. This hand-written file loads, but install -// renders it with deeper indentation, and the only edit is the first-install -// tracker default of acme/api. +// renders it with deeper indentation, and the edits are the first-install +// tracker default and the trace_context of acme/api. func TestRunReposInstall_ManifestOverSizeLimitIsRefused(t *testing.T) { const limit = 1 << 20 // LoadManifest's limit var b strings.Builder diff --git a/internal/cli/repos_safety_order_test.go b/internal/cli/repos_safety_order_test.go index 6ad0570fb5..063223715d 100644 --- a/internal/cli/repos_safety_order_test.go +++ b/internal/cli/repos_safety_order_test.go @@ -26,18 +26,21 @@ func assertNoInstallWrites(t *testing.T, fc *forge.FakeClient) { assert.Empty(t, fc.ForceCommittedFiles, "no forced commits") assert.Empty(t, fc.CreatedBranches, "no branches") assert.Empty(t, fc.CreatedProposals, "no PR/MR") - assert.Empty(t, fc.CreatedSecrets, "no secret writes") + // Counted, not printed: a secret value must not reach the test log. + assert.Zero(t, len(fc.CreatedSecrets), "no secret writes") assert.Empty(t, fc.DeletedSecrets, "no secret deletions") assert.Empty(t, fc.Variables, "no variable writes") assert.Empty(t, fc.UpdatedVariables, "no variable updates") + assert.Empty(t, fc.DeletedVariables, "no variable deletions") } // A layered safety rejection stops `repos install` before repos.yaml is -// persisted or the forge is written to. The only manifest edit install still -// plans (the install defaults recorded for a pending install) is applied in -// memory and compared with the installed layers first, for an overlay -// relaxation and for a preset replacement alike; selecting a glob-covered -// repository plans no edit at all (#8219). +// persisted or the forge is written to. The manifest edits install plans +// (here the install defaults and the trace_context of a pending install) are +// applied in memory and compared with the installed layers first, for an +// overlay relaxation and for a preset replacement alike; selecting an +// installed glob-covered repository plans no edit at all (#8219). The +// refused run reports no repos.yaml edit either. func TestRunReposInstall_SafetyRejectionLeavesManifestByteIdentical(t *testing.T) { const header = `version: 1 %DEFAULTS%github: @@ -122,10 +125,14 @@ func TestRunReposInstall_SafetyRejectionLeavesManifestByteIdentical(t *testing.T opts := githubManagedInstallOpts(manifestPath, fc) sc.edit(opts) - err := runReposInstall(context.Background(), opts) + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) require.Error(t, err) assert.Contains(t, err.Error(), rej.want) + // Compared without printing: a seed the refused run generated is + // never written, so none can be checked for first. + assert.False(t, strings.Contains(out, "Persisted"), "a refused run reports no repos.yaml edit") data, readErr := os.ReadFile(manifestPath) require.NoError(t, readErr) assert.Equal(t, manifestYAML, string(data), "repos.yaml must be byte-identical after a rejection") @@ -139,7 +146,8 @@ func TestRunReposInstall_SafetyRejectionLeavesManifestByteIdentical(t *testing.T // mint_url and the declared configuration disagree on, or a Vertex flag // that contradicts the declared value) are rejected before the planned // tracking writeback is persisted, so repos.yaml stays byte-identical -// — including for a pristine glob-covered repository. +// — including for a pristine glob-covered repository — and the refused run +// reports no repos.yaml edit. func TestRunReposInstall_InfrastructureConflictLeavesManifestByteIdentical(t *testing.T) { const manifestHeader = `version: 1 defaults: @@ -188,10 +196,14 @@ defaults: opts := githubManagedInstallOpts(manifestPath, fc) opts.repoFilter = sc.filter - err := runReposInstall(context.Background(), opts) + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) require.Error(t, err) assert.Contains(t, err.Error(), sc.want) + // Compared without printing: a seed the refused run generated is + // never written, so none can be checked for first. + assert.False(t, strings.Contains(out, "Persisted"), "a refused run reports no repos.yaml edit") data, readErr := os.ReadFile(manifestPath) require.NoError(t, readErr) assert.Equal(t, manifestYAML, string(data), "repos.yaml must be byte-identical after a rejection") diff --git a/internal/cli/repos_trace_keys_test.go b/internal/cli/repos_trace_keys_test.go new file mode 100644 index 0000000000..29df61fb43 --- /dev/null +++ b/internal/cli/repos_trace_keys_test.go @@ -0,0 +1,381 @@ +package cli + +import ( + "context" + "crypto/ed25519" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "os" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/repos" + "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" +) + +// traceSecretNameRe matches the secret name on its own, not as the prefix +// of FULLSEND_TRACE_SIGNING_KEY_ID. +var traceSecretNameRe = regexp.MustCompile(`\b` + forge.SecretTraceSigningKey + `\b`) + +// trace_context values as repos.yaml and the managed overlay render them. +var ( + traceInstallationIDRe = regexp.MustCompile(`installation_id:\s*["']?([0-9a-f]{32})\b`) + traceActiveKeyRe = regexp.MustCompile(`active:\s*["']?([A-Za-z0-9+/]{43}=)`) +) + +// traceValue returns the value re captures in yaml, or "" when it has none. +func traceValue(re *regexp.Regexp, yaml string) string { + if m := re.FindStringSubmatch(yaml); m != nil { + return m[1] + } + return "" +} + +// writtenTraceSeed returns the last FULLSEND_TRACE_SIGNING_KEY value written +// to repo, or "" when none was written. It is a seed: compare it, never +// print it. +func writtenTraceSeed(fc *forge.FakeClient, repo string) string { + seed := "" + for _, s := range fc.CreatedSecrets { + if s.Owner+"/"+s.Repo == repo && s.Name == forge.SecretTraceSigningKey { + seed = s.Value + } + } + return seed +} + +// hexTraceKeyID is the key ID of pub as 16 lowercase hex characters, +// derived with tracecontext.KeyID rather than the code under test. +func hexTraceKeyID(pub ed25519.PublicKey) string { + id := tracecontext.KeyID(pub) + return hex.EncodeToString(id[:]) +} + +// traceSeedForms decodes a written seed and returns its hex key ID, its +// public key as standard base64 (the form verification_keys holds), and +// the printable forms that must never appear in output: the 42-character +// base64 prefix it shares with the 64-byte private key, and its hex. +func traceSeedForms(t *testing.T, seedB64 string) (keyID, pub string, leaks []string) { + t.Helper() + seed, err := base64.StdEncoding.DecodeString(seedB64) + require.NoError(t, err, "the secret holds standard base64") + require.Equal(t, ed25519.SeedSize, len(seed), "the secret holds a 32-byte seed") + pk := ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey) + return hexTraceKeyID(pk), base64.StdEncoding.EncodeToString(pk), []string{seedB64[:42], hex.EncodeToString(seed)} +} + +// requireTraceKeyWritten requires a FULLSEND_TRACE_SIGNING_KEY write to repo +// and, without printing them, that no text shows its seed; then that +// FULLSEND_TRACE_SIGNING_KEY_ID names the written key. It returns the key's +// ID and its public key in standard base64. +func requireTraceKeyWritten(t *testing.T, fc *forge.FakeClient, repo string, texts ...string) (keyID, pub string) { + t.Helper() + seed := writtenTraceSeed(fc, repo) + require.True(t, seed != "", "%s gets a %s write", repo, forge.SecretTraceSigningKey) + keyID, pub, leaks := traceSeedForms(t, seed) + for i, s := range texts { + for _, leak := range leaks { + require.False(t, strings.Contains(s, leak), "text %d shows the seed of %s", i, repo) + } + } + assert.Equal(t, keyID, fc.VariableValues[repo+"/"+forge.VarTraceSigningKeyID], "the variable names the written key of %s", repo) + return keyID, pub +} + +// indentLines prefixes every line of s with indent. +func indentLines(indent, s string) string { + return indent + strings.ReplaceAll(strings.TrimSuffix(s, "\n"), "\n", "\n"+indent) + "\n" +} + +// --rotate-trace-signing-key is a one-run boolean, off by default, whose help +// says that the first rotation provisions an existing install. +func TestReposInstallCmd_RotateTraceSigningKeyFlag(t *testing.T) { + f := newReposInstallCmd().Flags().Lookup("rotate-trace-signing-key") + require.NotNil(t, f) + assert.Equal(t, "bool", f.Value.Type()) + assert.Equal(t, "false", f.DefValue) + assert.Contains(t, f.Usage, "on an existing install without trace_context, the first rotation provisions the keys") +} + +// A dry run of a fresh install, and the install that follows, name both +// trace names and show the installation ID and key ID, never the seed +// (ADR 0154). The dry run's key is never written, so the test cannot +// read its seed: the dry run's trace lines must show no value shaped like +// one, and the install's output, repos.yaml and the overlay must not show +// the written seed. The dry run leaves repos.yaml byte-identical and writes +// nothing. The install records the written seed's public key and the +// installation ID in repos.yaml and the managed overlay, and sets +// FULLSEND_TRACE_SIGNING_KEY_ID to the seed's key ID. +func TestRunReposInstall_TraceKeyOutputShowsIDsNeverSeed(t *testing.T) { + persisted := regexp.MustCompile(`\[acme/api\] (Would persist|Persisted) config\.trace_context in the manifest entry: ` + + `installation ID ([0-9a-f]{32}), new active key ID ([0-9a-f]{16}) \(fresh install\)`) + // A 32-byte value as standard base64 or unpadded URL-safe base64. Its 64 + // hex digits match too, as does the private key in any of these forms. + seedShaped := regexp.MustCompile(`[A-Za-z0-9+/]{43}=|[A-Za-z0-9_-]{43}`) + manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) + fc := newInstallFakeClient("acme/api") + install := func(dryRun bool) string { + t.Helper() + opts := githubManagedInstallOpts(manifestPath, fc) + opts.dryRun = dryRun + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + require.NoError(t, err) + return out + } + + dryOut := install(true) + // Checked before any assertion that prints the dry run's output, on the + // trace lines only, since other lines may hold long names, and with the + // manifest path masked, since t.TempDir names it after this test: the + // name contains "Trace" and is long enough to look like a seed. + for _, line := range strings.Split(strings.ReplaceAll(dryOut, manifestPath, ""), "\n") { + if strings.Contains(strings.ToLower(line), "trace") { + require.False(t, seedShaped.MatchString(line), "a dry-run trace line shows a seed-shaped value") + } + } + assert.Equal(t, githubUnmanagedManifestYAML, mustReadFile(t, manifestPath), "a dry run leaves repos.yaml byte-identical") + assertNoInstallWrites(t, fc) + + liveOut := install(false) + manifest := mustReadFile(t, manifestPath) + overlay := string(fc.FileContents[overlayPath("acme/api")]) + keyID, pub := requireTraceKeyWritten(t, fc, "acme/api", liveOut, manifest, overlay) + + dry := persisted.FindAllStringSubmatch(dryOut, -1) + require.Len(t, dry, 1, "the dry run previews the repos.yaml edit once:\n%s", dryOut) + assert.Equal(t, "Would persist", dry[0][1]) + assert.Regexp(t, `\[acme/api\] Would set secret `+traceSecretNameRe.String(), dryOut) + assert.Contains(t, dryOut, "[acme/api] Would set variable "+forge.VarTraceSigningKeyID) + live := persisted.FindAllStringSubmatch(liveOut, -1) + require.Len(t, live, 1, "the install reports the repos.yaml edit once") + assert.Equal(t, "Persisted", live[0][1]) + installationID := traceValue(traceInstallationIDRe, manifest) + assert.Equal(t, live[0][2], installationID, "repos.yaml records the installation ID the install showed") + assert.Equal(t, keyID, live[0][3], "the install shows the written seed's key ID") + assert.Equal(t, pub, traceValue(traceActiveKeyRe, manifest), "repos.yaml's active key is the written seed's public key") + assert.Equal(t, installationID, traceValue(traceInstallationIDRe, overlay), "the managed overlay carries the installation ID") + assert.Equal(t, pub, traceValue(traceActiveKeyRe, overlay), "the managed overlay carries the active key") + assert.Regexp(t, `\[acme/api\] Set secret `+traceSecretNameRe.String(), liveOut) + assert.Contains(t, liveOut, "[acme/api] Set variable "+forge.VarTraceSigningKeyID) +} + +// --rotate-trace-signing-key reaches the key planner: an existing install +// without trace_context gets keys only with the flag, its first rotation +// being the initial provisioning. The install writes the seed, sets the key +// ID variable to its key ID, records the block in repos.yaml with that key +// active and commits the same block in the managed overlay. +func TestRunReposInstall_RotateTraceSigningKeyProvisionsExistingInstall(t *testing.T) { + for _, rotate := range []bool{false, true} { + t.Run(fmt.Sprintf("rotate=%t", rotate), func(t *testing.T) { + manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) + fc := newInstalledFakeClientCLI("acme/api") + opts := githubManagedInstallOpts(manifestPath, fc) + opts.rotateTraceSigningKey = rotate + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + require.NoError(t, err) + + manifest := mustReadFile(t, manifestPath) + if !rotate { + assert.Zero(t, len(writtenTraceSeed(fc, "acme/api")), "no %s write without the flag", forge.SecretTraceSigningKey) + assert.NotContains(t, fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID, "no key ID variable") + assert.NotContains(t, manifest, "trace_context") + return + } + overlay := string(fc.FileContents[overlayPath("acme/api")]) + keyID, pub := requireTraceKeyWritten(t, fc, "acme/api", out, manifest, overlay) + installationID := traceValue(traceInstallationIDRe, manifest) + require.NotEmpty(t, installationID, "the repos.yaml entry gains trace_context") + assert.Equal(t, pub, traceValue(traceActiveKeyRe, manifest), "repos.yaml's active key is the written seed's public key") + assert.Equal(t, installationID, traceValue(traceInstallationIDRe, overlay), "the commit delivers the installation ID") + assert.Equal(t, pub, traceValue(traceActiveKeyRe, overlay), "the commit delivers the active key") + assert.Contains(t, out, "[acme/api] Persisted config.trace_context in the manifest entry: installation ID "+installationID+ + ", new active key ID "+keyID+" (rotation)") + }) + } +} + +// repos.yaml records the new key before the first forge write, so a failed +// seed write leaves the key recorded and the key ID variable absent. The next +// plain run writes a new key and the variable names it; the installation ID +// is kept and the key that was never written stays retained. +func TestRunReposInstall_TraceKeyRetryAfterSecretWriteFailure(t *testing.T) { + manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) + fc := newInstallFakeClient("acme/api") + fc.Errors["CreateRepoSecret"] = errors.New("secret write refused") + var err error + captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) + require.Error(t, err, "the failed secret write fails the install") + + first := mustReadFile(t, manifestPath) + installationID := traceValue(traceInstallationIDRe, first) + require.NotEmpty(t, installationID, "repos.yaml records trace_context before the secret write fails") + unwritten := traceValue(traceActiveKeyRe, first) + require.NotEmpty(t, unwritten, "repos.yaml records the new key as active") + assert.NotContains(t, fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID, "no key ID variable without the seed") + + delete(fc.Errors, "CreateRepoSecret") + out := captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) + require.NoError(t, err) + + second := mustReadFile(t, manifestPath) + _, pub := requireTraceKeyWritten(t, fc, "acme/api", out, second) + assert.NotEqual(t, unwritten, pub, "the retry generates a new key") + assert.Equal(t, pub, traceValue(traceActiveKeyRe, second), "the written key is active") + assert.Equal(t, installationID, traceValue(traceInstallationIDRe, second), "the installation ID is kept") + assert.Regexp(t, `retained:\s*-\s*["']?`+regexp.QuoteMeta(unwritten), second, "the key that was never written stays retained") +} + +// The token-scope check and the sign-off identity lookup only read, and they +// run before install plans any repos.yaml edit: when either fails, repos.yaml +// stays byte-identical, so it records no trace_context for a key that was +// never written, and nothing is written to the forge. +func TestRunReposInstall_ScopeOrIdentityFailureLeavesManifestUnchanged(t *testing.T) { + cases := []struct { + name, manifest, want string + setup func(fc *forge.FakeClient) + }{ + {name: "token without the workflow scope", manifest: githubUnmanagedManifestYAML, want: "token is missing required scopes: workflow", + setup: func(fc *forge.FakeClient) { + fc.InstallationToken = false + fc.TokenScopes = []string{"repo"} + }}, + {name: "sign-off without a user identity", manifest: strings.Replace(githubUnmanagedManifestYAML, "github:\n", "github:\n signoff: true\n", 1), + want: "signoff requires a GitHub user identity"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + manifestPath := writeTestManifest(t, tc.manifest) + fc := newInstallFakeClient("acme/api") + if tc.setup != nil { + tc.setup(fc) + } + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + // Compared without printing: no seed is written, so none can be + // checked for first. + assert.True(t, mustReadFile(t, manifestPath) == tc.manifest, "repos.yaml is byte-identical, with no trace_context") + assert.False(t, strings.Contains(out, "Persisted"), "the run reports no repos.yaml edit") + assertNoInstallWrites(t, fc) + }) + } +} + +// A committed config that trusts a key the repos.yaml entry does not list +// stops the install before repos.yaml is persisted or the forge is written, +// and the error names the key by its ID only. +func TestRunReposInstall_ContradictingCommittedConfigRefusedBeforeWrites(t *testing.T) { + active, extra := testTraceVerificationKey(1), testTraceVerificationKey(3) + manifest := githubUnmanagedManifestYAML + " config:\n" + + indentLines(" ", traceContextYAML(testTraceInstallationID, forge.SecretTraceSigningKey, active)) + manifestPath := writeTestManifest(t, manifest) + fc := newInstalledFakeClientCLI("acme/api") + fc.FileContents[overlayPath("acme/api")] = []byte(managedConfigMarker + + traceContextYAML(testTraceInstallationID, forge.SecretTraceSigningKey, active, extra)) + fc.Secrets["acme/api/"+forge.SecretTraceSigningKey] = true + fc.VariableValues["acme/api/"+forge.VarTraceSigningKeyID] = hexTraceKeyID(testTracePublicKey(1)) + fc.VariablesExist["acme/api/"+forge.VarTraceSigningKeyID] = true + + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) + require.ErrorIs(t, err, repos.ErrTraceManifestStale) + msg := err.Error() + assert.True(t, strings.HasPrefix(msg, "planning trace signing keys: "), msg) + assert.Contains(t, msg, "acme/api") + assert.Contains(t, msg, "trusts key ID "+hexTraceKeyID(testTracePublicKey(3)), "the error names the extra key by its ID") + for _, key := range []string{active, extra} { + assert.NotContains(t, msg+out, key, "a verification key appears only as its ID") + } + assert.Equal(t, manifest, mustReadFile(t, manifestPath), "repos.yaml is not written") + assertNoInstallWrites(t, fc) +} + +// A fresh repository whose markerless .fullsend/config.yaml needs adoption +// is skipped by convergence (#8511), so the trace-key preflight skips it +// too: repos.yaml records no trace_context and no key is written. +func TestRunReposInstall_AdoptionSkippedRepoGetsNoTraceKey(t *testing.T) { + manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) + fc := newInstallFakeClient("acme/api") + fc.FileContents[overlayPath("acme/api")] = []byte("kill_switch: false\n# hand-authored\n") + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) + require.Error(t, err) + require.Zero(t, len(writtenTraceSeed(fc, "acme/api")), "no %s write", forge.SecretTraceSigningKey) + assert.Contains(t, out, "FAILED: acme/api — adoption required") + assert.Equal(t, githubUnmanagedManifestYAML, mustReadFile(t, manifestPath), "no key is recorded for the skipped repo") + assert.NotContains(t, out, "trace_context") + assert.NotContains(t, fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID, "no key ID variable") +} + +// A fresh install from a read-only repos.yaml installs the repository +// without trace keys: it writes neither the seed nor the key ID variable, +// leaves repos.yaml byte-identical and says which run provisions the keys. +// Asking for a rotation fails before any write. The entry declares its +// tracker, so install needs no other repos.yaml edit. +func TestRunReposInstall_ReadOnlyManifestFreshInstallSkipsTraceKeys(t *testing.T) { + for _, rotate := range []bool{false, true} { + t.Run(fmt.Sprintf("rotate=%t", rotate), func(t *testing.T) { + manifestPath := writeTestManifest(t, behaviourTestManifestYAML) + require.NoError(t, os.Chmod(manifestPath, 0o444)) + fc := newInstallFakeClient("acme/api") + opts := githubManagedInstallOpts(manifestPath, fc) + opts.rotateTraceSigningKey = rotate + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + assert.Equal(t, behaviourTestManifestYAML, mustReadFile(t, manifestPath), "repos.yaml is byte-identical") + if rotate { + require.ErrorIs(t, err, repos.ErrTraceManifestReadOnly) + assertNoInstallWrites(t, fc) + return + } + require.NoError(t, err) + require.Zero(t, len(writtenTraceSeed(fc, "acme/api")), "no %s write", forge.SecretTraceSigningKey) + assert.NotEmpty(t, fc.CommittedFiles, "the repository is installed") + assert.NotContains(t, fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID, "no key ID variable") + assert.NotContains(t, string(fc.FileContents[overlayPath("acme/api")]), "trace_context") + assert.Equal(t, 1, strings.Count(out, "[acme/api] Trace signing keys not provisioned: repos.yaml is read-only; "+ + "a later repos install acme/api --rotate-trace-signing-key with a writable manifest provisions them"), out) + }) + } +} + +// A repository whose re-enrollment has not landed does not stop another +// repository's install. Its repos.yaml entry, seed and key ID variable belong +// to the new installation, while its default branch has no fullsend workflow +// and keeps the ended installation's trace_context. Install names the ended +// installation once, gives the fresh repository its keys, and the commit +// replaces the ended block with the entry's. +func TestRunReposInstall_PendingReenrollmentDoesNotBlockOtherRepos(t *testing.T) { + const entryInstallationID = "fedcba9876543210fedcba9876543210" + manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML+" config:\n"+ + indentLines(" ", traceContextYAML(entryInstallationID, forge.SecretTraceSigningKey, testTraceVerificationKey(3)))+ + " - name: acme/web\n") + fc := newInstallFakeClient("acme/api", "acme/web") + fc.FileContents[overlayPath("acme/api")] = []byte(managedConfigMarker + + traceContextYAML(testTraceInstallationID, forge.SecretTraceSigningKey, testTraceVerificationKey(1))) + fc.Secrets["acme/api/"+forge.SecretTraceSigningKey] = true + fc.VariableValues["acme/api/"+forge.VarTraceSigningKeyID] = hexTraceKeyID(testTracePublicKey(3)) + fc.VariablesExist["acme/api/"+forge.VarTraceSigningKeyID] = true + + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) + require.NoError(t, err) + require.Zero(t, len(writtenTraceSeed(fc, "acme/api")), "acme/api's key is healthy") + _, webPub := requireTraceKeyWritten(t, fc, "acme/web", out) + ended := regexp.MustCompile(regexp.QuoteMeta("[acme/api]") + `.*ended installation ` + testTraceInstallationID + + `: the repos.yaml entry's installation replaces it and stops trusting key ID ` + hexTraceKeyID(testTracePublicKey(1))) + assert.Len(t, ended.FindAllString(out, -1), 1, "install names the ended installation once:\n%s", out) + assert.Equal(t, webPub, traceValue(traceActiveKeyRe, string(fc.FileContents[overlayPath("acme/web")])), "acme/web's commit carries its key") + assert.Equal(t, entryInstallationID, traceValue(traceInstallationIDRe, string(fc.FileContents[overlayPath("acme/api")])), + "the commit replaces the ended block") +} diff --git a/internal/repos/drift.go b/internal/repos/drift.go index ce7ef2105b..db8e36f8b1 100644 --- a/internal/repos/drift.go +++ b/internal/repos/drift.go @@ -227,6 +227,12 @@ func CheckOrphanVars(ctx context.Context, client forge.Client, for _, s := range managedInferenceSecrets() { managedNames[s] = true } + // Install records the trace signing key's key ID in this variable on + // GitHub (ADR 0154). It is managed but, like FULLSEND_DISPATCH_SECRET, + // not required. + if cfg.Forge != ForgeGitLab { + managedNames[forge.VarTraceSigningKeyID] = true + } // FULLSEND_DISPATCH_SECRET is auto-provisioned by install/converge // to sign poll state. It is managed, not an orphan, but is // intentionally not in requiredSecretsForForge — that would mark diff --git a/internal/repos/drift_test.go b/internal/repos/drift_test.go index a6293ba560..5d157e5315 100644 --- a/internal/repos/drift_test.go +++ b/internal/repos/drift_test.go @@ -2,6 +2,7 @@ package repos import ( "context" + "slices" "testing" "github.com/fullsend-ai/fullsend/internal/forge" @@ -386,6 +387,54 @@ func TestCheckOrphanVars_GitLabWebhookVarsManagedButGenuineOrphanReported(t *tes } } +// Install writes FULLSEND_TRACE_SIGNING_KEY_ID on GitHub only (ADR 0154), so +// status counts it as managed there, while an unknown FULLSEND_ variable +// beside it is still an orphan. On GitLab install writes no such variable, +// and one found there is reported. +func TestCheckOrphanVars_TraceSigningKeyIDManagedOnGitHub(t *testing.T) { + cases := []struct { + forgeName, mintURL string + want []string + }{ + {ForgeGitHub, "https://mint.example.com", []string{"FULLSEND_UNKNOWN_LEFTOVER"}}, + {ForgeGitLab, "", []string{forge.VarTraceSigningKeyID, "FULLSEND_UNKNOWN_LEFTOVER"}}, + } + for _, tc := range cases { + t.Run(tc.forgeName, func(t *testing.T) { + fc := forge.NewFakeClient() + fc.VariableValues["owner/repo/"+forge.VarTraceSigningKeyID] = "x" + fc.VariableValues["owner/repo/FULLSEND_UNKNOWN_LEFTOVER"] = "x" + + orphans, err := CheckOrphanVars(context.Background(), fc, "owner", "repo", + InstallConfig{Forge: tc.forgeName, MintURL: tc.mintURL}, tc.mintURL) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + var names []string + for _, o := range orphans { + names = append(names, o.Name) + } + slices.Sort(names) + if !slices.Equal(names, tc.want) { + t.Errorf("orphans = %v, want %v", names, tc.want) + } + }) + } +} + +// Guard: the trace signing key and its key ID variable are managed but never +// required, so an install without them is not incomplete. +func TestTraceSigningKeyNamesNotRequired(t *testing.T) { + for _, forgeName := range []string{ForgeGitHub, ForgeGitLab} { + if slices.Contains(requiredVarsForForge(forgeName), forge.VarTraceSigningKeyID) { + t.Errorf("requiredVarsForForge(%s) must not include %s", forgeName, forge.VarTraceSigningKeyID) + } + if slices.Contains(requiredSecretsForForge(forgeName), forge.SecretTraceSigningKey) { + t.Errorf("requiredSecretsForForge(%s) must not include %s", forgeName, forge.SecretTraceSigningKey) + } + } +} + func TestCheckOrphanFiles_GitLabDispatchStubIsOrphan(t *testing.T) { fc := forge.NewFakeClient() fc.FileContents["owner/repo/"+fullsendPipelineInclude] = []byte("---\n# fullsend-ref: v2.5.0\n") diff --git a/internal/repos/install_uninstall_parity_test.go b/internal/repos/install_uninstall_parity_test.go index 2a9d15cec8..7fef3ba4d9 100644 --- a/internal/repos/install_uninstall_parity_test.go +++ b/internal/repos/install_uninstall_parity_test.go @@ -2,6 +2,7 @@ package repos import ( "fmt" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -21,12 +22,12 @@ import ( // asserted. The uninstall lists intentionally carry names install never // writes, so that repositories installed by earlier versions are still cleaned // up: the superseded poller variables in gitlabRetiredLegacyVars, the -// forge.VarLegacy* names, and the GitLab role-credential secrets. They also -// carry the trace signing key (ADR 0154), which install does not write. Two -// further omissions are deliberate and documented at their definitions — -// gitlabUninstallVars excludes the legacy shared forge token, and -// gitlabUninstallSecrets excludes the unprefixed OPENAI_API_KEY because other -// jobs in the same project may depend on it. +// forge.VarLegacy* names, and the GitLab role-credential secrets. The GitLab +// uninstall list also carries the trace signing key (ADR 0154), which install +// does not write on GitLab. Two further omissions are deliberate and +// documented at their definitions — gitlabUninstallVars excludes the legacy +// shared forge token, and gitlabUninstallSecrets excludes the unprefixed +// OPENAI_API_KEY because other jobs in the same project may depend on it. // // One consequence worth stating: the secret check does not catch a name added // to inferenceSecretsForAuth that installSecretsForForge never writes. Only @@ -37,12 +38,15 @@ import ( // variable builders, which the parity check therefore cannot discover on its // own. GitLab's FULLSEND_DISPATCH_SECRET is written by seedGitLabPollState // (install.go, GitLab branch only) through poll.EnsureDispatchSecret, and is -// cleaned up from gitlabUninstallVars. +// cleaned up from gitlabUninstallVars. On GitHub, convergeTraceSigningKey +// writes FULLSEND_TRACE_SIGNING_KEY_ID next to the trace signing key +// (ADR 0154), and uninstallVariables deletes it. // // This list is itself hand-maintained, which is the very thing these tests // exist to discourage. It is the narrow cost of keeping the check in the test // package; if install grows another out-of-band value, add it here. var installSideExtras = map[string][]string{ + ForgeGitHub: {forge.VarTraceSigningKeyID}, ForgeGitLab: {forge.SecretDispatch}, } @@ -65,14 +69,16 @@ func parityInstallConfig(forgeName, auth string) InstallConfig { // installSideSecretExtras names repository secrets install provisions outside // installSecretsForForge, which the secret parity check cannot discover on its // own. convergeJiraPoll writes the Jira polling credentials (jiraSecretValues) -// for repos whose effective tracker.jira.poll.enabled is true on both forges. +// for repos whose effective tracker.jira.poll.enabled is true on both forges, +// and on GitHub convergeTraceSigningKey writes FULLSEND_TRACE_SIGNING_KEY +// (ADR 0154). // Hand-maintained, like installSideExtras: add any further out-of-band secret. var installSideSecretExtras = func() map[string][]string { var names []string for name := range jiraSecretValues(ConvergeConfig{JiraToken: "token", JiraEmail: "email"}) { names = append(names, name) } - return map[string][]string{ForgeGitHub: names, ForgeGitLab: names} + return map[string][]string{ForgeGitHub: append(slices.Clone(names), forge.SecretTraceSigningKey), ForgeGitLab: names} }() func TestInstallUninstallVariableParity(t *testing.T) { diff --git a/internal/repos/managed_config_writeback.go b/internal/repos/managed_config_writeback.go index 1a0f9420a0..a9b2cbd1a1 100644 --- a/internal/repos/managed_config_writeback.go +++ b/internal/repos/managed_config_writeback.go @@ -320,7 +320,8 @@ type pendingWriteback struct { // A declared preset keeps inheriting its own tracker, and an // explicit manifest value is never overridden. A repository covered only // by a glob gets its own explicit entry copied from the glob so sibling -// repositories are unaffected. Existing overlays are not touched here +// repositories are unaffected, and progress names that entry and the +// glob. Existing overlays are not touched here // (install excludes a repository whose markerless overlay needs adoption). // // The in-memory manifest is always updated so rendering sees the values. @@ -393,20 +394,22 @@ func EnsureManagedConfigDefaults(ctx context.Context, cfg ManagedConfigWriteback } names := make([]string, 0, len(pending)) + // globs[i] names the glob entry pending[i]'s new entry is copied from. + globs := make([]string, len(pending)) needsNewEntry := make(map[string]bool, len(pending)) - for _, p := range pending { + for i, p := range pending { name := p.rr.Owner + "/" + p.rr.Repo entry := findExplicitEntry(m, name) if entry == nil { needsNewEntry[name] = true - carved, _, err := carveOutForForge(m, name, p.rr.Forge) + carved, glob, err := carveOutForForge(m, name, p.rr.Forge) if err != nil { return nil, fmt.Errorf("%s: %w", name, err) } if carved == nil { return nil, fmt.Errorf("no manifest entry or glob covers %q", name) } - entry = carved + entry, globs[i] = carved, glob } entry.Config = p.cfg names = append(names, name) @@ -424,7 +427,7 @@ func EnsureManagedConfigDefaults(ctx context.Context, cfg ManagedConfigWriteback if cfg.DryRun && !cfg.Deferred { verb = "Would persist" } - progress(names[i], "manifest", fmt.Sprintf("%s config.%s in the manifest entry", verb, strings.Join(p.what, ", config."))) + progress(names[i], "manifest", fmt.Sprintf("%s config.%s in %s", verb, strings.Join(p.what, ", config."), manifestEntryWhere(names[i], globs[i]))) } return names, nil } diff --git a/internal/repos/managed_config_writeback_test.go b/internal/repos/managed_config_writeback_test.go index 1d3278c17c..f3e465ad67 100644 --- a/internal/repos/managed_config_writeback_test.go +++ b/internal/repos/managed_config_writeback_test.go @@ -132,6 +132,9 @@ func TestEnsureManagedConfigDefaults_ForgeSpecificTargets(t *testing.T) { } } +// A repository that only a glob covers gets its own entry, copied from the +// glob, and progress names that entry and the glob, since later edits to +// the glob no longer reach it. func TestEnsureManagedConfigDefaults_GlobCoveredGetsScopedEntry(t *testing.T) { m := &Manifest{Version: 1, Defaults: testInferenceDefaults(), GitHub: &PlatformConfig{ Repos: []RepoEntry{{Name: "acme/*", FullsendRef: "v1.2.3"}}, @@ -139,11 +142,14 @@ func TestEnsureManagedConfigDefaults_GlobCoveredGetsScopedEntry(t *testing.T) { path := writebackManifestFile(t, m) fc := newFakeClientForBatch("acme/api", "acme/web") + var msgs []string names, err := EnsureManagedConfigDefaults(context.Background(), ManagedConfigWritebackConfig{ Manifest: m, ManifestPath: path, RepoFilter: []string{"acme/api"}, - }, newTestClientFactory(fc), nil) + }, newTestClientFactory(fc), func(repo, _, msg string) { msgs = append(msgs, repo+": "+msg) }) require.NoError(t, err) assert.Equal(t, []string{"acme/api"}, names) + assert.Equal(t, []string{"acme/api: Persisted config.tracker.github.allowed_targets.repos: [fullsend-ai/fullsend, fullsend-ai/agents] " + + "in the new manifest entry acme/api, copied from the glob entry acme/*"}, msgs) require.Len(t, m.GitHub.Repos, 2) assert.False(t, m.GitHub.Repos[0].Config.IsSet(), "the glob entry is unchanged so siblings are unaffected") diff --git a/internal/repos/preflight_read_cache.go b/internal/repos/preflight_read_cache.go index 320782fde0..00167d721c 100644 --- a/internal/repos/preflight_read_cache.go +++ b/internal/repos/preflight_read_cache.go @@ -17,10 +17,10 @@ import ( // The cache never observes a write it did not make, so it is only correct // for a window in which nothing writes to the forge. `repos install` uses // one for its read-only configuration preflights (ownership, install -// defaults, proposed safety, effective infrastructure) and discards it -// before the manifest is written; convergence keeps reading current state -// through the original clients. Successful reads and not-found answers are -// cached; any other error is returned uncached. +// defaults, trace signing keys, proposed safety, effective infrastructure) +// and discards it before the manifest is written; convergence keeps +// reading current state through the original clients. Successful reads and +// not-found answers are cached; any other error is returned uncached. func NewPreflightReadCache(clients ForgeClientFactory) ForgeClientFactory { return &preflightReadCache{clients: clients, byForge: make(map[string]*cachingReadClient)} } diff --git a/internal/repos/trace_keys_converge_test.go b/internal/repos/trace_keys_converge_test.go index 32f8bfbc9f..71aabce655 100644 --- a/internal/repos/trace_keys_converge_test.go +++ b/internal/repos/trace_keys_converge_test.go @@ -197,15 +197,13 @@ func requireNoSeed(t *testing.T, reported []string, seed string) { } } -// traceActions returns the actions of the trace key step, as "component +// traceActions returns every action on FULLSEND_TRACE_SIGNING_KEY or +// FULLSEND_TRACE_SIGNING_KEY_ID, orphan reports included, as "component // action detail". func traceActions(result *ConvergeBatchResult) []string { var out []string for _, r := range result.Results { for _, a := range r.Actions { - if a.Action == "orphan" { - continue - } if a.Component == "secret:"+forge.SecretTraceSigningKey || a.Component == "var:"+forge.VarTraceSigningKeyID { out = append(out, a.Component+" "+a.Action+" "+a.Detail) } @@ -300,6 +298,8 @@ func TestTraceKeys_FreshThenReinstall(t *testing.T) { requireNoSeed(t, reported, seed) require.Equal(t, 1, len(result.Results)) assert.True(t, result.Results[0].AlreadyCurrent, "the second run is already current:\n%s", strings.Join(reported, "\n")) + assert.Empty(t, traceActions(result), "the second run reports no trace action, and no orphan "+forge.VarTraceSigningKeyID) + assert.Zero(t, countLines(progress.all(), "Orphan variable "+forge.VarTraceSigningKeyID), "the key ID variable is managed") assert.Zero(t, client.committed(), "the second run commits nothing") assert.Equal(t, 1, traceVarRecords(fc.DeletedVariables), "the second run deletes no variable") assert.Equal(t, 1, len(traceSecretWrites(fc)), "the second run writes no seed") @@ -547,8 +547,9 @@ func TestConverge_TraceKeyRereadComparesPresenceAndValue(t *testing.T) { // The real uninstall keeps the repos.yaml entry, as repos uninstall // --uninstall-only does, and on GitHub the committed .fullsend/config.yaml; -// it deletes the seed. The next install keeps the installation, retains -// the old active key and writes a new key before its commit. +// it deletes the seed and the key ID variable. The next install keeps the +// installation, retains the old active key and writes a new key before its +// commit. func TestTraceKeys_UninstallOnlyThenInstall(t *testing.T) { old := newTraceKey(1) fc, cfg := traceFixture(t, true, "acme/api") @@ -560,6 +561,8 @@ func TestTraceKeys_UninstallOnlyThenInstall(t *testing.T) { require.Len(t, results, 1) require.True(t, results[0].Success, "uninstall: %v", results[0].Error) assert.False(t, fc.Secrets["acme/api/"+forge.SecretTraceSigningKey], "uninstall deletes the seed") + _, kept := keyIDVar(fc) + assert.False(t, kept, "uninstall deletes the key ID variable") progress := &progressLog{} plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) diff --git a/internal/repos/uninstall.go b/internal/repos/uninstall.go index 4b9166c875..27ed11eec5 100644 --- a/internal/repos/uninstall.go +++ b/internal/repos/uninstall.go @@ -13,7 +13,10 @@ import ( "github.com/fullsend-ai/fullsend/internal/scaffold" ) -var uninstallVariables = slices.Concat([]string{forge.PerRepoGuardVar}, requiredVariables, []string{forge.VarGCPRegion, forge.VarReviewClientID}) +// uninstallVariables are the variables uninstall deletes outside GitLab, +// including FULLSEND_TRACE_SIGNING_KEY_ID, which install writes next to the +// trace signing key (ADR 0154). +var uninstallVariables = slices.Concat([]string{forge.PerRepoGuardVar}, requiredVariables, []string{forge.VarGCPRegion, forge.VarReviewClientID, forge.VarTraceSigningKeyID}) // uninstallSecrets deletes every Fullsend-managed inference secret of // every inference.auth method (managedInferenceSecrets), independent of diff --git a/internal/repos/uninstall_test.go b/internal/repos/uninstall_test.go index d22b32cff4..45d1039c29 100644 --- a/internal/repos/uninstall_test.go +++ b/internal/repos/uninstall_test.go @@ -101,8 +101,10 @@ func TestUninstall_InstalledRepo(t *testing.T) { if !r.WorkflowDeleted { t.Error("WorkflowDeleted = false, want true") } - if r.VarsDeleted != 5 { - t.Errorf("VarsDeleted = %d, want 5", r.VarsDeleted) + // 5 managed variables plus FULLSEND_TRACE_SIGNING_KEY_ID, which install + // writes next to the trace signing key. + if r.VarsDeleted != 6 { + t.Errorf("VarsDeleted = %d, want 6", r.VarsDeleted) } // 2 required secrets plus the opt-in FULLSEND_OPENAI_API_KEY, which // uninstall always attempts to delete (idempotent: a 404 for a repo @@ -130,8 +132,8 @@ func TestUninstall_InstalledRepo(t *testing.T) { t.Errorf("thin caller %s was not in deleted files", tcPath) } } - if len(client.DeletedVariables) != 5 { - t.Errorf("deleted %d variables, want 5", len(client.DeletedVariables)) + if len(client.DeletedVariables) != 6 { + t.Errorf("deleted %d variables, want 6", len(client.DeletedVariables)) } if len(client.DeletedSecrets) != 8 { t.Errorf("deleted %d secrets, want 8", len(client.DeletedSecrets)) @@ -1193,19 +1195,28 @@ func TestUninstallSecretsForForge_GitLab_DeletesPrefixedOpenAIKeyOnly(t *testing } // Uninstall deletes the trace signing key on both forges (ADR 0154): a -// torn-down repository keeps no private key. +// torn-down repository keeps no private key. On GitHub, where install +// writes FULLSEND_TRACE_SIGNING_KEY_ID next to the key, uninstall deletes +// that variable too; on GitLab install writes no such variable. func TestUninstall_DeletesTraceSigningKey(t *testing.T) { for _, tc := range []struct { forgeName string client *forge.FakeClient manifest *Manifest + keyID bool }{ - {ForgeGitHub, newInstalledFakeClient("acme/api"), testManifest("acme/api")}, - {ForgeGitLab, newInstalledFakeGitLabClient("acme/api"), testGitLabManifest("acme/api")}, + {ForgeGitHub, newInstalledFakeClient("acme/api"), testManifest("acme/api"), true}, + {ForgeGitLab, newInstalledFakeGitLabClient("acme/api"), testGitLabManifest("acme/api"), false}, } { t.Run(tc.forgeName, func(t *testing.T) { client := tc.client client.Secrets["acme/api/"+forge.SecretTraceSigningKey] = true + if tc.keyID { + setKeyIDVar(client, "acme/api", newTraceKey(1).id()) + } + if got := slices.Contains(UninstallVarsForForge(tc.forgeName), forge.VarTraceSigningKeyID); got != tc.keyID { + t.Errorf("UninstallVarsForForge(%s) includes %s: %t, want %t", tc.forgeName, forge.VarTraceSigningKeyID, got, tc.keyID) + } results, err := Uninstall(context.Background(), UninstallConfig{ Manifest: tc.manifest, @@ -1225,6 +1236,9 @@ func TestUninstall_DeletesTraceSigningKey(t *testing.T) { if client.Secrets["acme/api/"+forge.SecretTraceSigningKey] { t.Errorf("%s still present after uninstall", forge.SecretTraceSigningKey) } + if _, ok := client.VariableValues["acme/api/"+forge.VarTraceSigningKeyID]; ok { + t.Errorf("%s still present after uninstall", forge.VarTraceSigningKeyID) + } }) } } From a7191050b41a8556366daa6bb2a1f502d2ecbf71 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 13 Nov 2026 18:26:22 -0500 Subject: [PATCH 03/12] docs(#9060): document GitHub trace signing key provisioning Document the key lifecycle in the trace context reference, the trace signing keys section and flag in the repos CLI reference, the trace_context config reference, the variable and secret inventories, the glob carve-out and repos.yaml write cases in the guides, and the parity paragraph in the Go contributor guide. GitLab keys, removing a retained key, keys from install flags and delivery to runs are marked planned. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 185 ++++++++++++-- docs/contributing/go-code.md | 11 +- docs/guides/dev/cli-internals.md | 1 + .../migrating-from-github-setup.md | 19 +- docs/guides/getting-started/operations.md | 6 +- .../guides/getting-started/repo-management.md | 15 +- .../infrastructure-reference.md | 18 +- docs/reference/config-reference.md | 26 +- docs/reference/trace-context.md | 238 +++++++++++++++++- 9 files changed, 473 insertions(+), 46 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index 549dd603e7..b19d4eec43 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -234,24 +234,50 @@ With no positional arguments, install converges every repository declared in the Selectors never add repositories. Every selector must match at least one declared repository, and the whole run fails before any manifest or forge write if any one does not, even when other selectors match: `repos install acme/api 'other/*'` fails for `other/*` when only `acme/*` is declared. An unrelated glob is never treated as declared merely because the manifest contains another glob. For a concrete name the error lists every undeclared selector and suggests the entry to add, for example `fullsend repos set 'github.repos["owner/repo"]' '{}'` or `fullsend repos set 'gitlab.repos["group/project"]' '{}'` (a GitLab entry needs `gitlab.url` first). Declare the repository, then re-run. A glob selector is checked against the repositories the declared entries resolve to, so a glob that lists no repository fails with a "matched no manifest entries" error. Live install, `--dry-run` and `repos status` select identically. -A concrete repository named on the command line that a glob entry covers is installed with that glob entry's settings, even when the org listing omits it (for example a fork or an archived repository). No explicit entry is added for it. To give it different settings, declare an explicit entry. +A concrete repository named on the command line that a glob entry covers is +installed with that glob entry's settings, even when the org listing omits it +(for example a fork or an archived repository). Naming it adds no explicit +entry, but install gives it one, copied from the glob, when it writes the +first-install `tracker` default or, on GitHub, the `trace_context` block to +`repos.yaml`. Edits to the glob entry do not apply to a repository that has +its own entry. To give it different settings, declare an explicit entry. Credentials are required only for the forges of the selected repos: a GitLab-only selection does not need `GH_TOKEN`, and a GitHub-only selection does not need `GITLAB_TOKEN`. An unfiltered run still requires credentials for every forge present in the manifest. -Install writes to `repos.yaml` itself in only three cases: the first-install +Install writes to `repos.yaml` itself in only four cases: the first-install `tracker` writeback described above; the conversion of legacy issue-tracking -configuration described below; and, after a first install, the CLI's release -written to `github.fullsend_ref` or `gitlab.fullsend_ref` when that key is -unset. `--dry-run` writes none of them. Install writes the first two together, -after its configuration preflights. It stops before that write when the file -changed after the run loaded it, as when another install that uses the same -file runs at the same time. Run install again once that install has finished. -Install still overwrites a change that lands in the short window between that -check and the write. When the rewritten file would exceed the 1 MB limit that -loading a manifest enforces, install also stops before that write. `--dry-run` -reports the same refusal. To install a larger fleet, split it across several -manifests. Declare each repository in only one of them, including a repository -that a glob covers. +configuration described below; the `trace_context` block of a GitHub +repository's [trace signing keys](#trace-signing-keys); and, after a first +install, the CLI's release written to `github.fullsend_ref` or +`gitlab.fullsend_ref` when that key is unset. `--dry-run` writes none of them. +Install writes the first three together. These checks run before that write, +so a run they stop leaves `repos.yaml` unchanged: + +- the command-line flags, the manifest and the repository selection; +- the existing configuration layers: an undeclared base stops the run, and a + repository that needs adoption is skipped; +- the token's scopes and the sign-off identity; +- a read-only manifest that must record the `tracker` default or a trace key, + and the [trace signing key](#trace-signing-keys) refusals; +- the proposed configuration, against the installed layers and against the + effective infrastructure. + +Install also stops before that write when the file changed after the run +loaded it, as when another install that uses the same file runs at the same +time. Run install again once that install has finished. Install still +overwrites a change that lands in the short window between that check and the +write. When the rewritten file would exceed the 1 MB limit that loading a +manifest enforces, install also stops before that write. `--dry-run` reports +the same refusal. To install a larger fleet, split it across several +manifests. Declare each repository in only one of them, including a +repository that a glob covers. + +Some convergence input checks run only after that write: whether a selected +repository uses each `--openai-api-key`, `--vertex-project`, +`--vertex-wif-provider` and `--jira-*` value given, and the GCP project-number +lookup that derives a repository's WIF provider. A failure there stops the run +after `repos.yaml` recorded any new trace key, so that key's seed is never +written. The next run keeps that key as a retained key. Legacy issue-tracking configuration in managed `config:` blocks (the scalar `tracker: github|gitlab|jira` form and the removed `create_issues` block) is @@ -638,6 +664,111 @@ flag or environment variable supplies them. and `--jira-client-secret` are never written to `repos.yaml`, and the secret values are never logged. +### Trace signing keys + +On GitHub, `repos install` provisions an Ed25519 key pair for signing +trace-context envelopes +([ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)). +No fullsend code reads the signing key yet. For the whole lifecycle, see +[Trace Context Reference — Key lifecycle](../reference/trace-context.md#key-lifecycle). + +- **What install writes.** The installation ID and the public key go in the + repository's `repos.yaml` entry as + [`config.trace_context`](../reference/config-reference.md#trace_context), + and install renders them into the managed `.fullsend/config.yaml`. A + repository covered only by a glob gets its own entry, copied from the glob, + and install's output names the new entry and the glob. Later edits to the + glob entry no longer apply to it, including a glob-level `fullsend_ref` pin, + `kill_switch`, and role or resource restrictions: set such fleet-wide + controls in `github.config`, `defaults.config` or `github.fullsend_ref` + instead of on the glob. A copied entry keeps the values it copied, and they + override those levels, so also delete a copied `fullsend_ref`, `kill_switch`, + `roles` or `allowed_remote_resources` from each copied entry. The private + key, a 32-byte seed in standard base64, goes in the + `FULLSEND_TRACE_SIGNING_KEY` repository secret. Its key ID goes + in the `FULLSEND_TRACE_SIGNING_KEY_ID` repository variable: GitHub never + returns a secret's value, so the variable records which key the secret + holds. Install writes `repos.yaml` before the secret and the variable, and + writes them before it commits the managed configuration. +- **When install writes a key.** A fresh install, one whose fullsend workflow + is not on the default branch yet, gets an installation ID and a key pair. An + existing install whose entry has no `trace_context` gets none from a plain + run: its first run with `--rotate-trace-signing-key` provisions them. On + later runs, install writes no key while the secret exists and the variable + names the active key. When the secret is missing, or the variable is missing + or names a retained key, install writes a new key pair, keeps the + installation ID and moves the previous active key to `retained`. This + recovers an interrupted run, retried with the `repos.yaml` that run wrote, + and a reinstall after `repos uninstall --uninstall-only`. A repository that + install skips, such as one whose `.fullsend/config.yaml` needs adoption, + gets no key. +- **Rotation.** `--rotate-trace-signing-key` writes a new key pair even when + the install is healthy. The previous active key moves to `retained`. Within + an installation, install never removes a retained key. Enrolling a fully + uninstalled repository again replaces the ended installation's block, keys + included (see [`repos uninstall`](#repos-uninstall)). +- **Checks before any write.** Before it writes `repos.yaml` or any key, + install compares each entry with the committed `.fullsend/config.yaml` and + with `FULLSEND_TRACE_SIGNING_KEY_ID`, and stops the run when they contradict + it (see + [When install refuses an entry](../reference/trace-context.md#when-install-refuses-an-entry)). + A `FULLSEND_TRACE_SIGNING_KEY_ID` value that is not 16 lowercase hex + characters also stops the run: delete the variable, then run install again. + Install cannot tell an older copy of `repos.yaml` from the one a run wrote + when that run failed after deleting the variable, at the seed or variable + write (a seed write that failed may still have landed), so keep and commit + the `repos.yaml` such a run wrote, and retry with it. +- **Read-only manifest.** A manifest loaded from an HTTPS URL, read from a + pipe or FIFO, or a local file without write permission cannot record a key. + From such a manifest, a fresh install without `--rotate-trace-signing-key` + goes ahead without keys and says so. A later run with the flag and a + writable manifest provisions them. Any other key write stops the run before + it writes any key. +- **Concurrent installs.** Just before it writes a key, install reads + `FULLSEND_TRACE_SIGNING_KEY_ID` again. If that read fails, or the variable + appeared, disappeared or changed since the run first read it, install writes + no key and makes no commit for that repository, and fails it. GitHub + installs take no lease, so this check misses an install or uninstall that + writes after it. Overlapping runs can then leave the secret holding a key + that the variable does not name, which install cannot see. Run one install + of a repository at a time. `--rotate-trace-signing-key` writes a matching + key. +- **Output.** Install and `--dry-run` name `FULLSEND_TRACE_SIGNING_KEY` and + `FULLSEND_TRACE_SIGNING_KEY_ID`, and show the installation ID, the new key ID + and the reason (fresh install, recovery or rotation) for each new key. They + never show the seed. `--dry-run` writes nothing, and the IDs it shows belong + to keys that it discards. +- **Uninstall and status.** On GitHub, `repos uninstall` deletes + `FULLSEND_TRACE_SIGNING_KEY` and `FULLSEND_TRACE_SIGNING_KEY_ID` (see + [`repos uninstall`](#repos-uninstall)), and `repos status` counts the + variable as managed, not as an orphan. Status does not report a missing + secret or variable. +- **GitLab.** Install writes no key and no `FULLSEND_TRACE_SIGNING_KEY_ID` on + GitLab, even with `--rotate-trace-signing-key`, and prints that it does not + provision them on GitLab yet. +- **Compatibility (breaking).** Fullsend v0.37.0 through v0.55.0 refuse a + `repos.yaml` that contains `trace_context`, and earlier releases cannot read + this manifest format. v0.56.0 accepts it but does not manage + `FULLSEND_TRACE_SIGNING_KEY_ID`: its `repos status` reports the variable as + orphan drift, and its `repos uninstall` leaves it, after which this release + refuses the repository when you declare it again without keys, until you + delete the variable or restore the entry's `trace_context`. Use a release + with this change for every `repos` command on that manifest. Keep and commit + the `repos.yaml` edits install makes: a later install from a copy without + them stops the run, except after a run that failed writing the seed or + `FULLSEND_TRACE_SIGNING_KEY_ID`, when it replaces the key that run may have + written without retaining it. If the copy with those edits is lost, + rebuild the entry's `trace_context` from the block in the + `.fullsend/config.yaml` that the last install committed (in its pull request + until that merges). An entry that already declares `trace_context` by hand + gets a new key pair on its first install with this release, as a recovery: + install replaces `FULLSEND_TRACE_SIGNING_KEY` and moves the declared active + key to `retained`. From a read-only manifest, that run stops. + +```bash +fullsend repos install acme/api --rotate-trace-signing-key +``` + ### Flags Install flags supply only secrets and sensitive provisioning inputs, local vendoring artifacts, and controls for one run. None of their values is written to `repos.yaml`. Persistent settings live in the manifest; the flags that used to set them were removed (see [Removed configuration flags](#removed-configuration-flags-breaking)). @@ -657,6 +788,7 @@ Install flags supply only secrets and sensitive provisioning inputs, local vendo | `--jira-email` | | Optional Jira account email written as `FULLSEND_JIRA_EMAIL` to selected repos whose effective `tracker.jira.poll.enabled` is `true`. If omitted, the existing secret is kept. Command-line only. See [Jira polling](#jira-polling). | | `--jira-client-id` | | Atlassian service account OAuth 2.0 client ID written as `FULLSEND_JIRA_CLIENT_ID`, instead of `--jira-token`, to selected repos whose effective `tracker.jira.poll.enabled` is `true`. If omitted, the existing secret is kept. Command-line only. See [Jira polling](#jira-polling). | | `--jira-client-secret` | | Atlassian service account OAuth 2.0 client secret written as `FULLSEND_JIRA_CLIENT_SECRET`, instead of `--jira-token`. If omitted, the existing secret is kept. Command-line only: never written to `repos.yaml` and never logged. See [Jira polling](#jira-polling). | +| `--rotate-trace-signing-key` | `false` | Generate a new trace signing key pair for each selected GitHub repo: write the private key as `FULLSEND_TRACE_SIGNING_KEY`, record the public key as active in `repos.yaml`, and keep the previous key as retained. On an existing install without `trace_context`, the first rotation provisions the keys. Needs a writable `repos.yaml`. GitLab repos get no key. See [Trace signing keys](#trace-signing-keys). | | `--fullsend-binary` | | Path to a pre-built Linux fullsend binary to upload when vendoring instead of auto-resolving it from the resolved `fullsend_ref`. Valid only when at least one selected repo resolves `vendor: true`; otherwise install fails and points at `fullsend repos set defaults.vendor true` | | `--fullsend-source` | | Path to a fullsend source checkout for vendored content and cross-compilation instead of auto-detecting or fetching from GitHub. Same `vendor: true` requirement as `--fullsend-binary` | | `--gitlab-role-registry` | | Path to administrator GitLab role registry JSON (custom roles: credential references and policy, never secret values). Written as the protected unmasked `FULLSEND_GITLAB_ROLE_REGISTRY` variable. | @@ -1607,7 +1739,7 @@ entry's lines, for example: fullsend repos set --unset 'github.repos["acme/api"]' ``` -File deletions (workflow YAML, `.fullsend/config.yaml`, and GitLab `.gitlab-ci.yml` unmerge) are delivered as a pull request unless `--direct` is set, matching `repos install`. Variable and secret deletions are API-only operations and always happen immediately. For GitLab repos, uninstall also deletes the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches (a missing branch is ignored so older installs still uninstall cleanly) after deleting the fullsend-owned webhook fast-path project webhook (hooks fullsend does not own are left untouched) and revoking its managed Poller-owned pipeline trigger token before any scaffold file is removed, and deleting the wildcard-scoped `FULLSEND_TRIGGER_TOKEN` and `FULLSEND_WEBHOOK_SECRET` variables (a failure there fails uninstall and leaves the manifest entry in place for retry). On the trigger-account route, `FULLSEND_TRIGGER_TOKEN` was already deleted during install and the webhook's trigger is revoked during the trigger-account removal described below. Uninstall also deletes the retired poll-state CI/CD variables, registry/rotation-state variables (`FULLSEND_GITLAB_POLLER_GENERATIONS` is deleted last, only after every Poller account it records was verified and deleted; uninstall retains it when cleanup is incomplete or ambiguous, so the quarantine and retirement obligations it records survive until an administrator has reconciled them), built-in and custom `FULLSEND_GITLAB_*_TOKEN` secrets, and the corresponding `fullsend-poller` / `fullsend-analyst` / `fullsend-coder` / `fullsend-role-*` project access tokens. Uninstall does **not** delete a leftover `FULLSEND_FORGE_TOKEN` secret or revoke a matching `fullsend-bot` project access token — a repository installed before the role-only rollout requires manual cleanup of those. Token revocation is part of uninstall success: if listing or revoking the role project access tokens fails, uninstall fails and the manifest entry is left in place for retry. Reinstall and converge do not revoke credentials that are already distributed. Before deleting anything, uninstall reads the rotation-state variable and fails closed, leaving every variable, secret, and token in place, if it is unreadable or malformed. The rotation-state variable is deleted last, after every other cleanup step succeeds; when it records administrator-supplied service-account exclusions, an exclusions-only document is retained so a later install or uninstall does not treat those accounts as fullsend-managed. When the rotation state records an administrator-supplied credential whose owner was never recorded and the CLI's token client cannot attribute it, uninstall does not guess: it leaves the supplied role's project access token and the whole rotation-state variable in place (reporting this in the cleanup diagnostics) and still removes everything else. +File deletions (workflow YAML, and on GitLab `.fullsend/config.yaml` and the `.gitlab-ci.yml` unmerge) are delivered as a pull request unless `--direct` is set, matching `repos install`. Variable and secret deletions are API-only operations and always happen immediately. For GitLab repos, uninstall also deletes the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches (a missing branch is ignored so older installs still uninstall cleanly) after deleting the fullsend-owned webhook fast-path project webhook (hooks fullsend does not own are left untouched) and revoking its managed Poller-owned pipeline trigger token before any scaffold file is removed, and deleting the wildcard-scoped `FULLSEND_TRIGGER_TOKEN` and `FULLSEND_WEBHOOK_SECRET` variables (a failure there fails uninstall and leaves the manifest entry in place for retry). On the trigger-account route, `FULLSEND_TRIGGER_TOKEN` was already deleted during install and the webhook's trigger is revoked during the trigger-account removal described below. Uninstall also deletes the retired poll-state CI/CD variables, registry/rotation-state variables (`FULLSEND_GITLAB_POLLER_GENERATIONS` is deleted last, only after every Poller account it records was verified and deleted; uninstall retains it when cleanup is incomplete or ambiguous, so the quarantine and retirement obligations it records survive until an administrator has reconciled them), built-in and custom `FULLSEND_GITLAB_*_TOKEN` secrets, and the corresponding `fullsend-poller` / `fullsend-analyst` / `fullsend-coder` / `fullsend-role-*` project access tokens. Uninstall does **not** delete a leftover `FULLSEND_FORGE_TOKEN` secret or revoke a matching `fullsend-bot` project access token — a repository installed before the role-only rollout requires manual cleanup of those. Token revocation is part of uninstall success: if listing or revoking the role project access tokens fails, uninstall fails and the manifest entry is left in place for retry. Reinstall and converge do not revoke credentials that are already distributed. Before deleting anything, uninstall reads the rotation-state variable and fails closed, leaving every variable, secret, and token in place, if it is unreadable or malformed. The rotation-state variable is deleted last, after every other cleanup step succeeds; when it records administrator-supplied service-account exclusions, an exclusions-only document is retained so a later install or uninstall does not treat those accounts as fullsend-managed. When the rotation state records an administrator-supplied credential whose owner was never recorded and the CLI's token client cannot attribute it, uninstall does not guess: it leaves the supplied role's project access token and the whole rotation-state variable in place (reporting this in the cleanup diagnostics) and still removes everything else. GitLab uninstall holds the `FULLSEND_GITLAB_INSTALL_LEASE` project lease for the whole teardown, from webhook removal through the final variable, secret, branch, and token deletions, so no concurrent installer can publish a replacement hook, trigger token, or role credential mid-teardown. It fails closed: if another installer holds the lease or the client cannot take it, uninstall stops before removing anything and the manifest entry is left in place for retry. See [Upgrade compatibility](#upgrade-compatibility) for stranded-lease recovery. @@ -1640,8 +1772,27 @@ Uninstall removes every fullsend-managed inference credential, whatever the repo Uninstall also deletes `FULLSEND_TRACE_SIGNING_KEY`, the trace signing key secret, on both forges -([ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)). -A repository without it still uninstalls. +([ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)), +and on GitHub its `FULLSEND_TRACE_SIGNING_KEY_ID` variable. A repository +without them still uninstalls. On GitHub, uninstall leaves the committed +`.fullsend/config.yaml`, `trace_context` block included, in place. With +`--uninstall-only`, the `repos.yaml` entry keeps its block too, so the next +install keeps the installation ID, moves the old active key to `retained` and +writes a new key pair. A fully uninstalled GitHub repository that you declare +and install again is enrolled as a new installation: from a writable manifest, +install generates a new installation ID and key pair. The uninstall counts as +finished once the repository has no fullsend workflow, +`FULLSEND_TRACE_SIGNING_KEY` or `FULLSEND_TRACE_SIGNING_KEY_ID` left, so merge +the uninstall pull request first. Until then, install refuses the entry. +`--manifest-only` removes the entry and leaves the variable, the secret, the +workflow and the committed block in place. When you declare the repository +again without keys, install refuses the entry until you restore its +`trace_context` or a full uninstall finishes. A repository that a glob covers +stays selected after uninstall removes its own entry, so these refusals stop +any install that selects it, such as an unfiltered run or the glob, and once +a full uninstall finishes, the next such install enrolls it again. Select +other repositories by name, or narrow the glob, to keep it out. See +[Trace Context Reference — Uninstall](../reference/trace-context.md#uninstall). ```bash fullsend repos uninstall acme/old-api diff --git a/docs/contributing/go-code.md b/docs/contributing/go-code.md index 2c8e783f84..459445fad3 100644 --- a/docs/contributing/go-code.md +++ b/docs/contributing/go-code.md @@ -696,7 +696,12 @@ entry, and the symptom only appears on user repositories after `FULLSEND_DISPATCH_SECRET` through `seedGitLabPollState`, not through `managedVarsForForge`. Anything added by a similar out-of-band path needs a cleanup entry too, and needs naming in the parity test, which - cannot discover it. + cannot discover it. On GitHub, `convergeTraceSigningKey` writes + `FULLSEND_TRACE_SIGNING_KEY` and `FULLSEND_TRACE_SIGNING_KEY_ID` + ([ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)) + outside both builders; `uninstallSecrets` and `uninstallVariables` delete + them, and the parity tests name them in `installSideSecretExtras` and + `installSideExtras`. ### The invariant is one-way @@ -704,10 +709,10 @@ Everything install writes must be deleted on uninstall. The reverse is false by design: the uninstall lists deliberately retain names install no longer writes, so repositories installed by earlier versions are still cleaned up — `gitlabRetiredLegacyVars` and the `forge.VarLegacy*` names. -The uninstall lists also carry the trace signing key, +The GitLab uninstall list also carries the trace signing key, `FULLSEND_TRACE_SIGNING_KEY` ([ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)), -which install does not write. +which install does not write on GitLab. Two omissions are also deliberate and documented where they are defined: `gitlabUninstallVars` excludes the legacy shared forge token, and `gitlabUninstallSecrets` excludes the unprefixed `OPENAI_API_KEY`, which diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 61501c2bdf..63cdd063b5 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -71,6 +71,7 @@ fullsend │ │ ├── --jira-email # FULLSEND_JIRA_EMAIL for repos whose tracker.jira.poll.enabled is true (optional; CLI-only) │ │ ├── --jira-client-id # FULLSEND_JIRA_CLIENT_ID instead of --jira-token (CLI-only) │ │ ├── --jira-client-secret # FULLSEND_JIRA_CLIENT_SECRET instead of --jira-token (CLI-only; never logged) +│ │ ├── --rotate-trace-signing-key # New trace signing key pair for GitHub repos; the first rotation gives an existing install its keys │ │ ├── --fullsend-binary # Pre-built binary to vendor (requires a selected repo with vendor: true) │ │ ├── --fullsend-source # Source checkout to vendor from (requires a selected repo with vendor: true) │ │ ├── --gitlab-role-registry # Administrator GitLab role registry JSON diff --git a/docs/guides/getting-started/migrating-from-github-setup.md b/docs/guides/getting-started/migrating-from-github-setup.md index 787b9a1b59..6c610fb204 100644 --- a/docs/guides/getting-started/migrating-from-github-setup.md +++ b/docs/guides/getting-started/migrating-from-github-setup.md @@ -128,7 +128,7 @@ These inputs are never written to `repos.yaml`: |---|---| | Secrets and sensitive provisioning | `--openai-api-key`, `--jira-token`, `--jira-email`, `--jira-client-id`, `--jira-client-secret`, `--vertex-project`, `--vertex-wif-provider`, `--gitlab-role-token role=token` (repeatable), `--gitlab-role-registry`, `--gitlab-token` (or `GITLAB_TOKEN`) | | Local vendoring artifacts | `--fullsend-binary`, `--fullsend-source`. Valid only when a selected repository resolves `vendor: true`; otherwise install fails and points at `fullsend repos set defaults.vendor true` | -| One-run controls | `-f` / `--manifest`, `--dry-run`, `--direct`, `--concurrency`, `--force`, `--reactivate-schedules`, `--rotate-gitlab-roles`, `--rotate-gitlab-role`, `--rotate-gitlab-trigger-token`, `--rotate-gitlab-trigger-account` | +| One-run controls | `-f` / `--manifest`, `--dry-run`, `--direct`, `--concurrency`, `--force`, `--reactivate-schedules`, `--rotate-gitlab-roles`, `--rotate-gitlab-role`, `--rotate-gitlab-trigger-token`, `--rotate-gitlab-trigger-account`, `--rotate-trace-signing-key` | `--vertex-project` and `--vertex-wif-provider` are optional when the effective configuration declares `inference.project` and @@ -205,8 +205,11 @@ github: `fullsend repos install acme/web` installs `acme/web` with the glob's settings, even when the org listing omits it (for example a fork or an -archived repository), and adds no explicit entry. To give one repository -different settings, add an explicit entry for it. +archived repository). Naming it adds no explicit entry, but install gives it +one, copied from the glob, when it writes the first-install `tracker` default +or, on GitHub, the `trace_context` block to `repos.yaml`. Edits to the glob +entry do not apply to a repository that has its own entry. To give one +repository different settings, add an explicit entry for it. ### Infrastructure values @@ -461,14 +464,20 @@ cannot be read back to compare, so they are always refreshed from the supplied values. When neither supplies a project, the existing secrets are reused. -Install writes to `repos.yaml` itself only in two cases, both of which -predate this change: +Install writes to `repos.yaml` itself only in these cases: - On a first install with no preset and no `tracker` declaration, it records `config.tracker.github.allowed_targets.repos: [fullsend-ai/fullsend, fullsend-ai/agents]` on a GitHub repository's entry. For GitLab it records the explicit empty policy `config.tracker.gitlab.allowed_targets: {}`. For a repository covered only by a glob, this adds an explicit entry. +- When it converts legacy `tracker` or `create_issues` configuration, it + writes the converted manifest (see + [Permit agent improvement proposals on existing installations](#permit-agent-improvement-proposals-on-existing-installations)). +- When it generates a trace signing key pair for a GitHub repository, it + records `config.trace_context` in the repository's entry. For a repository + covered only by a glob, this adds an explicit entry, copied from the glob. + See [Trace signing keys](../../cli/repos.md#trace-signing-keys). - After a first install, it writes the CLI's release to `github.fullsend_ref` or `gitlab.fullsend_ref` when that key is unset. diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index f981ac1202..b04efb5822 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -36,6 +36,7 @@ fullsend github set "$OWNER/$REPO" FULLSEND_GCP_REGION global | `FULLSEND_OPENAI_IDENTITY_PROVIDER_ID` | Repo variable | OpenAI WIF identity-provider ID | `idp-example` | | `FULLSEND_OPENAI_SERVICE_ACCOUNT_ID` | Repo variable | OpenAI WIF service-account ID | `sa-example` | | `FULLSEND_REVIEW_CLIENT_ID` | Repo variable | OAuth client ID of the review agent's GitHub App (best-effort, auto-set by installer) | `Iv23li1nIorNLIQy6NWK` | +| `FULLSEND_TRACE_SIGNING_KEY_ID` | Repo variable | Key ID of the last seed `repos install` confirmed writing to `FULLSEND_TRACE_SIGNING_KEY`: 16 lowercase hex characters. `repos install` deletes it before it writes a new key and sets it once the write succeeds. Not secret; do not set it by hand. `repos uninstall` deletes it | `0123456789abcdef` | | `FULLSEND_GCP_PROJECT_ID` | Repo secret | GCP project ID where Agent Platform is enabled | `my-gcp-project` | | `FULLSEND_GCP_WIF_PROVIDER` | Repo secret | Full WIF provider resource name for OIDC authentication | `projects/123456789/locations/global/...` | | `FULLSEND_OPENAI_API_KEY` | Repo secret | OpenAI API key for repos whose `inference.auth` is `openai-api-key`, written by `repos install --openai-api-key` (exported as `OPENAI_API_KEY`; unused when the WIF trio is set) | `sk-...` | @@ -43,9 +44,12 @@ fullsend github set "$OWNER/$REPO" FULLSEND_GCP_REGION global | `FULLSEND_JIRA_TOKEN` | Repo secret | Jira API token for polling and Jira-originated agent status updates when effective `tracker.jira.poll.enabled` is `true`, written by `repos install --jira-token` (required on the first install unless client credentials are supplied; an omitted flag keeps the existing secret; `repos uninstall` deletes it) | (Jira API token) | | `FULLSEND_JIRA_EMAIL` | Repo secret | Optional Jira account email for the same poller and agent status calls, written by `repos install --jira-email`; an omitted flag keeps the existing secret; `repos uninstall` deletes it | `poller@example.com` | | `FULLSEND_JIRA_CLIENT_ID` / `FULLSEND_JIRA_CLIENT_SECRET` | Repo secret | A service account's OAuth 2.0 credential, used instead of `FULLSEND_JIRA_TOKEN` (never both). GitHub poll and Jira-originated dispatch workflows forward them to the Jira client; `repos install` writes them on GitHub and GitLab. `repos uninstall` deletes them | (OAuth client credentials) | -| `FULLSEND_TRACE_SIGNING_KEY` | Repo secret | Reserved for the trace-context signing key ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)). Fullsend does not provision it yet. `fullsend run` keeps it from harnesses. `repos uninstall` deletes it | — | +| `FULLSEND_TRACE_SIGNING_KEY` | Repo secret | Trace-context signing key ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): standard base64 of a 32-byte Ed25519 seed, generated by `repos install`, which records its public key in `repos.yaml` as `config.trace_context`. [Trace signing keys](../../cli/repos.md#trace-signing-keys) lists when install writes it. Nothing reads it yet. `fullsend run` keeps it from harnesses. `repos uninstall` deletes it | (generated) | | `FULLSEND_GITHUB_RUNNER_SECRETS` | Repo or org secret (optional) | JSON object of name → value for host-side scripts, read through each harness's `env.runner`. Set with `gh secret set`, not `fullsend github set`; see [Pass secrets to host-side scripts](../user/bring-your-own-agent.md#pass-secrets-to-host-side-scripts-github) | `{"JIRA_API_TOKEN":"..."}` | +> **Planned:** delivery of `FULLSEND_TRACE_SIGNING_KEY` to runs +> ([#9060](https://github.com/fullsend-ai/fullsend/issues/9060)). + Repositories selecting `inference.auth: openai-wif` need no inference secrets unless Vertex sub-agents require GCP credentials. See [OpenAI Workload Identity](../infrastructure/openai-workload-identity.md) for identifier sources and precedence. These three WIF variables are user-owned; diff --git a/docs/guides/getting-started/repo-management.md b/docs/guides/getting-started/repo-management.md index 1857dcb705..a119b84de4 100644 --- a/docs/guides/getting-started/repo-management.md +++ b/docs/guides/getting-started/repo-management.md @@ -498,7 +498,11 @@ When the manifest is read-only (an HTTPS URL, a pipe or FIFO such as `<(cmd)`, or a local file without write permission), install fails before attempting any manifest write and prints the exact entry to add to its source, including for a glob-covered repository whose first-install `tracker` default needs an explicit -entry. `--dry-run`, live install and `repos status` agree. +entry. `--dry-run`, live install and `repos status` agree. Trace signing keys +follow their own rule on GitHub: from such a manifest, a fresh install without +`--rotate-trace-signing-key` goes ahead without keys and says so, and any +other install that must record a key stops the run before it writes one (see +[Trace signing keys](../../cli/repos.md#trace-signing-keys)). ```bash fullsend repos status -f repos.yaml --json # whole-file managed drift @@ -871,7 +875,14 @@ fullsend repos install acme/new-api acme/new-web --dry-run To cover every repository in an org, declare a glob entry such as `fullsend repos set 'github.repos["acme/*"]' '{}'`. Naming a concrete repository the glob covers (`fullsend repos install acme/new-api`) -installs it with the glob's settings without adding an explicit entry. +installs it with the glob's settings. Naming it adds no explicit entry. Any +install, whether it names the repository, passes `"acme/*"` or selects the +whole manifest, gives a glob-covered repository its own entry, copied from the +glob, when it writes that repository's first-install `tracker` default or, on +GitHub, its `trace_context` block +([Trace signing keys](../../cli/repos.md#trace-signing-keys)) to `repos.yaml`. +Edits to the glob entry apply only to repositories that have no entry of their +own. Per-repo settings live on the entry, never in install flags: `fullsend_ref`, `mint_url`, `app_set`, `inference.auth`, `vendor`, diff --git a/docs/guides/infrastructure/infrastructure-reference.md b/docs/guides/infrastructure/infrastructure-reference.md index 512205166e..5ae13f6861 100644 --- a/docs/guides/infrastructure/infrastructure-reference.md +++ b/docs/guides/infrastructure/infrastructure-reference.md @@ -348,15 +348,21 @@ Secrets and variables are deployed on the target repository. not by `github setup`) - `FULLSEND_JIRA_TOKEN`, `FULLSEND_JIRA_EMAIL` — Jira API token and optional account email for repos whose effective `tracker.jira.poll.enabled` is `true`, used by the poller and Jira-originated agent status updates (written by `repos install --jira-token` / `--jira-email`; an omitted flag keeps the existing secret; deleted by `repos uninstall`; not set by `github setup`) - `FULLSEND_JIRA_CLIENT_ID`, `FULLSEND_JIRA_CLIENT_SECRET` — a service account's OAuth 2.0 credential, an alternative to `FULLSEND_JIRA_TOKEN` (never both). GitHub poll and Jira-originated dispatch workflows forward them to the Jira client, and `repos install` writes them on GitHub and GitLab; `repos uninstall` deletes them -- `FULLSEND_TRACE_SIGNING_KEY` — reserved for the trace-context signing key - ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)). - Fullsend does not provision it yet. `fullsend run` keeps it from harnesses. - `repos uninstall` deletes it. +- `FULLSEND_TRACE_SIGNING_KEY` — trace-context signing key + ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): + standard base64 of a 32-byte Ed25519 seed, generated by `repos install`, + which records its public key in `repos.yaml` as `config.trace_context` + ([when install writes it](../../cli/repos.md#trace-signing-keys)). Nothing + reads it yet. `fullsend run` keeps it from harnesses. Deleted by + `repos uninstall`; not set by `github setup`. - `FULLSEND_GITHUB_RUNNER_SECRETS` — optional, set by you: a JSON object of name → literal value for host-side scripts, resolved through each harness's `env.runner` ([setup](../user/bring-your-own-agent.md#pass-secrets-to-host-side-scripts-github)) +> **Planned:** delivery of `FULLSEND_TRACE_SIGNING_KEY` to runs +> ([#9060](https://github.com/fullsend-ai/fullsend/issues/9060)). + Repos whose `inference.auth` is `openai-wif` need no fullsend-managed inference secret: they authenticate with the user-managed `FULLSEND_OPENAI_*` identifier variables or `inference.openai` configuration, and the GCP secrets above are written only when Vertex sub-agents are configured. **Target repo variables:** @@ -364,6 +370,10 @@ Repos whose `inference.auth` is `openai-wif` need no fullsend-managed inference - `FULLSEND_GCP_REGION` (value drift is detected and repaired by convergence) - `FULLSEND_REVIEW_CLIENT_ID` — OAuth client ID of the review agent's GitHub App (best-effort, conditional on successful lookup) - `FULLSEND_APP_SET` — GitHub App set prefix (apps named `{app-set}-{role}`); auto-set by the installer and repaired on convergence +- `FULLSEND_TRACE_SIGNING_KEY_ID` — key ID of the last seed `repos install` + confirmed writing to `FULLSEND_TRACE_SIGNING_KEY`. Install deletes it before + it writes a new key and sets it once the write succeeds. Not secret. Deleted + by `repos uninstall` #### GitLab diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 674acec46a..f8ac6d6a64 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -1022,24 +1022,30 @@ The repository's trace-context keys ([ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): its installation ID, the public keys that verify its trace-context envelopes, and the name of the secret that holds its private signing key. Every value in -the block is public. No fullsend command generates these keys or creates the -secret, and nothing signs or verifies an envelope with them; the -[Trace Context Reference](trace-context.md#implementation-scope) lists what is -implemented. +the block is public. `fullsend repos install` generates the keys of GitHub +repositories (see +[Trace Context Reference — Key lifecycle](trace-context.md#key-lifecycle)). +Nothing signs or verifies an envelope with them yet. - **`installation_id`** — Identifies the repository's key set: exactly 32 - lowercase hex characters (128 bits), not all zero. + lowercase hex characters (128 bits), not all zero. Install keeps it through + recovery, rotation and reinstall while the `repos.yaml` entry keeps its + `trace_context`; a fully uninstalled repository declared again without it + starts a new installation. - **`signing_key.secret`** — The secret that holds the private signing key. It must be exactly `FULLSEND_TRACE_SIGNING_KEY`. The key itself never appears in configuration. - **`verification_keys.active`** — The public key of the current signing key: standard base64, with padding, of a 32-byte Ed25519 public key. - **`verification_keys.retained`** — Optional. Earlier public keys, in the same - form, so that envelopes signed with their private keys still verify. - -A concrete repository entry in `repos.yaml` declares the block as -`config.trace_context`, and `fullsend repos install` renders it into the managed -`.fullsend/config.yaml`. Only a concrete repository entry may declare it: + form, so that envelopes signed with their private keys still verify. Within + an installation, install never removes one; enrolling a fully uninstalled + repository again replaces the whole block. + +On GitHub, `fullsend repos install` records the block in the repository's +concrete `repos.yaml` entry as `config.trace_context`. Install renders the +block into the managed `.fullsend/config.yaml`. Commit the `repos.yaml` +changes install makes. Only a concrete repository entry may declare it: manifest validation rejects it in `defaults.config`, `github.config`, `gitlab.config` and glob entries. `repos install` also rejects a configuration preset or an existing `.fullsend/config.base.yaml` that contains it, and diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index cce595ecd2..9bf223b125 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -3,7 +3,8 @@ The [trace-context v1 specification](../normative/trace-context/v1/README.md) defines the identity, fallback, wire format, admission, and compatibility contract for [ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). -This page covers the Go API and adapter integration. +This page covers the Go API, adapter integration, and the signing-key +lifecycle. ## Implementation scope @@ -23,14 +24,243 @@ The signing key's name, `FULLSEND_TRACE_SIGNING_KEY`, is reserved. `fullsend lock` gives the same report when it composes that harness. Fullsend's GitLab poll, dispatcher and agent jobs unset it on the first line of their `before_script`. `fullsend repos uninstall` deletes it. -Carrier publication, key provisioning, production creation activation, -runtime admission wiring, and scenario collection remain later delivery -slices. +`fullsend repos install` provisions the signing keys of GitHub repositories +(see [Key lifecycle](#key-lifecycle) for when). Key provisioning on GitLab, the +install flags through which the behaviour-test suite supplies its own keys, +delivery of the signing key to runs, carrier publication, production creation +activation, runtime admission wiring, and scenario collection are not +implemented yet. The package must stay importable from public behaviour-test code: it must not depend on `internal/cli`, `internal/repos`, `internal/layers`, or the nested mintcore module. +## Key lifecycle + +[`fullsend repos install`](../cli/repos.md#trace-signing-keys) creates and +maintains the signing keys of GitHub repositories. No fullsend code reads +the signing key yet, nothing signs or publishes trace-context carriers, and no +workflow passes the secret to a job. Until then, `fullsend run` only validates +the [`trace_context`](config-reference.md#trace_context) block. On GitLab, +install writes no key and no `FULLSEND_TRACE_SIGNING_KEY_ID`, even with +`--rotate-trace-signing-key`, and prints that it does not provision them on +GitLab yet. + +> **Planned:** keys for GitLab repositories, removing a retained key, keys that +> the behaviour-test suite supplies through install flags, and delivery of the +> signing key to runs +> ([#9060](https://github.com/fullsend-ai/fullsend/issues/9060)). + +### Installation ID and key pair + +Each repository with keys has its own installation ID: 16 random bytes, +written as 32 lowercase hex characters. Install generates it with the +repository's first key pair. Recovery, rotation and a reinstall after +`--uninstall-only` keep it. Install starts a new installation only when the +repository's `repos.yaml` entry has no `trace_context` block, and either its +committed `.fullsend/config.yaml` has none or the repository was fully +uninstalled (see [Uninstall](#uninstall)). + +The key pair is an Ed25519 pair. Install keeps three records of it: + +- **The private key**, as its 32-byte seed in standard base64, in the + `FULLSEND_TRACE_SIGNING_KEY` repository secret. +- **The public key and the installation ID**, in the `trace_context` block of + the repository's `repos.yaml` entry. Install renders the block into the + managed `.fullsend/config.yaml`. +- **The key ID of the last seed that install confirmed writing**, in the + `FULLSEND_TRACE_SIGNING_KEY_ID` repository variable. A key ID is the first + 8 bytes of the SHA-256 hash of the public key, written as 16 lowercase hex + characters. Envelopes carry the same bytes, so the value is not secret. + GitHub never returns a secret's value, so the variable records which key + the secret holds. Nothing at run time uses it. + +A fresh install, one with no fullsend workflow on the default branch yet, gets +keys. An existing install whose entry has no `trace_context` gets none from a +plain run: its first run with `--rotate-trace-signing-key` provisions them. A +fresh install from a manifest that install cannot write, such as an HTTPS URL, +gets no keys. Install prints that they were not provisioned, and a later run +with `--rotate-trace-signing-key` and a writable manifest provisions them. With +`--rotate-trace-signing-key`, such a fresh install stops the run before it +writes any key. + +### Writes and recovery + +Install writes a new key in this order: + +1. It records the new public key as `active` in `repos.yaml` and moves the + previous active key, if any, to `retained`. When another install that uses + the same file changed it after this run loaded it, install stops before + writing it. +2. It reads `FULLSEND_TRACE_SIGNING_KEY_ID` again. If the read fails, or the + variable appeared, disappeared or changed since the run first read it, as + when another install or uninstall of the repository ran at the same time, + install writes no key, skips the commit and fails that repository. Run + install again once the other run has finished; after another install, use + the `repos.yaml` that install wrote. +3. It deletes `FULLSEND_TRACE_SIGNING_KEY_ID`. +4. It writes the seed to `FULLSEND_TRACE_SIGNING_KEY`. +5. It sets `FULLSEND_TRACE_SIGNING_KEY_ID` to the new key ID. +6. It commits the managed `.fullsend/config.yaml`, directly or in the install + pull request. + +Each step runs only after the one before it succeeds, and a failure in steps +2 to 5 stops the repository before step 6. So the variable never names a key +whose seed the secret no longer holds, apart from overlapping installs (see +below). A failure in step 2 or 3 leaves it as it was or absent, and a failure +in step 4 or 5 leaves it absent unless the failed step 5 write still reached +GitHub. + +An install is healthy when the secret exists and the variable names the +active key. Install then writes no key unless you pass +`--rotate-trace-signing-key`. When the variable is missing or names a retained +key, the secret may not hold the active key. In that case, and when the secret +is missing, the next plain `repos install` generates a new key through the +same steps and keeps the installation ID. From a read-only manifest, that run +stops before it writes any key. + +Unless another install of the repository wrote a key after the run started +(see step 2), a run that stopped at any step converges on a plain retry with +the `repos.yaml` it wrote. That retry keeps every trusted key: a key that the +stopped run recorded but did not confirm writing moves to `retained`. Keep and +commit that `repos.yaml` even though the run failed: after a run that stopped +at step 4 or 5, a retry from an older copy writes a new key and drops the one +the stopped run may have written, and install cannot tell (see +[When install refuses an entry](#when-install-refuses-an-entry)). A seed write +that failed may still have landed, for example after a timeout. + +GitHub installs take no lease, so step 2 misses an install or uninstall that +writes after it. Two overlapping installs can leave the secret holding a key +that the variable does not name, and install cannot see that. Run one install +of a repository at a time. From a writable manifest, this command writes a +matching key: + +```bash +fullsend repos install --rotate-trace-signing-key +``` + +Commit the changes install makes to `repos.yaml`: install renders +`.fullsend/config.yaml` from it, and the committed copy changes only when the +install commit lands. + +### Rotation + +`fullsend repos install --rotate-trace-signing-key` generates a new key pair. +The previous active key moves to `retained`, so envelopes it signed still +verify. Envelopes carry no timestamp, so a retained key stays trusted. Within +an installation, install never removes a retained key. Enrolling a fully +uninstalled repository again replaces the ended installation's block, keys +included (see [Uninstall](#uninstall)). + +### When install refuses an entry + +Install replaces the managed `.fullsend/config.yaml` with what `repos.yaml` +declares, so an older copy of `repos.yaml` could drop keys that a later run +added. Before it writes `repos.yaml` or any key, install compares each +selected repository's entry with the committed `.fullsend/config.yaml` and +with `FULLSEND_TRACE_SIGNING_KEY_ID`. It stops the run when: + +- the committed installation ID differs from the entry's, and a fullsend + workflow is on the default branch; +- a committed active or retained key is missing from the entry, unless the + committed block belongs to an ended installation; +- the committed configuration has a `trace_context` block and the entry has + none, unless the repository was fully uninstalled (see + [Uninstall](#uninstall)); +- `FULLSEND_TRACE_SIGNING_KEY_ID` exists while the entry has no + `trace_context`, or names a key that the entry does not list; +- another `repos.yaml` entry uses the same installation ID. + +These usually mean that the last install wrote a different `repos.yaml`. Run +install with the `repos.yaml` the last install wrote, or restore the entry's +`trace_context` from it. + +Install cannot detect an older copy after a run that failed after deleting +`FULLSEND_TRACE_SIGNING_KEY_ID` (step 3), at the seed write (step 4) or the +variable write (step 5). A seed write that failed may still have landed, for +example after a timeout. The variable is absent and the committed block is +unchanged, so none of these checks fires, and a retry from the older copy +replaces a seed that landed without retaining its key. That run's error says +to keep and commit the `repos.yaml` it wrote; retry with it. + +A committed block belongs to an ended installation when its installation ID +differs from the entry's and the default branch has no fullsend workflow, for +example before the commit of a re-enrollment lands (see +[Uninstall](#uninstall)). Install then skips the checks of that block's +installation ID and keys. It still checks `FULLSEND_TRACE_SIGNING_KEY_ID` and +the other entries' installation IDs. + +The error names the repository and, for a key missing from the entry, its key +ID. It never shows a key, an installation ID or the value of +`FULLSEND_TRACE_SIGNING_KEY_ID`. + +A merged change to the committed `.fullsend/config.yaml` can also add a key +that no install recorded. If you did not add the key that the error names, +revert that change, and do not add the key to `repos.yaml`: that would make it +trusted. + +A `FULLSEND_TRACE_SIGNING_KEY_ID` value that is not 16 lowercase hex +characters also stops the run before it writes `repos.yaml` or any key. The +error names the repository and the variable and says to delete the variable. +It never shows the value. Delete the variable, then run install again: + +```bash +gh variable delete FULLSEND_TRACE_SIGNING_KEY_ID --repo OWNER/REPO +fullsend repos install OWNER/REPO +``` + +Install also stops the run, before it writes any key, when it needs to record +a key and the manifest is read-only: an HTTPS URL, a pipe or FIFO, or a local +file without write permission. Run install from a writable local copy of the +manifest instead. A fresh install without `--rotate-trace-signing-key` is the +exception, including the re-enrollment of a fully uninstalled repository: it +goes ahead without keys (see +[Installation ID and key pair](#installation-id-and-key-pair) and +[Uninstall](#uninstall)). + +### Uninstall + +On GitHub, uninstall deletes `FULLSEND_TRACE_SIGNING_KEY` and +`FULLSEND_TRACE_SIGNING_KEY_ID` and leaves `.fullsend/config.yaml`, +`trace_context` block included, in place. With `--uninstall-only`, the +`repos.yaml` entry keeps its `trace_context` block. The next install then +keeps the installation ID, moves the old active key to `retained`, and writes +a new key pair. `--manifest-only` removes the entry and leaves the variable, +the secret, the workflow and the committed block in place. When you declare +the repository again without keys, install refuses the entry until you +restore its `trace_context` or a full uninstall finishes. + +A full uninstall also removes the repository's `repos.yaml` entry. A fully +uninstalled repository that you declare and install again is enrolled again +as a new installation. Install generates a new installation ID and key pair, +and replaces the `trace_context` block that GitHub leaves in the committed +`.fullsend/config.yaml`. It prints the ended installation's ID and the key IDs +that it stops trusting. The repository counts as fully uninstalled once it has +no fullsend workflow, `FULLSEND_TRACE_SIGNING_KEY` or +`FULLSEND_TRACE_SIGNING_KEY_ID` left. Until then, for example while the +uninstall pull request is open, install refuses the entry. To keep the +installation instead, restore the entry's `trace_context` from the +`repos.yaml` the last install wrote. + +A repository that a glob covers stays selected after uninstall removes its own +entry, so these refusals stop any install that selects it, such as an +unfiltered run or the glob, and once a full uninstall finishes, the next such +install enrolls it again. Select other repositories by name, or narrow the +glob, to keep it out. + +Install replaces the ended block in the commit that delivers its scaffold, by +default through the install pull request. Until that change lands, the +default branch has no fullsend workflow and keeps the ended block. Later runs +treat that block as the ended installation's: they print the ended +installation again, keep the entry's installation, and recover a missing seed +or `FULLSEND_TRACE_SIGNING_KEY_ID` as usual. + +From a read-only manifest, install enrolls a fully uninstalled repository +again without keys, as for any fresh install (see +[Installation ID and key pair](#installation-id-and-key-pair)). It still +prints the ended installation, and its commit removes the ended block instead +of replacing it. + ## Adapter integration [`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/main/internal/tracker/jira_client.go) From 2fbfafc5f37b29a3007c2f43e967e395ae2245fc Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 13 Nov 2026 18:28:49 -0500 Subject: [PATCH 04/12] docs(adr): note that repos install provisions GitHub signing keys The ADR 0154 status note now says that repos install provisions the signing keys of GitHub repositories; the rest stays pending. Signed-off-by: Dharit Shah --- ...4-correlate-work-item-and-behaviour-scenario-traces.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md index 2301036c05..35033a99cd 100644 --- a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md +++ b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md @@ -22,8 +22,12 @@ Accepted This records the chosen topology. The identity, fallback, envelope, and admission foundation is implemented; the [trace-context v1 specification](../normative/trace-context/v1/README.md) -defines its contract. Carrier publication, key provisioning, and runtime -integration are pending. +defines its contract. `fullsend repos install` provisions the signing keys of +GitHub repositories (see the +[key lifecycle](../reference/trace-context.md#key-lifecycle)). Carrier +publication, key provisioning on GitLab, the flags through which the +behaviour-test suite supplies its own keys, delivery of the signing key to +runs, and runtime integration are pending. ## Context From b33a2ecca264e4d69656c7b6c1450a5c2dfd61e7 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 12:19:51 -0500 Subject: [PATCH 05/12] refactor(repos): guard a nil trace-key progress and make TraceKeyPlan.Reason a string EnsureTraceSigningKeys replaces a nil progress with a no-op, as the other exported repos functions that take a ProgressFunc do, so a caller without one no longer panics at the first line it reports. repos install always passes one. TraceKeyPlan.Reason is a plain string, so the exported field no longer has an unexported type. The reason values and the progress output are unchanged. Signed-off-by: Dharit Shah --- internal/repos/trace_keys.go | 17 +++++++++-------- internal/repos/trace_keys_test.go | 13 ++++++++++++- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/internal/repos/trace_keys.go b/internal/repos/trace_keys.go index e7c32d7a82..cea8bde177 100644 --- a/internal/repos/trace_keys.go +++ b/internal/repos/trace_keys.go @@ -32,13 +32,11 @@ type TraceKeysConfig struct { Rotate bool } -// traceKeyReason is why EnsureTraceSigningKeys plans a key. -type traceKeyReason string - +// TraceKeyPlan.Reason values. const ( - reasonFreshInstall traceKeyReason = "fresh install" - reasonRecovery traceKeyReason = "recovery" - reasonRotation traceKeyReason = "rotation" + reasonFreshInstall = "fresh install" + reasonRecovery = "recovery" + reasonRotation = "rotation" ) // TraceKeyPlan is one repository's pending trace-key write. Key holds the @@ -49,7 +47,7 @@ type TraceKeyPlan struct { Key tracecontext.SigningKey // Reason is why the key is planned: a fresh install, a recovery or a // rotation. - Reason traceKeyReason + Reason string KeyIDVar string KeyIDVarExists bool } @@ -103,6 +101,9 @@ var ( // RequireInferenceAuth are skipped. Progress names installation and key IDs, // and the glob a new entry was copied from, never the seed. func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients ForgeClientFactory, progress ProgressFunc) (map[string]*TraceKeyPlan, error) { + if progress == nil { + progress = func(_, _, _ string) {} + } m := cfg.Manifest selected, err := selectManifestRepos(ctx, m, clients, cfg.RepoFilter) if err != nil { @@ -280,7 +281,7 @@ type traceRepo struct { manifest *traceKeySet installed *traceKeySet // reason is why a key is planned; "" plans none. - reason traceKeyReason + reason string // readOnlySkip reports a fresh install that goes ahead without keys // because the manifest is read-only. readOnlySkip bool diff --git a/internal/repos/trace_keys_test.go b/internal/repos/trace_keys_test.go index 05c53fa650..2d8bd6605f 100644 --- a/internal/repos/trace_keys_test.go +++ b/internal/repos/trace_keys_test.go @@ -258,6 +258,17 @@ func TestEnsureTraceSigningKeys_FreshInstall(t *testing.T) { } } +// A nil progress is a no-op, as in the other exported functions that take +// a ProgressFunc: a fresh install still gets its plan. +func TestEnsureTraceSigningKeys_NilProgress(t *testing.T) { + fc, cfg := traceFixture(t, false, "acme/api") + + plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + newTestClientFactory(fc), nil) + require.NoError(t, err) + assert.Equal(t, []string{"acme/api"}, planNames(plans)) +} + // A repository that only a glob covers gets its own GitHub entry, copied // from the first glob entry that covers it, and progress names that entry // and that glob, since later edits to the glob no longer reach it; the globs @@ -425,7 +436,7 @@ func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { // installed puts a fullsend workflow on the default branch. installed bool rotate bool - reason traceKeyReason + reason string // keyIDVar is the variable's value in the fixture; "" is absent. keyIDVar string setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) From 25b3ac7e919d8e23d81d57f6ddc72c5d194b04b2 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 12:35:42 -0500 Subject: [PATCH 06/12] fix(repos): treat a repos.yaml on a read-only file system as read-only ManifestReadOnly counted a failed open for writing as read-only only when it was a permission error. A repos.yaml on a read-only file system, such as a Docker :ro bind mount or a ConfigMap volume, keeps its write bits and fails that open with EROFS, so it counted as writable. A fresh GitHub install, which records its trace keys in repos.yaml, then stopped at that write and converged nothing; repos uninstall tore the repository down before its manifest write failed; and repos set failed on its temporary file. isWriteDenied counts EROFS along with a permission error, so such a file takes the read-only path of a file without write permission: install goes ahead without trace keys and names the run that adds them, uninstall refuses before any teardown, and repos set reports the read-only manifest. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 14 +++++----- .../guides/getting-started/repo-management.md | 7 ++--- internal/repos/config_layers_test.go | 26 +++++++++++++++++++ internal/repos/managed_config_writeback.go | 11 ++++++-- 4 files changed, 46 insertions(+), 12 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index b19d4eec43..452cfd742d 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -1721,12 +1721,12 @@ Requires a GitHub token via `GH_TOKEN`, `GITHUB_TOKEN`, or `gh auth token`. For Tear down fullsend from the specified repos and remove them from the manifest. By default, the command tears down first (opening a PR to remove workflow files, then deleting variables and secrets via the API), then removes successfully-torn-down repos from the manifest. Partial failures leave the manifest entry intact so the user can retry. A manifest loaded from an HTTPS URL, read from a pipe or FIFO (as `-f <(cmd)` -gives), or a local file without write permission, is read-only, so uninstall -cannot remove entries from it. Uninstall refuses such a manifest before it -tears anything down, `--manifest-only` refuses it too, and `--dry-run` reports -the same refusal. To uninstall from one, run with `--uninstall-only`, which -tears down without editing the manifest, then remove each torn-down entry from -its source. +gives), or a local file without write permission or on a read-only file +system, is read-only, so uninstall cannot remove entries from it. Uninstall +refuses such a manifest before it tears anything down, `--manifest-only` +refuses it too, and `--dry-run` reports the same refusal. To uninstall from +one, run with `--uninstall-only`, which tears down without editing the +manifest, then remove each torn-down entry from its source. Uninstall rewrites the whole `repos.yaml` with its own formatting. When the rewritten file would exceed the 1 MB limit that loading a manifest enforces, @@ -1844,7 +1844,7 @@ fullsend repos set --unset Paths are resolved against the manifest schema, so every field the manifest accepts can be set and there is no separate list of keys. After each edit the whole resulting manifest is validated with the same checks `repos install` uses. A rejected edit leaves the file byte-identical. A successful edit changes only the edited lines and keeps unrelated values, comments, blank lines, and ordering. If the manifest does not exist, `repos set` creates it with `version: 1`. Missing optional parent mappings (for example `defaults.config`) are created as needed. -A manifest loaded from an HTTPS URL, read from a pipe or FIFO (as `-f <(cmd)` gives), or a local file without write permission, is read-only: `repos set` reports `manifest is read-only; apply the equivalent edit to its source, then re-run` and writes nothing. +A manifest loaded from an HTTPS URL, read from a pipe or FIFO (as `-f <(cmd)` gives), or a local file without write permission or on a read-only file system, is read-only: `repos set` reports `manifest is read-only; apply the equivalent edit to its source, then re-run` and writes nothing. ### Path syntax diff --git a/docs/guides/getting-started/repo-management.md b/docs/guides/getting-started/repo-management.md index a119b84de4..4005b09edf 100644 --- a/docs/guides/getting-started/repo-management.md +++ b/docs/guides/getting-started/repo-management.md @@ -495,9 +495,10 @@ replaced. `.fullsend/config.base.yaml` is managed as described under [Configuration presets](#configuration-presets). When the manifest is read-only (an HTTPS URL, a pipe or FIFO such as `<(cmd)`, -or a local file without write permission), install fails before attempting any -manifest write and prints the exact entry to add to its source, including for a -glob-covered repository whose first-install `tracker` default needs an explicit +or a local file without write permission or on a read-only file system), +install fails before attempting any manifest write and prints the exact entry +to add to its source, including for a glob-covered repository whose +first-install `tracker` default needs an explicit entry. `--dry-run`, live install and `repos status` agree. Trace signing keys follow their own rule on GitHub: from such a manifest, a fresh install without `--rotate-trace-signing-key` goes ahead without keys and says so, and any diff --git a/internal/repos/config_layers_test.go b/internal/repos/config_layers_test.go index 9613e65a35..725181db24 100644 --- a/internal/repos/config_layers_test.go +++ b/internal/repos/config_layers_test.go @@ -2,9 +2,11 @@ package repos import ( "context" + "io/fs" "os" "path/filepath" "strconv" + "syscall" "testing" "github.com/fullsend-ai/fullsend/internal/config" @@ -273,6 +275,30 @@ func TestManifestReadOnly_LocalFileWithoutWritePermission(t *testing.T) { err := writeManifest(path, m) require.Error(t, err) assert.Contains(t, err.Error(), "read-only") + + // Write bits that leave out the owner: only the open for writing tells. + require.NoError(t, os.Chmod(path, 0o464)) + if os.Geteuid() != 0 { + assert.True(t, ManifestReadOnly(m, path)) + } +} + +// A file on a read-only file system (a Docker :ro bind mount or a +// ConfigMap volume) keeps its write bits, so only the open for writing +// tells. +func TestIsWriteDenied(t *testing.T) { + for _, tc := range []struct { + errno syscall.Errno + want bool + }{ + {syscall.EROFS, true}, + {syscall.EACCES, true}, + {syscall.EPERM, true}, + {syscall.ENOENT, false}, + } { + err := &fs.PathError{Op: "open", Path: "repos.yaml", Err: tc.errno} + assert.Equal(t, tc.want, isWriteDenied(err), "%v", err) + } } func TestEnsureManagedConfigDefaults_ReadOnlyLocalManifestFailsBeforeWrite(t *testing.T) { diff --git a/internal/repos/managed_config_writeback.go b/internal/repos/managed_config_writeback.go index a9b2cbd1a1..f4d6211eec 100644 --- a/internal/repos/managed_config_writeback.go +++ b/internal/repos/managed_config_writeback.go @@ -8,6 +8,7 @@ import ( "os" "slices" "strings" + "syscall" "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" @@ -487,7 +488,7 @@ func installDefaultsPossible(resolved ResolvedConfig) bool { // ManifestReadOnly reports whether the manifest at path cannot be written: // an HTTP(S) source, a pipe, FIFO or device (as -f <(cmd) gives), or a -// local file without write permission. +// local file without write permission or on a read-only file system. func ManifestReadOnly(m *Manifest, path string) bool { lower := strings.ToLower(path) if m.sourceRemote || strings.HasPrefix(lower, "https://") || strings.HasPrefix(lower, "http://") { @@ -512,12 +513,18 @@ func ManifestReadOnly(m *Manifest, path string) bool { } f, err := os.OpenFile(path, os.O_WRONLY, 0) if err != nil { - return errors.Is(err, fs.ErrPermission) + return isWriteDenied(err) } _ = f.Close() return false } +// isWriteDenied reports whether an open for writing failed because the file +// cannot be written: no write permission, or a read-only file system. +func isWriteDenied(err error) bool { + return errors.Is(err, fs.ErrPermission) || errors.Is(err, syscall.EROFS) +} + func findExplicitEntryIn(platform *PlatformConfig, name string) *RepoEntry { if platform == nil { return nil From 12499619c5f07330b7ab2e382d2af8871e139e8f Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 13:11:29 -0500 Subject: [PATCH 07/12] fix(#9060): fail only the repository whose trace keys install refuses One repository's trace signing key refusal stopped the whole repos install: a malformed FULLSEND_TRACE_SIGNING_KEY_ID, an entry that contradicts the committed trace_context or the key ID variable, or a plain run's recovery that a read-only repos.yaml cannot record kept every other selected repository from converging. EnsureTraceSigningKeys now returns these as refusals, and repos install skips each refused repository and lists it as FAILED, as it does one that needs adoption (#8511). The trace preflight runs before the tracking writeback, and the skip list also reaches that writeback, the safety and infrastructure preflights and convergence, so a refused repository gets no repos.yaml edit, no key and no commit; its commit would have replaced the committed trace_context with the entry's. A read error, or --rotate-trace-signing-key with a read-only repos.yaml, still stops the run, and that error also names every refusal. A refusal now says that install wrote nothing for the repository. A contradicting entry's remedy is to restore its trace_context from the repos.yaml the last install wrote, not to switch to that file, which would drop the keys the run recorded for other repositories. The help text and docs say which trace key problems fail one repository and which stop the run. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 44 ++-- .../guides/getting-started/repo-management.md | 5 +- docs/reference/trace-context.md | 37 ++-- internal/cli/repos.go | 92 ++++---- internal/cli/repos_trace_keys_test.go | 197 +++++++++++++++++- internal/repos/trace_keys.go | 90 +++++--- internal/repos/trace_keys_converge_test.go | 17 +- internal/repos/trace_keys_test.go | 185 ++++++++++++---- 8 files changed, 508 insertions(+), 159 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index 452cfd742d..37f9167bdf 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -257,8 +257,11 @@ so a run they stop leaves `repos.yaml` unchanged: - the existing configuration layers: an undeclared base stops the run, and a repository that needs adoption is skipped; - the token's scopes and the sign-off identity; -- a read-only manifest that must record the `tracker` default or a trace key, - and the [trace signing key](#trace-signing-keys) refusals; +- the [trace signing keys](#trace-signing-keys): a repository whose keys + install refuses, or whose recovery a read-only manifest cannot record, is + skipped, and `--rotate-trace-signing-key` with a read-only manifest stops + the run; +- a read-only manifest that must record the `tracker` default; - the proposed configuration, against the installed layers and against the effective infrastructure. @@ -709,21 +712,26 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see included (see [`repos uninstall`](#repos-uninstall)). - **Checks before any write.** Before it writes `repos.yaml` or any key, install compares each entry with the committed `.fullsend/config.yaml` and - with `FULLSEND_TRACE_SIGNING_KEY_ID`, and stops the run when they contradict - it (see + with `FULLSEND_TRACE_SIGNING_KEY_ID`. When they contradict it, install + writes nothing for that repository, lists it as failed and converges the + others (see [When install refuses an entry](../reference/trace-context.md#when-install-refuses-an-entry)). A `FULLSEND_TRACE_SIGNING_KEY_ID` value that is not 16 lowercase hex - characters also stops the run: delete the variable, then run install again. + characters also fails the repository: delete the variable, then run install + again. A failed read of either still stops the run, as in the other + preflights, and so does `--rotate-trace-signing-key` with a read-only + manifest, which cannot record the rotation the run asks for. Install cannot tell an older copy of `repos.yaml` from the one a run wrote when that run failed after deleting the variable, at the seed or variable write (a seed write that failed may still have landed), so keep and commit the `repos.yaml` such a run wrote, and retry with it. - **Read-only manifest.** A manifest loaded from an HTTPS URL, read from a - pipe or FIFO, or a local file without write permission cannot record a key. - From such a manifest, a fresh install without `--rotate-trace-signing-key` - goes ahead without keys and says so. A later run with the flag and a - writable manifest provisions them. Any other key write stops the run before - it writes any key. + pipe or FIFO, or a local file without write permission or on a read-only + file system cannot record a key. From such a manifest, a fresh install + without `--rotate-trace-signing-key` goes ahead without keys and says so. A + later run with the flag and a writable manifest provisions them. Any other + key write fails that repository, and with `--rotate-trace-signing-key` the + run stops before it writes any key. - **Concurrent installs.** Just before it writes a key, install reads `FULLSEND_TRACE_SIGNING_KEY_ID` again. If that read fails, or the variable appeared, disappeared or changed since the run first read it, install writes @@ -755,15 +763,15 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see delete the variable or restore the entry's `trace_context`. Use a release with this change for every `repos` command on that manifest. Keep and commit the `repos.yaml` edits install makes: a later install from a copy without - them stops the run, except after a run that failed writing the seed or - `FULLSEND_TRACE_SIGNING_KEY_ID`, when it replaces the key that run may have - written without retaining it. If the copy with those edits is lost, + them fails that repository, except after a run that failed writing the + seed or `FULLSEND_TRACE_SIGNING_KEY_ID`, when it replaces the key that run + may have written without retaining it. If the copy with those edits is lost, rebuild the entry's `trace_context` from the block in the `.fullsend/config.yaml` that the last install committed (in its pull request until that merges). An entry that already declares `trace_context` by hand gets a new key pair on its first install with this release, as a recovery: install replaces `FULLSEND_TRACE_SIGNING_KEY` and moves the declared active - key to `retained`. From a read-only manifest, that run stops. + key to `retained`. From a read-only manifest, that repository fails. ```bash fullsend repos install acme/api --rotate-trace-signing-key @@ -1788,10 +1796,10 @@ the uninstall pull request first. Until then, install refuses the entry. workflow and the committed block in place. When you declare the repository again without keys, install refuses the entry until you restore its `trace_context` or a full uninstall finishes. A repository that a glob covers -stays selected after uninstall removes its own entry, so these refusals stop -any install that selects it, such as an unfiltered run or the glob, and once -a full uninstall finishes, the next such install enrolls it again. Select -other repositories by name, or narrow the glob, to keep it out. See +stays selected after uninstall removes its own entry, so while these +refusals hold, any install that selects it, such as an unfiltered run or the +glob, skips it and lists it as failed, and once a full uninstall finishes, +the next such install enrolls it again. Narrow the glob to keep it out. See [Trace Context Reference — Uninstall](../reference/trace-context.md#uninstall). ```bash diff --git a/docs/guides/getting-started/repo-management.md b/docs/guides/getting-started/repo-management.md index 4005b09edf..a454f6d8fe 100644 --- a/docs/guides/getting-started/repo-management.md +++ b/docs/guides/getting-started/repo-management.md @@ -501,8 +501,9 @@ to add to its source, including for a glob-covered repository whose first-install `tracker` default needs an explicit entry. `--dry-run`, live install and `repos status` agree. Trace signing keys follow their own rule on GitHub: from such a manifest, a fresh install without -`--rotate-trace-signing-key` goes ahead without keys and says so, and any -other install that must record a key stops the run before it writes one (see +`--rotate-trace-signing-key` goes ahead without keys and says so, any other +repository that must record a key fails, and `--rotate-trace-signing-key` +stops the run before it writes a key (see [Trace signing keys](../../cli/repos.md#trace-signing-keys)). ```bash diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 9bf223b125..2939031a03 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -117,7 +117,7 @@ active key. Install then writes no key unless you pass key, the secret may not hold the active key. In that case, and when the secret is missing, the next plain `repos install` generates a new key through the same steps and keeps the installation ID. From a read-only manifest, that run -stops before it writes any key. +fails the repository and writes nothing for it. Unless another install of the repository wrote a key after the run started (see step 2), a run that stopped at any step converges on a plain retry with @@ -158,7 +158,7 @@ Install replaces the managed `.fullsend/config.yaml` with what `repos.yaml` declares, so an older copy of `repos.yaml` could drop keys that a later run added. Before it writes `repos.yaml` or any key, install compares each selected repository's entry with the committed `.fullsend/config.yaml` and -with `FULLSEND_TRACE_SIGNING_KEY_ID`. It stops the run when: +with `FULLSEND_TRACE_SIGNING_KEY_ID`. It refuses the repository when: - the committed installation ID differs from the entry's, and a fullsend workflow is on the default branch; @@ -171,9 +171,12 @@ with `FULLSEND_TRACE_SIGNING_KEY_ID`. It stops the run when: `trace_context`, or names a key that the entry does not list; - another `repos.yaml` entry uses the same installation ID. -These usually mean that the last install wrote a different `repos.yaml`. Run -install with the `repos.yaml` the last install wrote, or restore the entry's -`trace_context` from it. +Install then writes nothing for that repository and lists it as failed, and +the other repositories still converge. Such a mismatch usually means that the +last install wrote a different `repos.yaml`. Restore the entry's +`trace_context` from the `repos.yaml` the last install wrote. Do not switch +to that file: the run that refused the repository may have recorded other +repositories' keys in the current one. Install cannot detect an older copy after a run that failed after deleting `FULLSEND_TRACE_SIGNING_KEY_ID` (step 3), at the seed write (step 4) or the @@ -200,7 +203,7 @@ revert that change, and do not add the key to `repos.yaml`: that would make it trusted. A `FULLSEND_TRACE_SIGNING_KEY_ID` value that is not 16 lowercase hex -characters also stops the run before it writes `repos.yaml` or any key. The +characters also fails the repository, and install writes nothing for it. The error names the repository and the variable and says to delete the variable. It never shows the value. Delete the variable, then run install again: @@ -209,12 +212,14 @@ gh variable delete FULLSEND_TRACE_SIGNING_KEY_ID --repo OWNER/REPO fullsend repos install OWNER/REPO ``` -Install also stops the run, before it writes any key, when it needs to record -a key and the manifest is read-only: an HTTPS URL, a pipe or FIFO, or a local -file without write permission. Run install from a writable local copy of the -manifest instead. A fresh install without `--rotate-trace-signing-key` is the -exception, including the re-enrollment of a fully uninstalled repository: it -goes ahead without keys (see +Install also fails the repository, and writes nothing for it, when it needs +to record a key and the manifest is read-only: an HTTPS URL, a pipe or FIFO, +or a local file without write permission or on a read-only file system. With +`--rotate-trace-signing-key`, it stops the run before it writes any key, +since the run cannot record the rotation it asks for. Run install from a +writable local copy of the manifest instead. A fresh install without +`--rotate-trace-signing-key` is the exception, including the re-enrollment +of a fully uninstalled repository: it goes ahead without keys (see [Installation ID and key pair](#installation-id-and-key-pair) and [Uninstall](#uninstall)). @@ -243,10 +248,10 @@ installation instead, restore the entry's `trace_context` from the `repos.yaml` the last install wrote. A repository that a glob covers stays selected after uninstall removes its own -entry, so these refusals stop any install that selects it, such as an -unfiltered run or the glob, and once a full uninstall finishes, the next such -install enrolls it again. Select other repositories by name, or narrow the -glob, to keep it out. +entry, so while these refusals hold, any install that selects it, such as an +unfiltered run or the glob, skips it and lists it as failed, and once a full +uninstall finishes, the next such install enrolls it again. Narrow the glob +to keep it out. Install replaces the ended block in the commit that delivers its scaffold, by default through the install pull request. Until that change lands, the diff --git a/internal/cli/repos.go b/internal/cli/repos.go index 5b10280825..c488e77ce6 100644 --- a/internal/cli/repos.go +++ b/internal/cli/repos.go @@ -534,10 +534,12 @@ keeping the installation ID and retaining the previous public key, when the secret is missing, when that variable is missing or names a retained key, and with --rotate-trace-signing-key, whose first use gives an existing install its keys. From a read-only manifest a fresh -install without --rotate-trace-signing-key goes ahead without keys; any -other key write stops the run. Output shows installation and key IDs, -never the seed. Commit the repos.yaml changes install makes, and run one -install of a repository at a time. GitLab repositories get no keys yet. +install without --rotate-trace-signing-key goes ahead without keys, and +any other key write fails that repository; with +--rotate-trace-signing-key it stops the run. Output shows installation +and key IDs, never the seed. Commit the repos.yaml changes install +makes, and run one install of a repository at a time. GitLab +repositories get no keys yet. The persistent-setting flags --roles, --fullsend-ref, --mint-url, --app-set, --inference-auth, --vendor, --signoff, --gitlab-url, --vertex-region and @@ -774,12 +776,14 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { // before any manifest or forge write: a markerless overlay needs // adoption and an undeclared base needs resolution (#8218). A repo that // only needs adoption is skipped and reported as failed, so the other - // repos still converge (#8511); every other problem stops the run. + // repos still converge (#8511); every other problem it finds stops the + // run. The trace signing key preflight below skips a repo it refuses + // the same way. adoptionRequired, err := repos.PreflightManagedConfig(ctx, manifest, preflightClients, opts.repoFilter) if err != nil { return fmt.Errorf("configuration preflight: %w", err) } - adoptionFailedRepos := make([]repos.ConvergeResult, 0, len(adoptionRequired)) + skippedRepos := make([]repos.ConvergeResult, 0, len(adoptionRequired)) adoptionSkip := make([]string, 0, len(adoptionRequired)) for _, a := range adoptionRequired { printer.StepFail(fmt.Sprintf("[%s] skipped: %s", a.Name(), a.Guidance)) @@ -789,7 +793,7 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { // recovery. continue } - adoptionFailedRepos = append(adoptionFailedRepos, repos.ConvergeResult{ + skippedRepos = append(skippedRepos, repos.ConvergeResult{ Owner: a.Owner, Repo: a.Repo, Error: fmt.Errorf("adoption required: %s exists without the managed-configuration ownership marker (ADR-0122); see the guidance above; nothing was written", preset.OverlayPath), }) @@ -829,48 +833,61 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { deferOutput := func(f func()) { deferredOutput = append(deferredOutput, f) } manifestChanged := false - // Persist the install-time choice the generated managed overlay must - // reproduce (the upstream tracking default for a no-preset first - // install) in each repo's manifest entry before the overlay is rendered - // (#8218). A manifest that cannot be written fails here, before any - // forge write, with the exact edit. - writtenBack, wbErr := repos.EnsureManagedConfigDefaults(ctx, repos.ManagedConfigWritebackConfig{ + // Plan trace signing key writes (ADR 0154) and record their public keys + // in the manifest entries, under the same deferred-persist contract. It + // runs before the tracking writeback, so a repo whose keys install + // refuses gets no tracking default either. A read error, or + // --rotate-trace-signing-key with a read-only manifest, fails here, + // before the manifest write and any key write. A fresh install from a + // read-only manifest without --rotate-trace-signing-key goes ahead + // without keys and says so. + traceKeyPlans, traceRefused, traceErr := repos.EnsureTraceSigningKeys(ctx, repos.TraceKeysConfig{ Manifest: manifest, ManifestPath: opts.manifest, - DryRun: true, Deferred: !opts.dryRun, RepoFilter: opts.repoFilter, ExcludeRepos: adoptionSkip, + Rotate: opts.rotateTraceSigningKey, }, preflightClients, func(repo, _, msg string) { deferOutput(func() { printer.StepInfo(fmt.Sprintf("[%s] %s", repo, msg)) }) }) - if wbErr != nil { - return fmt.Errorf("recording install defaults in manifest: %w", wbErr) + if traceErr != nil { + return fmt.Errorf("planning trace signing keys: %w", traceErr) } - if len(writtenBack) > 0 { + // A repo whose trace keys install refuses is skipped and reported as + // failed, like one that needs adoption, so the other repos still + // converge. Every later preflight and convergence skip it too: its + // commit would replace the committed trace_context with the entry's. + skipped := append([]string(nil), adoptionSkip...) + for _, r := range traceRefused { + name := r.Owner + "/" + r.Repo + printer.StepFail(fmt.Sprintf("[%s] skipped: %v", name, r.Err)) + skipped = append(skipped, name) + skippedRepos = append(skippedRepos, repos.ConvergeResult{Owner: r.Owner, Repo: r.Repo, Error: r.Err}) + } + if len(traceKeyPlans) > 0 { manifestChanged = true } - // Plan trace signing key writes (ADR 0154) and record their public keys - // in the manifest entries, under the same deferred-persist contract. A - // refusal, or a read-only manifest that must record a key, fails here, - // before the manifest write and any key write. A fresh install from a - // read-only manifest without --rotate-trace-signing-key goes ahead - // without keys and says so. - traceKeyPlans, traceErr := repos.EnsureTraceSigningKeys(ctx, repos.TraceKeysConfig{ + // Persist the install-time choice the generated managed overlay must + // reproduce (the upstream tracking default for a no-preset first + // install) in each repo's manifest entry before the overlay is rendered + // (#8218). A manifest that cannot be written fails here, before any + // forge write, with the exact edit. + writtenBack, wbErr := repos.EnsureManagedConfigDefaults(ctx, repos.ManagedConfigWritebackConfig{ Manifest: manifest, ManifestPath: opts.manifest, + DryRun: true, Deferred: !opts.dryRun, RepoFilter: opts.repoFilter, - ExcludeRepos: adoptionSkip, - Rotate: opts.rotateTraceSigningKey, + ExcludeRepos: skipped, }, preflightClients, func(repo, _, msg string) { deferOutput(func() { printer.StepInfo(fmt.Sprintf("[%s] %s", repo, msg)) }) }) - if traceErr != nil { - return fmt.Errorf("planning trace signing keys: %w", traceErr) + if wbErr != nil { + return fmt.Errorf("recording install defaults in manifest: %w", wbErr) } - if len(traceKeyPlans) > 0 { + if len(writtenBack) > 0 { manifestChanged = true } @@ -890,14 +907,14 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { // Compare the proposed layered configuration (manifest edits and declared // presets) with each repository's installed layers before anything is // persisted or written to the forge. - if err := repos.PreflightProposedManagedSafety(ctx, manifest, preflightClients, opts.repoFilter, adoptionSkip); err != nil { + if err := repos.PreflightProposedManagedSafety(ctx, manifest, preflightClients, opts.repoFilter, skipped); err != nil { return fmt.Errorf("configuration safety preflight: %w", err) } // Resolve the effective infrastructure and reconcile the Vertex inputs // of every selected repository before the manifest is persisted, so a // mint URL conflict or a flag that contradicts the declared // configuration leaves repos.yaml byte-identical. - if err := repos.PreflightEffectiveInfrastructure(ctx, manifest, preflightClients, opts.repoFilter, adoptionSkip, opts.inferenceProject, opts.inferenceWIFProvider); err != nil { + if err := repos.PreflightEffectiveInfrastructure(ctx, manifest, preflightClients, opts.repoFilter, skipped, opts.inferenceProject, opts.inferenceWIFProvider); err != nil { return fmt.Errorf("effective infrastructure preflight: %w", err) } // A dry run reports the size refusal that the write below gives. @@ -1010,7 +1027,7 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { Manifest: manifest, DryRun: opts.dryRun, RepoFilter: opts.repoFilter, - ExcludeRepos: append(containFailedKeys(containFailedRepos), adoptionSkip...), + ExcludeRepos: append(containFailedKeys(containFailedRepos), skipped...), MaxConcurrency: opts.concurrency, UpstreamRef: upstreamRef, UpstreamTag: upstreamTag, @@ -1150,9 +1167,10 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { for _, r := range containFailedRepos { failedRepoKeys[r.Owner+"/"+r.Repo] = true } - // A repo skipped because its overlay needs adoption was excluded the - // same way and is likewise counted once and takes no later stage. - for _, r := range adoptionFailedRepos { + // A repo skipped because its overlay needs adoption or install refused + // its trace signing keys was excluded the same way and is likewise + // counted once and takes no later stage. + for _, r := range skippedRepos { failedRepoKeys[r.Owner+"/"+r.Repo] = true } postInstallRepos := make([]repos.ConvergeResult, 0, len(installed)+len(converged)+len(alreadyCurrent)) @@ -1442,7 +1460,7 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { printer.Blank() installedCount := len(installed) - installedPostFail - roleFailInstalledCount - failedCount := len(failed) + len(postInstallFailedRepos) + len(containFailedRepos) + len(adoptionFailedRepos) + pollStateFail + roleFail + failedCount := len(failed) + len(postInstallFailedRepos) + len(containFailedRepos) + len(skippedRepos) + pollStateFail + roleFail for _, r := range failed { printer.StepInfo(fmt.Sprintf(" FAILED: %s/%s — %v", r.Owner, r.Repo, r.Error)) @@ -1456,7 +1474,7 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { for _, r := range containFailedRepos { printer.StepInfo(fmt.Sprintf(" FAILED: %s/%s — %v", r.Owner, r.Repo, r.Error)) } - for _, r := range adoptionFailedRepos { + for _, r := range skippedRepos { printer.StepInfo(fmt.Sprintf(" FAILED: %s/%s — %v", r.Owner, r.Repo, r.Error)) } for _, r := range roleFailedRepos { diff --git a/internal/cli/repos_trace_keys_test.go b/internal/cli/repos_trace_keys_test.go index 29df61fb43..41eff7de6e 100644 --- a/internal/cli/repos_trace_keys_test.go +++ b/internal/cli/repos_trace_keys_test.go @@ -7,6 +7,7 @@ import ( "encoding/hex" "errors" "fmt" + "maps" "os" "regexp" "strings" @@ -14,6 +15,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/repos" @@ -272,8 +274,9 @@ func TestRunReposInstall_ScopeOrIdentityFailureLeavesManifestUnchanged(t *testin } // A committed config that trusts a key the repos.yaml entry does not list -// stops the install before repos.yaml is persisted or the forge is written, -// and the error names the key by its ID only. +// fails the repository before repos.yaml is persisted or the forge is +// written: it is listed as FAILED with an error that names the key by its ID +// only. func TestRunReposInstall_ContradictingCommittedConfigRefusedBeforeWrites(t *testing.T) { active, extra := testTraceVerificationKey(1), testTraceVerificationKey(3) manifest := githubUnmanagedManifestYAML + " config:\n" + @@ -288,18 +291,196 @@ func TestRunReposInstall_ContradictingCommittedConfigRefusedBeforeWrites(t *test var err error out := captureStdout(t, func() { err = runReposInstall(context.Background(), githubManagedInstallOpts(manifestPath, fc)) }) - require.ErrorIs(t, err, repos.ErrTraceManifestStale) - msg := err.Error() - assert.True(t, strings.HasPrefix(msg, "planning trace signing keys: "), msg) - assert.Contains(t, msg, "acme/api") - assert.Contains(t, msg, "trusts key ID "+hexTraceKeyID(testTracePublicKey(3)), "the error names the extra key by its ID") + require.EqualError(t, err, "1 repos failed") + failed := regexp.MustCompile(`FAILED: acme/api — ` + regexp.QuoteMeta(repos.ErrTraceManifestStale.Error()) + `.*`).FindString(out) + require.NotEmpty(t, failed, "acme/api is listed as FAILED with the refusal") + assert.Contains(t, failed, "trusts key ID "+hexTraceKeyID(testTracePublicKey(3)), "the error names the extra key by its ID") for _, key := range []string{active, extra} { - assert.NotContains(t, msg+out, key, "a verification key appears only as its ID") + assert.NotContains(t, out, key, "a verification key appears only as its ID") } assert.Equal(t, manifest, mustReadFile(t, manifestPath), "repos.yaml is not written") assertNoInstallWrites(t, fc) } +// repoWrites counts the commits, the secret writes and deletions, and the +// variable writes and deletions the fake recorded for repo. It returns +// counts only, so no seed is printed. +func repoWrites(fc *forge.FakeClient, repo string) (commits, secrets, variables int) { + for _, c := range fc.CommittedFiles { + if c.Owner+"/"+c.Repo == repo { + commits++ + } + } + for _, c := range fc.CommittedFilesToBranch { + if c.Owner+"/"+c.Repo == repo { + commits++ + } + } + for _, records := range [][]forge.SecretRecord{fc.CreatedSecrets, fc.DeletedSecrets} { + for _, s := range records { + if s.Owner+"/"+s.Repo == repo { + secrets++ + } + } + } + for _, records := range [][]forge.VariableRecord{fc.Variables, fc.UpdatedVariables, fc.DeletedVariables} { + for _, v := range records { + if v.Owner+"/"+v.Repo == repo { + variables++ + } + } + } + return commits, secrets, variables +} + +// manifestEntryYAML returns the repos.yaml entry named name in the manifest +// at path as YAML, or "" when the manifest has none. An entry holds public +// values only. +func manifestEntryYAML(t *testing.T, path, name string) string { + t.Helper() + m, err := repos.LoadManifest(context.Background(), path) + require.NoError(t, err) + for _, e := range m.AllRepos() { + if e.Name == name { + data, err := yaml.Marshal(e) + require.NoError(t, err) + return string(data) + } + } + return "" +} + +// A repository whose trace signing keys install refuses is skipped and +// listed as FAILED, like one that needs adoption (#8511), and the run exits +// non-zero, while acme/web converges. The refused repository gets no commit, +// no secret and no variable write, its committed config is unchanged and +// its repos.yaml entry is byte-identical: install records no tracker +// default for it and carves no entry for it out of a glob. Its layers and +// its infrastructure are not checked, so they cannot stop the run. +func TestRunReposInstall_TraceKeyRefusalSkipsOnlyThatRepo(t *testing.T) { + const web = " - name: acme/web\n" + declared := strings.TrimPrefix(behaviourTestManifestYAML, "version: 1\ngithub:\n repos:\n") + block := indentLines(" ", traceContextYAML(testTraceInstallationID, forge.SecretTraceSigningKey, testTraceVerificationKey(1))) + setKeyIDVar := func(fc *forge.FakeClient, value string) { + fc.VariableValues["acme/api/"+forge.VarTraceSigningKeyID] = value + fc.VariablesExist["acme/api/"+forge.VarTraceSigningKeyID] = true + } + malformed := func(fc *forge.FakeClient) { setKeyIDVar(fc, "not-a-key-id") } + // installAPI makes acme/api an existing install whose committed + // .fullsend/config.yaml is the managed overlay. + installAPI := func(fc *forge.FakeClient, overlay string) { + installed := newInstalledFakeClientCLI("acme/api") + maps.Copy(fc.VariableValues, installed.VariableValues) + maps.Copy(fc.Secrets, installed.Secrets) + maps.Copy(fc.FileContents, installed.FileContents) + fc.FileContents[overlayPath("acme/api")] = []byte(managedConfigMarker + overlay) + } + cases := []struct { + name string + manifest string + readOnly bool + dryRun bool + setup func(fc *forge.FakeClient) + sentinel error + }{ + {name: "malformed key ID variable", manifest: githubUnmanagedManifestYAML + web, setup: malformed, + sentinel: repos.ErrTraceKeyIDInvalid}, + {name: "malformed key ID variable, dry run", manifest: githubUnmanagedManifestYAML + web, dryRun: true, setup: malformed, + sentinel: repos.ErrTraceKeyIDInvalid}, + // As an uninstall by a release without this change leaves it. + {name: "key ID variable on a keyless entry", manifest: githubUnmanagedManifestYAML + web, + setup: func(fc *forge.FakeClient) { setKeyIDVar(fc, hexTraceKeyID(testTracePublicKey(1))) }, sentinel: repos.ErrTraceManifestStale}, + {name: "committed config trusts a key the entry lacks", manifest: githubUnmanagedManifestYAML + " config:\n" + block + web, + setup: func(fc *forge.FakeClient) { + installAPI(fc, traceContextYAML(testTraceInstallationID, forge.SecretTraceSigningKey, + testTraceVerificationKey(1), testTraceVerificationKey(3))) + fc.Secrets["acme/api/"+forge.SecretTraceSigningKey] = true + setKeyIDVar(fc, hexTraceKeyID(testTracePublicKey(1))) + }, sentinel: repos.ErrTraceManifestStale}, + // A hand-declared trace_context without a seed is a recovery, which + // a read-only repos.yaml cannot record. + {name: "recovery from a read-only repos.yaml", manifest: behaviourTestManifestYAML + block + strings.Replace(declared, "acme/api", "acme/web", 1), + readOnly: true, sentinel: repos.ErrTraceManifestReadOnly}, + {name: "glob-covered", manifest: strings.Replace(githubUnmanagedManifestYAML, "acme/api", "acme/*", 1), setup: malformed, + sentinel: repos.ErrTraceKeyIDInvalid}, + {name: "layers the safety check rejects", manifest: githubUnmanagedManifestYAML + web, + setup: func(fc *forge.FakeClient) { + installAPI(fc, "kill_switch: true\n") + malformed(fc) + }, sentinel: repos.ErrTraceKeyIDInvalid}, + {name: "mint URL conflict", manifest: githubUnmanagedManifestYAML + " config:\n mint_url: https://other-mint.example.com\n" + web, + setup: malformed, sentinel: repos.ErrTraceKeyIDInvalid}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + path := writeTestManifest(t, tc.manifest) + if tc.readOnly { + require.NoError(t, os.Chmod(path, 0o444)) + } + fc := newInstallFakeClient("acme/api", "acme/web") + if tc.setup != nil { + tc.setup(fc) + } + committed := string(fc.FileContents[overlayPath("acme/api")]) + entry := manifestEntryYAML(t, path, "acme/api") + opts := githubManagedInstallOpts(path, fc) + opts.dryRun = tc.dryRun + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + written := mustReadFile(t, path) + + // acme/web converges. Its seed is checked before any assertion + // that prints the output. + switch { + case tc.dryRun: + assertNoInstallWrites(t, fc) + assert.Equal(t, tc.manifest, written, "a dry run leaves repos.yaml byte-identical") + assert.Equal(t, 1, strings.Count(out, "[acme/web] Would persist config.trace_context"), "the dry run previews acme/web's key") + case tc.readOnly: + assert.Equal(t, tc.manifest, written, "repos.yaml is byte-identical") + commits, _, _ := repoWrites(fc, "acme/web") + assert.NotZero(t, commits, "acme/web is installed") + assert.Zero(t, len(writtenTraceSeed(fc, "acme/web")), "acme/web goes ahead without keys") + assert.Equal(t, 1, strings.Count(out, "[acme/web] Trace signing keys not provisioned: repos.yaml is read-only"), "one notice") + default: + _, pub := requireTraceKeyWritten(t, fc, "acme/web", out, written) + assert.Equal(t, pub, traceValue(traceActiveKeyRe, string(fc.FileContents[overlayPath("acme/web")])), "acme/web's commit carries its key") + } + + require.EqualError(t, err, "1 repos failed") + assert.Equal(t, 1, strings.Count(out, "FAILED: "), "one repository fails") + assert.Equal(t, 1, strings.Count(out, "FAILED: acme/api — "+tc.sentinel.Error()), "acme/api fails with the refusal") + assert.Equal(t, 1, strings.Count(out, "[acme/api] skipped: "+tc.sentinel.Error()), "acme/api is skipped with the refusal") + assert.NotRegexp(t, `\[acme/api\] (Persisted|Would persist)`, out, "no repos.yaml edit for acme/api") + commits, secrets, variables := repoWrites(fc, "acme/api") + assert.Zero(t, commits, "no commit for acme/api") + assert.Zero(t, secrets, "no secret write for acme/api") + assert.Zero(t, variables, "no variable write or deletion for acme/api") + assert.Equal(t, committed, string(fc.FileContents[overlayPath("acme/api")]), "acme/api's committed config is unchanged") + assert.Equal(t, entry, manifestEntryYAML(t, path, "acme/api"), "acme/api's repos.yaml entry is unchanged") + }) + } +} + +// --rotate-trace-signing-key from a read-only repos.yaml stops the run +// before any write, also with two repositories: the run cannot record any +// rotation it asks for. +func TestRunReposInstall_ReadOnlyRotationStopsTheRun(t *testing.T) { + manifest := behaviourTestManifestYAML + + strings.Replace(strings.TrimPrefix(behaviourTestManifestYAML, "version: 1\ngithub:\n repos:\n"), "acme/api", "acme/web", 1) + path := writeTestManifest(t, manifest) + require.NoError(t, os.Chmod(path, 0o444)) + fc := newInstallFakeClient("acme/api", "acme/web") + opts := githubManagedInstallOpts(path, fc) + opts.rotateTraceSigningKey = true + var err error + captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + require.ErrorIs(t, err, repos.ErrTraceManifestReadOnly) + assert.Contains(t, err.Error(), "acme/api, acme/web", "the error names both repositories") + assert.Equal(t, manifest, mustReadFile(t, path), "repos.yaml is byte-identical") + assertNoInstallWrites(t, fc) +} + // A fresh repository whose markerless .fullsend/config.yaml needs adoption // is skipped by convergence (#8511), so the trace-key preflight skips it // too: repos.yaml records no trace_context and no key is written. diff --git a/internal/repos/trace_keys.go b/internal/repos/trace_keys.go index cea8bde177..47011d40c8 100644 --- a/internal/repos/trace_keys.go +++ b/internal/repos/trace_keys.go @@ -52,6 +52,18 @@ type TraceKeyPlan struct { KeyIDVarExists bool } +// TraceKeyRefusal is a selected repository whose trace signing keys +// EnsureTraceSigningKeys refuses: Err wraps ErrTraceKeyIDInvalid, +// ErrTraceManifestStale, or ErrTraceManifestReadOnly for a recovery that a +// run without Rotate cannot record. repos install skips the repository and +// reports it as failed, as it does one that needs adoption (#8511); its +// convergence would commit the entry's trace_context over the committed +// one. +type TraceKeyRefusal struct { + Owner, Repo string + Err error +} + // Trace-key preflight refusals. They name the repository and key IDs, never // key material or the value of FULLSEND_TRACE_SIGNING_KEY_ID. var ( @@ -69,13 +81,14 @@ var ( // FULLSEND_TRACE_SIGNING_KEY_ID and, when they decide the outcome, the // fullsend workflow marker and whether FULLSEND_TRACE_SIGNING_KEY exists. // Then it: -// - refuses with ErrTraceKeyIDInvalid, before any edit, a variable that is -// not 16 lowercase hex characters; -// - refuses with ErrTraceManifestStale, before any edit, an entry whose -// installation_id differs from the committed one, that lacks a committed -// key, or that has no trace_context while the committed config has one; -// a variable set beside an entry without trace_context, or naming a key -// the entry does not list; and an installation_id another entry uses. +// - refuses with ErrTraceKeyIDInvalid a variable that is not 16 lowercase +// hex characters; +// - refuses with ErrTraceManifestStale an entry whose installation_id +// differs from the committed one, that lacks a committed key, or that +// has no trace_context while the committed config has one; a variable +// set beside an entry without trace_context, or naming a key the entry +// does not list; and an installation_id another entry uses, which +// refuses both entries when both are selected. // The committed block of an ended installation is not compared with the // entry: a keyless entry's block once no fullsend workflow, seed or // variable remains (a full uninstall, which keeps the committed config @@ -85,34 +98,41 @@ var ( // or names a retained key, "rotation" for Rotate, and "fresh install" // for a keyless entry without a fullsend workflow; a healthy install, // and an existing install without trace_context, get no plan; -// - refuses with ErrTraceManifestReadOnly, before any edit, a plan that a -// read-only manifest cannot record, except a fresh install without -// Rotate, which goes ahead without keys and says so; +// - refuses with ErrTraceManifestReadOnly a recovery without Rotate that a +// read-only manifest cannot record; a fresh install without Rotate goes +// ahead without keys and says so; // - otherwise generates a key (and, for an entry without keys, an // installation ID) from crypto/rand, retains the previous active key, // records the block in the manifest entry (carving an explicit entry out // of a glob like EnsureManagedConfigDefaults) and returns a plan keyed // "owner/repo". // +// A refused repository gets no plan, no edit and no progress line, and is +// returned as a TraceKeyRefusal; the others are still planned. A read, +// client or parse error, and a key that Rotate asks for from a read-only +// manifest, stop the run before any edit: the error also names every +// refusal, and nothing else is returned. +// // EnsureTraceSigningKeys never writes repos.yaml; the caller persists the // edited manifest (repos install does so through its compare-before-write // guard). Deferred reports that the caller persists it, so progress says // Persisted rather than Would persist. Repositories that fail // RequireInferenceAuth are skipped. Progress names installation and key IDs, // and the glob a new entry was copied from, never the seed. -func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients ForgeClientFactory, progress ProgressFunc) (map[string]*TraceKeyPlan, error) { +func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients ForgeClientFactory, progress ProgressFunc) (map[string]*TraceKeyPlan, []TraceKeyRefusal, error) { if progress == nil { progress = func(_, _, _ string) {} } m := cfg.Manifest selected, err := selectManifestRepos(ctx, m, clients, cfg.RepoFilter) if err != nil { - return nil, err + return nil, nil, err } readOnly := ManifestReadOnly(m, cfg.ManifestPath) var repos []*traceRepo var gitlab []string var errs []error + var refused []TraceKeyRefusal for _, rr := range withoutRepos(selected, cfg.ExcludeRepos) { if rr.Forge == ForgeGitLab { gitlab = append(gitlab, rr.Owner+"/"+rr.Repo) @@ -124,14 +144,20 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo continue } t, err := readTraceRepo(ctx, m, clients, rr, cfg.Rotate) - if err != nil { + switch { + case errors.Is(err, ErrTraceKeyIDInvalid), errors.Is(err, ErrTraceManifestStale): + refused = append(refused, TraceKeyRefusal{Owner: rr.Owner, Repo: rr.Repo, Err: err}) + case err != nil: errs = append(errs, err) - continue + case readOnly && !cfg.Rotate && t.reason == reasonRecovery: + // A plain run fails only this repository; a rotation the + // manifest cannot record stops the run below. + refused = append(refused, TraceKeyRefusal{Owner: rr.Owner, Repo: rr.Repo, Err: fmt.Errorf( + "%w: recording the trace keys of %s needs a repos.yaml edit; install wrote nothing for it: "+ + "run repos install %s with a writable local manifest", ErrTraceManifestReadOnly, t.name(), t.name())}) + default: + repos = append(repos, t) } - repos = append(repos, t) - } - if err := errors.Join(errs...); err != nil { - return nil, err } var edited []string @@ -146,8 +172,14 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo } } if readOnly && len(edited) > 0 { - return nil, fmt.Errorf("%w: recording the trace keys of %s needs a repos.yaml edit; repos.yaml and the trace keys were not changed: re-run with a writable local manifest", - ErrTraceManifestReadOnly, strings.Join(edited, ", ")) + errs = append(errs, fmt.Errorf("%w: recording the trace keys of %s needs a repos.yaml edit; repos.yaml and the trace keys were not changed: re-run with a writable local manifest", + ErrTraceManifestReadOnly, strings.Join(edited, ", "))) + } + if len(errs) > 0 { + for _, r := range refused { + errs = append(errs, r.Err) + } + return nil, nil, errors.Join(errs...) } for _, name := range gitlab { progress(name, "manifest", "Trace signing keys not provisioned: repos install does not provision them on GitLab yet") @@ -170,7 +202,7 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo } } if len(edited) == 0 { - return nil, nil + return nil, refused, nil } plans := make(map[string]*TraceKeyPlan, len(edited)) @@ -180,7 +212,7 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo } key, err := t.provision() if err != nil { - return nil, fmt.Errorf("%s: %w", t.name(), err) + return nil, nil, fmt.Errorf("%s: %w", t.name(), err) } p := &TraceKeyPlan{Key: key, Reason: t.reason} if t.recordedKeyID != nil { @@ -191,17 +223,17 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo if entry == nil { carved, glob, err := carveOutForForge(m, t.name(), t.rr.Forge) if err != nil { - return nil, fmt.Errorf("%s: %w", t.name(), err) + return nil, nil, fmt.Errorf("%s: %w", t.name(), err) } if carved == nil { - return nil, fmt.Errorf("no manifest entry or glob covers %q", t.name()) + return nil, nil, fmt.Errorf("no manifest entry or glob covers %q", t.name()) } entry, t.carvedFrom = carved, glob } entry.Config = entry.Config.WithTraceContext(t.next) } if err := validateManifestManaged(m); err != nil { - return nil, fmt.Errorf("validating manifest after recording trace keys: %w", err) + return nil, nil, fmt.Errorf("validating manifest after recording trace keys: %w", err) } verb := "Would persist" @@ -215,7 +247,7 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo verb, where, t.next.InstallationID, tracecontext.FormatKeyID(p.Key.KeyID()), p.Reason)) } } - return plans, nil + return plans, refused, nil } // traceKeySet is a validated trace_context block's installation ID and @@ -337,7 +369,7 @@ func readTraceRepo(ctx context.Context, m *Manifest, clients ForgeClientFactory, // The value is never echoed: only install writes the variable, so // anything else in it is unexpected input. if keyID, err = tracecontext.ParseKeyID(value); err != nil { - return nil, fmt.Errorf("%w for %s: its value is not 16 lowercase hex characters; repos.yaml and the trace keys were not changed: "+ + return nil, fmt.Errorf("%w for %s: its value is not 16 lowercase hex characters; install wrote nothing for it: "+ "delete the repository variable %s, then run repos install again", ErrTraceKeyIDInvalid, name, forge.VarTraceSigningKeyID) } } @@ -386,8 +418,8 @@ func readTraceRepo(ctx context.Context, m *Manifest, clients ForgeClientFactory, } } if len(whys) > 0 { - return nil, fmt.Errorf("%w for %s: %s; repos.yaml and the trace keys were not changed: "+ - "run install with the repos.yaml the last install wrote, or restore the entry's trace_context from it", + return nil, fmt.Errorf("%w for %s: %s; install wrote nothing for it: "+ + "restore the entry's trace_context from the repos.yaml the last install wrote", ErrTraceManifestStale, name, strings.Join(whys, "; ")) } if recorded { diff --git a/internal/repos/trace_keys_converge_test.go b/internal/repos/trace_keys_converge_test.go index 71aabce655..46b831b5a0 100644 --- a/internal/repos/trace_keys_converge_test.go +++ b/internal/repos/trace_keys_converge_test.go @@ -446,9 +446,10 @@ func TestTraceKeys_WriteStepFailureThenRetry(t *testing.T) { } progress = &progressLog{} - second, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + second, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) lines := progress.all() requireNoSeed(t, lines, seed) if step == "none" || step == "commit" { @@ -473,9 +474,10 @@ func TestTraceKeys_WriteStepFailureThenRetry(t *testing.T) { assert.Equal(t, after, committed, "the commit delivers the entry's block") progress = &progressLog{} - third, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + third, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) assert.Empty(t, planNames(third), "the install is healthy after one retry") assert.Zero(t, countLines(progress.all(), "ended installation"), "the landed commit leaves no ended installation") }) @@ -565,8 +567,9 @@ func TestTraceKeys_UninstallOnlyThenInstall(t *testing.T) { assert.False(t, kept, "uninstall deletes the key ID variable") progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) p := requireTracePlan(t, plans, "acme/api") assert.Equal(t, reasonRecovery, p.Reason) // The committed block is the entry's own installation, so it has not @@ -647,7 +650,7 @@ func TestTraceKeys_GitHubReenrollAfterFullUninstall(t *testing.T) { } if tc.leftover != nil { tc.leftover(fc) - err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, nil, old) + _, err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, nil, old) require.ErrorIs(t, err, ErrTraceManifestStale) msg := err.Error() assert.Contains(t, msg, "has trace_context and the repos.yaml entry has none (install enrolls the repository again "+ @@ -658,9 +661,10 @@ func TestTraceKeys_GitHubReenrollAfterFullUninstall(t *testing.T) { } progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) p := requireTracePlan(t, plans, "acme/api") lines := progress.all() requireNoSeed(t, lines, p.Key.EncodeSeed()) @@ -690,9 +694,10 @@ func TestTraceKeys_GitHubReenrollFromReadOnlyManifest(t *testing.T) { before := manifestSnapshot(t, cfg.Manifest) progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, ManifestPath: url}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, ManifestPath: url}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) assert.Empty(t, planNames(plans)) assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest), "the entry is not edited") assertNoForgeWrites(t, fc) diff --git a/internal/repos/trace_keys_test.go b/internal/repos/trace_keys_test.go index 2d8bd6605f..4057e36a23 100644 --- a/internal/repos/trace_keys_test.go +++ b/internal/repos/trace_keys_test.go @@ -17,6 +17,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" @@ -83,9 +84,12 @@ func healthyTrace(t *testing.T, m *Manifest, fc *forge.FakeClient, name, block s setKeyIDVar(fc, name, active.id()) } +// ensureTrace runs the preflight, which must refuse no repository. func ensureTrace(t *testing.T, fc forge.Client, cfg TraceKeysConfig) (map[string]*TraceKeyPlan, error) { t.Helper() - return EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), noopProgress) + plans, refused, err := EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), noopProgress) + require.Empty(t, refused, "no repository is refused") + return plans, err } // manifestTrace returns the trace_context of name's explicit manifest entry. @@ -173,27 +177,77 @@ func (p *progressLog) all() []string { return slices.Clone(p.lines) } -// refuseTrace runs the preflight, which must refuse, and checks that the +// stopTrace runs the preflight, which must stop the run, and checks that the // error shows no non-empty value of hidden and no value of keys, before any -// assertion that prints it, and that nothing was planned, edited, written -// or reported. It returns the error for the caller's own checks. -func refuseTrace(t *testing.T, fc *forge.FakeClient, cfg TraceKeysConfig, hidden []string, keys ...traceKey) error { +// assertion that prints it, and that nothing was planned, refused, edited, +// written or reported. It returns the error for the caller's own checks. +func stopTrace(t *testing.T, fc *forge.FakeClient, cfg TraceKeysConfig, hidden []string, keys ...traceKey) error { t.Helper() before := manifestSnapshot(t, cfg.Manifest) progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), progress.fn) + plans, refused, err := EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), progress.fn) require.Error(t, err) for _, v := range hidden { require.False(t, v != "" && strings.Contains(err.Error(), v), "the error never shows a hidden value") } assertNoTraceValues(t, err.Error(), keys...) assert.Empty(t, planNames(plans)) + assert.Zero(t, len(refused), "the error names the refusals") assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest), "no entry is edited") assertNoForgeWrites(t, fc) - assert.Empty(t, progress.all(), "a refusal reports nothing") + assert.Empty(t, progress.all(), "a stopped run reports nothing") return err } +// entryYAML returns name's explicit manifest entry as YAML, or "" when it +// has none. +func entryYAML(t *testing.T, m *Manifest, name string) string { + t.Helper() + entry := findExplicitEntry(m, name) + if entry == nil { + return "" + } + data, err := yaml.Marshal(entry) + require.NoError(t, err) + return string(data) +} + +// refuseTrace runs the preflight, which must refuse a repository without +// stopping the run. Before any assertion that prints them, it checks that +// the error and the refusals show no non-empty value of hidden and no value +// of keys; then that no refused repository is planned, edited or reported, +// and that nothing was written. It returns the plans and the refusals' +// errors joined, for the caller's own checks. +func refuseTrace(t *testing.T, fc *forge.FakeClient, cfg TraceKeysConfig, hidden []string, keys ...traceKey) (map[string]*TraceKeyPlan, error) { + t.Helper() + before := map[string]string{} + for _, e := range cfg.Manifest.AllRepos() { + before[strings.ToLower(e.Name)] = entryYAML(t, cfg.Manifest, e.Name) + } + progress := &progressLog{} + plans, refused, err := EnsureTraceSigningKeys(context.Background(), cfg, newTestClientFactory(fc), progress.fn) + var refusals []error + for _, r := range refused { + refusals = append(refusals, r.Err) + } + shown := fmt.Sprint(errors.Join(append([]error{err}, refusals...)...)) + for _, v := range hidden { + require.False(t, v != "" && strings.Contains(shown, v), "the error never shows a hidden value") + } + assertNoTraceValues(t, shown, keys...) + require.NoError(t, err, "a refusal does not stop the run") + require.NotEmpty(t, refused, "a repository is refused") + lines := progress.all() + for _, r := range refused { + name := r.Owner + "/" + r.Repo + assert.NotContains(t, planNames(plans), name, "a refused repository gets no plan") + assert.Equal(t, before[strings.ToLower(name)], entryYAML(t, cfg.Manifest, name), "the entry of %s is not edited", name) + assert.Zero(t, countLines(lines, name+" manifest "), "a refused repository is not reported") + } + assertNoForgeWrites(t, fc) + return plans, errors.Join(refusals...) +} + // countLines returns how many lines contain every one of parts. func countLines(lines []string, parts ...string) int { n := 0 @@ -220,9 +274,10 @@ func TestEnsureTraceSigningKeys_FreshInstall(t *testing.T) { findExplicitEntry(cfg.Manifest, "acme/api").Config = mustManagedConfig(t, "roles: [triage]\n") progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, Deferred: deferred}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, Deferred: deferred}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) assert.Equal(t, []string{"acme/api", "acme/web"}, planNames(plans)) assertNoForgeWrites(t, fc) @@ -263,9 +318,10 @@ func TestEnsureTraceSigningKeys_FreshInstall(t *testing.T) { func TestEnsureTraceSigningKeys_NilProgress(t *testing.T) { fc, cfg := traceFixture(t, false, "acme/api") - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest}, newTestClientFactory(fc), nil) require.NoError(t, err) + require.Empty(t, refused) assert.Equal(t, []string{"acme/api"}, planNames(plans)) } @@ -298,9 +354,10 @@ func TestEnsureTraceSigningKeys_GlobCoveredGetsExplicitEntry(t *testing.T) { fc := newFakeClientForBatch("acme/api", "acme/web") progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, RepoFilter: []string{"acme/api"}}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, RepoFilter: []string{"acme/api"}}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) assert.Equal(t, []string{"acme/api"}, planNames(plans)) p := requireTracePlan(t, plans, "acme/api") lines := progress.all() @@ -382,9 +439,10 @@ func TestEnsureTraceSigningKeys_GitLabGetsNoKeyYet(t *testing.T) { before := manifestSnapshot(t, m) progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, Rotate: rotate}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, Rotate: rotate}, newTestClientFactory(reads), progress.fn) require.NoError(t, err) + require.Empty(t, refused) assert.Empty(t, planNames(plans)) assert.Zero(t, reads.total(), "nothing is read for a GitLab repository") assert.Equal(t, before, manifestSnapshot(t, m)) @@ -409,9 +467,10 @@ func TestEnsureTraceSigningKeys_HealthyPlansNothing(t *testing.T) { before := manifestSnapshot(t, cfg.Manifest) progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, ManifestPath: path}, + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, ManifestPath: path}, newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) assert.Empty(t, planNames(plans)) assert.Equal(t, before, manifestSnapshot(t, cfg.Manifest)) assertNoForgeWrites(t, fc) @@ -523,15 +582,26 @@ func TestEnsureTraceSigningKeys_ExistingInstallKeysOnlyWithRotate(t *testing.T) // From a read-only manifest (an HTTPS source, a remotely loaded manifest or // a local file without write permission) a fresh install without Rotate -// goes ahead without keys and names the run that provisions them. Any -// other key write needs the repos.yaml edit, so the run stops before any -// edit, prints nothing and shows no generated value. +// goes ahead without keys and names the run that provisions them. A +// recovery without Rotate needs the repos.yaml edit, so it fails that +// repository alone, and the fresh install beside it still goes ahead. Any +// key with Rotate stops the run before any edit. A refusal prints nothing +// and shows no generated value. func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { a, r := newTraceKey(1), newTraceKey(2) const url = "https://example.com/repos.yaml" healthy := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { healthyTrace(t, m, fc, "acme/api", traceBlock(traceInstallA, a, r), a) } + recovery := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + healthy(t, m, fc) + delete(fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID) + delete(fc.VariablesExist, "acme/api/"+forge.VarTraceSigningKeyID) + } + notice := func(name string) string { + return name + " manifest Trace signing keys not provisioned: repos.yaml is read-only; " + + "a later repos install " + name + " --rotate-trace-signing-key with a writable manifest provisions them" + } cases := []struct { name string // installed puts a fullsend workflow on the default branch. @@ -542,16 +612,18 @@ func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { remote bool rotate bool setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) - // skipped is a fresh install that goes ahead without keys. - skipped bool + // skipped is a fresh install that goes ahead without keys; refused + // is a repository that fails alone; web selects the fresh + // repository acme/web beside acme/api. + skipped, refused, web bool }{ {name: "fresh install from https", path: url, skipped: true}, {name: "fresh install from a remotely loaded manifest", remote: true, skipped: true}, {name: "fresh install from a file without write permission", path: readOnlyFile, skipped: true}, - {name: "recovery", installed: true, path: url, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { - healthy(t, m, fc) - delete(fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID) - delete(fc.VariablesExist, "acme/api/"+forge.VarTraceSigningKeyID) + {name: "recovery", installed: true, path: url, refused: true, setup: recovery}, + {name: "recovery beside a fresh install", path: readOnlyFile, refused: true, web: true, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + markTraceInstalled(t, fc, "acme/api") + recovery(t, m, fc) }}, {name: "rotation", installed: true, path: url, rotate: true, setup: healthy}, {name: "rotation on a remotely loaded manifest", installed: true, remote: true, rotate: true, setup: healthy}, @@ -563,7 +635,11 @@ func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fc, cfg := traceFixture(t, tc.installed, "acme/api") + names := []string{"acme/api"} + if tc.web { + names = append(names, "acme/web") + } + fc, cfg := traceFixture(t, tc.installed, names...) if tc.setup != nil { tc.setup(t, cfg.Manifest, fc) } @@ -576,7 +652,7 @@ func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { } progress := &progressLog{} - plans, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{ + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{ Manifest: cfg.Manifest, ManifestPath: path, Rotate: tc.rotate, }, newTestClientFactory(fc), progress.fn) assert.Empty(t, planNames(plans)) @@ -585,16 +661,31 @@ func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { lines := progress.all() if tc.skipped { require.NoError(t, err) + assert.Empty(t, refused) assert.Len(t, lines, 1, "one notice:\n%s", strings.Join(lines, "\n")) - assert.Equal(t, 1, countLines(lines, "acme/api manifest Trace signing keys not provisioned: repos.yaml is read-only; "+ - "a later repos install acme/api --rotate-trace-signing-key with a writable manifest provisions them"), + assert.Equal(t, 1, countLines(lines, notice("acme/api")), "the notice names the run that provisions the keys:\n%s", strings.Join(lines, "\n")) return } + if tc.refused { + require.NoError(t, err) + require.Len(t, refused, 1) + require.Equal(t, "acme/api", refused[0].Owner+"/"+refused[0].Repo) + err = refused[0].Err + } else { + assert.Empty(t, refused) + } require.ErrorIs(t, err, ErrTraceManifestReadOnly) assertNoTraceValues(t, err.Error(), a, r) assert.Contains(t, err.Error(), "acme/api") + if tc.refused { + assert.Contains(t, err.Error(), "install wrote nothing for it") + } assert.NotRegexp(t, `[0-9a-f]{16}`, err.Error(), "the error shows no installation ID and no key ID") + if tc.web { + assert.Equal(t, []string{notice("acme/web")}, lines, "the fresh install beside it goes ahead without keys") + return + } assert.Empty(t, lines, "a refusal reports nothing") }) } @@ -604,9 +695,10 @@ func TestEnsureTraceSigningKeys_ReadOnlyManifest(t *testing.T) { // permission. const readOnlyFile = "read-only file" -// A failed or invalid read refuses the run before any edit: the error -// names the repository and what was read, the fresh repository beside it -// gets no plan, and the GitLab repository beside them gets no notice. +// A failed or invalid read stops the run before any edit: the error names +// the repository and what was read, and also the run's refusals, unless the +// variable read fails for every repository. The fresh repository beside +// them gets no plan, and the GitLab repository gets no notice. func TestEnsureTraceSigningKeys_ReadErrorsRefuseBeforeAnyEdit(t *testing.T) { a := newTraceKey(1) failed := errors.New("the forge failed") @@ -638,20 +730,25 @@ func TestEnsureTraceSigningKeys_ReadErrorsRefuseBeforeAnyEdit(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fc, cfg := traceFixture(t, false, "acme/api", "acme/web") + fc, cfg := traceFixture(t, false, "acme/api", "acme/web", "acme/bad") cfg.Manifest.GitLab = testGitLabManifest("acme/lab").GitLab + setKeyIDVar(fc, "acme/bad", "not-a-key-id") tc.setup(t, cfg.Manifest, fc) - err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, []string{strings.Repeat("0", 32)}, a) + err := stopTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, []string{strings.Repeat("0", 32), "not-a-key-id"}, a) assert.Contains(t, err.Error(), tc.want) + if fc.Errors["GetRepoVariable"] == nil { + assert.Contains(t, err.Error(), forge.VarTraceSigningKeyID+" is not a key ID for acme/bad", "the error names the refusal too") + } }) } } // A FULLSEND_TRACE_SIGNING_KEY_ID that is not 16 lowercase hex characters -// stops the run before any edit with its own error, which says to delete -// the variable and never shows its value. It wins over the refusal of a -// keyless entry beside a committed block. +// refuses the repository with its own error, which says to delete the +// variable and never shows its value, and the fresh repository beside it +// gets its plan. It wins over the refusal of a keyless entry beside a +// committed block. func TestEnsureTraceSigningKeys_MalformedKeyIDVariableRefused(t *testing.T) { a := newTraceKey(1) malformed := []struct{ name, value string }{ @@ -683,7 +780,7 @@ func TestEnsureTraceSigningKeys_MalformedKeyIDVariableRefused(t *testing.T) { } setKeyIDVar(fc, "acme/api", tc.value) - err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, []string{strings.TrimSpace(tc.value)}, a) + plans, err := refuseTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest}, []string{strings.TrimSpace(tc.value)}, a) require.ErrorIs(t, err, ErrTraceKeyIDInvalid) msg := err.Error() assert.False(t, errors.Is(err, ErrTraceManifestStale), "a malformed value is not a repos.yaml mismatch") @@ -691,13 +788,14 @@ func TestEnsureTraceSigningKeys_MalformedKeyIDVariableRefused(t *testing.T) { assert.Contains(t, msg, forge.VarTraceSigningKeyID) assert.Contains(t, msg, "delete the repository variable") assert.NotContains(t, msg, "restore the entry's trace_context") + assert.Equal(t, []string{"acme/web"}, planNames(plans), "the fresh repository beside it gets its plan") }) } } // refusalRemedy ends every ErrTraceManifestStale refusal. -const refusalRemedy = "; repos.yaml and the trace keys were not changed: " + - "run install with the repos.yaml the last install wrote, or restore the entry's trace_context from it" +const refusalRemedy = "; install wrote nothing for it: " + + "restore the entry's trace_context from the repos.yaml the last install wrote" // refusal is the ErrTraceManifestStale refusal of name for reasons. func refusal(name string, reasons ...string) string { @@ -705,10 +803,10 @@ func refusal(name string, reasons ...string) string { } // An entry that contradicts the committed trace_context, the key ID -// variable or another entry stops the run before any edit, with or without -// Rotate: the error names the repository, every reason with key IDs only -// and the restore remedy, and the fresh repository beside it gets no plan. -// The committed block of an ended installation is no reason, but the other +// variable or another entry is refused, with or without Rotate: the error +// names the repository, every reason with key IDs only and the restore +// remedy, and the fresh repository beside it still gets its plan. The +// committed block of an ended installation is no reason, but the other // checks still apply. func TestEnsureTraceSigningKeys_ContradictingStateRefused(t *testing.T) { a, b, n, x, z := newTraceKey(1), newTraceKey(2), newTraceKey(4), newTraceKey(5), newTraceKey(6) @@ -808,15 +906,16 @@ func TestEnsureTraceSigningKeys_ContradictingStateRefused(t *testing.T) { } tc.setup(t, cfg.Manifest, fc) - err := refuseTrace(t, fc, TraceKeysConfig{ + plans, err := refuseTrace(t, fc, TraceKeysConfig{ Manifest: cfg.Manifest, RepoFilter: []string{"acme/api", "acme/web"}, Rotate: rotate, }, []string{tc.hidden}, a, b, n, x, z, r1, r2) require.ErrorIs(t, err, ErrTraceManifestStale) - want := refusal("acme/api", tc.reasons...) + want, wantPlans := refusal("acme/api", tc.reasons...), []string{"acme/web"} if tc.web != nil { - want += "\n" + refusal("acme/web", tc.web...) + want, wantPlans = want+"\n"+refusal("acme/web", tc.web...), nil } assert.Equal(t, want, err.Error()) + assert.Equal(t, wantPlans, planNames(plans), "a repository that is not refused gets its plan") }) } } From 79f32ea16d514890932c0ee04088a226ede075d4 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 13:48:23 -0500 Subject: [PATCH 08/12] fix(#9060): replace a recorded trace key that the secret cannot hold repos install records a new trace signing key in repos.yaml before convergence writes its seed. A run that stops a repository before its key step, at a run-level input check, at one of the repository's convergence checks or at another convergence error, leaves that key recorded without its seed, and the next run's recovery retained it. A repository that kept failing gained one retained key per attempt, and the commit that finally landed trusted every one of them. A recovery now replaces the recorded active key instead of retaining it when the secret cannot hold it: FULLSEND_TRACE_SIGNING_KEY_ID names a retained key and the committed config does not list the active key, since a key write deletes the variable before it writes the seed; or neither the variable nor the secret exists and no block of this installation is committed. Progress names the key ID it replaces. Otherwise the key stays retained: while the variable is absent and the secret exists, or after repos uninstall --uninstall-only of an install whose commit landed, install cannot tell whether the seed was written. The rule also replaces a key whose seed was written once but never committed: after --uninstall-only before the install's first commit landed, and for a hand-declared trace_context that no secret holds. The help text and docs state the rule, the failures before the key step and the growth that remains. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 64 ++++-- docs/reference/trace-context.md | 43 ++-- internal/cli/repos.go | 21 +- internal/cli/repos_trace_keys_test.go | 255 ++++++++++++++++++++- internal/repos/trace_keys.go | 35 ++- internal/repos/trace_keys_converge_test.go | 26 ++- internal/repos/trace_keys_test.go | 74 +++++- 7 files changed, 453 insertions(+), 65 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index 37f9167bdf..d82e77a3ae 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -278,9 +278,21 @@ repository that a glob covers. Some convergence input checks run only after that write: whether a selected repository uses each `--openai-api-key`, `--vertex-project`, `--vertex-wif-provider` and `--jira-*` value given, and the GCP project-number -lookup that derives a repository's WIF provider. A failure there stops the run -after `repos.yaml` recorded any new trace key, so that key's seed is never -written. The next run keeps that key as a retained key. +lookup that derives a repository's WIF provider. A failure there stops the +run. A repository can also stop after that write and before its trace key +step: at one of its own convergence checks, such as missing inference +credentials or a malformed vendor manifest, at another convergence error +before that step, or when the run is interrupted. Each of these leaves the new +trace key that `repos.yaml` recorded for a repository without its seed. The +next run replaces that key when the secret cannot hold it: when +`FULLSEND_TRACE_SIGNING_KEY_ID` names a retained key and the committed +configuration does not list the active key, or when neither the variable nor +`FULLSEND_TRACE_SIGNING_KEY` exists and no block of the installation is +committed. Otherwise it keeps that key as a retained key. So while the +variable is absent and the secret exists, or after +`repos uninstall --uninstall-only` of an install whose commit landed, each +failed run adds one retained key whose seed no one holds, and install never +removes a retained key. Legacy issue-tracking configuration in managed `config:` blocks (the scalar `tracker: github|gitlab|jira` form and the removed `create_issues` block) is @@ -700,16 +712,21 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see later runs, install writes no key while the secret exists and the variable names the active key. When the secret is missing, or the variable is missing or names a retained key, install writes a new key pair, keeps the - installation ID and moves the previous active key to `retained`. This - recovers an interrupted run, retried with the `repos.yaml` that run wrote, - and a reinstall after `repos uninstall --uninstall-only`. A repository that - install skips, such as one whose `.fullsend/config.yaml` needs adoption, - gets no key. + installation ID and moves the previous active key to `retained`. When the + secret cannot hold the previous active key, install replaces that key + instead and prints its key ID: when the variable names a retained key and + the committed configuration does not list the active key, or when neither + the variable nor the secret exists and no block of the installation is + committed. This recovers an interrupted run, retried with the `repos.yaml` + that run wrote, and a reinstall after `repos uninstall --uninstall-only`. A + repository that install skips, such as one whose `.fullsend/config.yaml` + needs adoption, gets no key. - **Rotation.** `--rotate-trace-signing-key` writes a new key pair even when - the install is healthy. The previous active key moves to `retained`. Within - an installation, install never removes a retained key. Enrolling a fully - uninstalled repository again replaces the ended installation's block, keys - included (see [`repos uninstall`](#repos-uninstall)). + the install is healthy. The previous active key moves to `retained` unless, + as above, the secret cannot hold it. Within an installation, install never + removes a retained key. Enrolling a fully uninstalled repository again + replaces the ended installation's block, keys included (see + [`repos uninstall`](#repos-uninstall)). - **Checks before any write.** Before it writes `repos.yaml` or any key, install compares each entry with the committed `.fullsend/config.yaml` and with `FULLSEND_TRACE_SIGNING_KEY_ID`. When they contradict it, install @@ -743,9 +760,10 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see key. - **Output.** Install and `--dry-run` name `FULLSEND_TRACE_SIGNING_KEY` and `FULLSEND_TRACE_SIGNING_KEY_ID`, and show the installation ID, the new key ID - and the reason (fresh install, recovery or rotation) for each new key. They - never show the seed. `--dry-run` writes nothing, and the IDs it shows belong - to keys that it discards. + and the reason (fresh install, recovery or rotation) for each new key, and + the key ID of an active key that a recovery replaces. They never show the + seed. `--dry-run` writes nothing, and the IDs it shows belong to keys that + it discards. - **Uninstall and status.** On GitHub, `repos uninstall` deletes `FULLSEND_TRACE_SIGNING_KEY` and `FULLSEND_TRACE_SIGNING_KEY_ID` (see [`repos uninstall`](#repos-uninstall)), and `repos status` counts the @@ -771,7 +789,9 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see until that merges). An entry that already declares `trace_context` by hand gets a new key pair on its first install with this release, as a recovery: install replaces `FULLSEND_TRACE_SIGNING_KEY` and moves the declared active - key to `retained`. From a read-only manifest, that repository fails. + key to `retained`, or replaces that key when neither the secret nor the + variable exists and no block of this installation is committed. From a + read-only manifest, that repository fails. ```bash fullsend repos install acme/api --rotate-trace-signing-key @@ -796,7 +816,7 @@ Install flags supply only secrets and sensitive provisioning inputs, local vendo | `--jira-email` | | Optional Jira account email written as `FULLSEND_JIRA_EMAIL` to selected repos whose effective `tracker.jira.poll.enabled` is `true`. If omitted, the existing secret is kept. Command-line only. See [Jira polling](#jira-polling). | | `--jira-client-id` | | Atlassian service account OAuth 2.0 client ID written as `FULLSEND_JIRA_CLIENT_ID`, instead of `--jira-token`, to selected repos whose effective `tracker.jira.poll.enabled` is `true`. If omitted, the existing secret is kept. Command-line only. See [Jira polling](#jira-polling). | | `--jira-client-secret` | | Atlassian service account OAuth 2.0 client secret written as `FULLSEND_JIRA_CLIENT_SECRET`, instead of `--jira-token`. If omitted, the existing secret is kept. Command-line only: never written to `repos.yaml` and never logged. See [Jira polling](#jira-polling). | -| `--rotate-trace-signing-key` | `false` | Generate a new trace signing key pair for each selected GitHub repo: write the private key as `FULLSEND_TRACE_SIGNING_KEY`, record the public key as active in `repos.yaml`, and keep the previous key as retained. On an existing install without `trace_context`, the first rotation provisions the keys. Needs a writable `repos.yaml`. GitLab repos get no key. See [Trace signing keys](#trace-signing-keys). | +| `--rotate-trace-signing-key` | `false` | Generate a new trace signing key pair for each selected GitHub repo: write the private key as `FULLSEND_TRACE_SIGNING_KEY`, record the public key as active in `repos.yaml`, and keep the previous key as retained unless the secret cannot hold it. On an existing install without `trace_context`, the first rotation provisions the keys. Needs a writable `repos.yaml`. GitLab repos get no key. See [Trace signing keys](#trace-signing-keys). | | `--fullsend-binary` | | Path to a pre-built Linux fullsend binary to upload when vendoring instead of auto-resolving it from the resolved `fullsend_ref`. Valid only when at least one selected repo resolves `vendor: true`; otherwise install fails and points at `fullsend repos set defaults.vendor true` | | `--fullsend-source` | | Path to a fullsend source checkout for vendored content and cross-compilation instead of auto-detecting or fetching from GitHub. Same `vendor: true` requirement as `--fullsend-binary` | | `--gitlab-role-registry` | | Path to administrator GitLab role registry JSON (custom roles: credential references and policy, never secret values). Written as the protected unmasked `FULLSEND_GITLAB_ROLE_REGISTRY` variable. | @@ -1785,10 +1805,12 @@ and on GitHub its `FULLSEND_TRACE_SIGNING_KEY_ID` variable. A repository without them still uninstalls. On GitHub, uninstall leaves the committed `.fullsend/config.yaml`, `trace_context` block included, in place. With `--uninstall-only`, the `repos.yaml` entry keeps its block too, so the next -install keeps the installation ID, moves the old active key to `retained` and -writes a new key pair. A fully uninstalled GitHub repository that you declare -and install again is enrolled as a new installation: from a writable manifest, -install generates a new installation ID and key pair. The uninstall counts as +install keeps the installation ID and writes a new key pair. Once a commit of +the installation's block has landed, it moves the old active key to +`retained`; before that, it replaces the old active key and prints its key ID. +A fully uninstalled GitHub repository that you declare and install again is +enrolled as a new installation: from a writable manifest, install generates a +new installation ID and key pair. The uninstall counts as finished once the repository has no fullsend workflow, `FULLSEND_TRACE_SIGNING_KEY` or `FULLSEND_TRACE_SIGNING_KEY_ID` left, so merge the uninstall pull request first. Until then, install refuses the entry. diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 2939031a03..8b69745f42 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -89,9 +89,9 @@ writes any key. Install writes a new key in this order: 1. It records the new public key as `active` in `repos.yaml` and moves the - previous active key, if any, to `retained`. When another install that uses - the same file changed it after this run loaded it, install stops before - writing it. + previous active key, if any, to `retained`, or replaces it when the secret + cannot hold it (see below). When another install that uses the same file + changed it after this run loaded it, install stops before writing it. 2. It reads `FULLSEND_TRACE_SIGNING_KEY_ID` again. If the read fails, or the variable appeared, disappeared or changed since the run first read it, as when another install or uninstall of the repository ran at the same time, @@ -116,16 +116,26 @@ active key. Install then writes no key unless you pass `--rotate-trace-signing-key`. When the variable is missing or names a retained key, the secret may not hold the active key. In that case, and when the secret is missing, the next plain `repos install` generates a new key through the -same steps and keeps the installation ID. From a read-only manifest, that run -fails the repository and writes nothing for it. +same steps and keeps the installation ID. It moves the previous active key to +`retained` unless the secret cannot hold that key: when the variable names a +retained key and the committed `.fullsend/config.yaml` does not list the +active key, since step 3 deletes the variable before step 4 writes the seed, +or when neither the variable nor the secret exists and no block of the +installation is committed. Install then replaces the key and prints its key +ID. From a read-only manifest, that run fails the repository and writes +nothing for it. Unless another install of the repository wrote a key after the run started (see step 2), a run that stopped at any step converges on a plain retry with -the `repos.yaml` it wrote. That retry keeps every trusted key: a key that the -stopped run recorded but did not confirm writing moves to `retained`. Keep and -commit that `repos.yaml` even though the run failed: after a run that stopped -at step 4 or 5, a retry from an older copy writes a new key and drops the one -the stopped run may have written, and install cannot tell (see +the `repos.yaml` it wrote. That retry keeps every key whose seed may have been +written: a key that the stopped run recorded but did not confirm writing moves +to `retained`, unless the secret cannot hold it. While the variable is absent +and the secret exists, or after `repos uninstall --uninstall-only` of an +install whose commit landed, install cannot tell whether a recorded key's seed +was written, so each run that stops before step 4 adds one more retained key. +Keep and commit that `repos.yaml` even though the run failed: after a run that +stopped at step 4 or 5, a retry from an older copy writes a new key and drops +the one the stopped run may have written, and install cannot tell (see [When install refuses an entry](#when-install-refuses-an-entry)). A seed write that failed may still have landed, for example after a timeout. @@ -229,11 +239,14 @@ On GitHub, uninstall deletes `FULLSEND_TRACE_SIGNING_KEY` and `FULLSEND_TRACE_SIGNING_KEY_ID` and leaves `.fullsend/config.yaml`, `trace_context` block included, in place. With `--uninstall-only`, the `repos.yaml` entry keeps its `trace_context` block. The next install then -keeps the installation ID, moves the old active key to `retained`, and writes -a new key pair. `--manifest-only` removes the entry and leaves the variable, -the secret, the workflow and the committed block in place. When you declare -the repository again without keys, install refuses the entry until you -restore its `trace_context` or a full uninstall finishes. +keeps the installation ID and writes a new key pair. Once a commit of the +installation's block has landed, it moves the old active key to `retained`; +before that, neither the variable nor the secret exists and no block of the +installation is committed, so it replaces the old active key and prints its +key ID. `--manifest-only` removes the entry and leaves the variable, the +secret, the workflow and the committed block in place. When you declare the +repository again without keys, install refuses the entry until you restore +its `trace_context` or a full uninstall finishes. A full uninstall also removes the repository's `repos.yaml` entry. A fully uninstalled repository that you declare and install again is enrolled again diff --git a/internal/cli/repos.go b/internal/cli/repos.go index c488e77ce6..f39d53050a 100644 --- a/internal/cli/repos.go +++ b/internal/cli/repos.go @@ -397,9 +397,10 @@ type reposInstallConfig struct { jiraClientSecret string // rotateTraceSigningKey writes a new trace signing key pair and keeps - // the previous verification key as retained (ADR 0154); on an existing - // install without trace_context the first rotation provisions the - // keys. A one-run control: never persisted. + // the previous verification key as retained unless the secret cannot + // hold it (ADR 0154); on an existing install without trace_context the + // first rotation provisions the keys. A one-run control: never + // persisted. rotateTraceSigningKey bool // GitLab-specific @@ -530,10 +531,14 @@ repos.yaml entry as config.trace_context (a repository that only a glob covers gets its own entry, copied from the glob), and writes the private seed as the FULLSEND_TRACE_SIGNING_KEY secret and its key ID as the FULLSEND_TRACE_SIGNING_KEY_ID variable. A later run writes a new pair, -keeping the installation ID and retaining the previous public key, when -the secret is missing, when that variable is missing or names a -retained key, and with --rotate-trace-signing-key, whose first use -gives an existing install its keys. From a read-only manifest a fresh +keeping the installation ID, when the secret is missing, when that +variable is missing or names a retained key, and with +--rotate-trace-signing-key, whose first use gives an existing install +its keys. It retains the previous public key, or replaces it when the +secret cannot hold that key: when the variable names a retained key and +the committed .fullsend/config.yaml does not list the active key, or +when neither the variable nor the secret exists and no block of the +installation is committed. From a read-only manifest a fresh install without --rotate-trace-signing-key goes ahead without keys, and any other key write fails that repository; with --rotate-trace-signing-key it stops the run. Output shows installation @@ -581,7 +586,7 @@ GCP infrastructure (WIF, mint) must be provisioned separately via cmd.Flags().StringVar(&opts.jiraEmail, "jira-email", "", "Jira account email written as FULLSEND_JIRA_EMAIL to selected repos whose tracker.jira.poll.enabled is true (optional); an omitted value keeps the existing secret; command-line only, never written to repos.yaml") cmd.Flags().StringVar(&opts.jiraClientID, "jira-client-id", "", "Atlassian service account OAuth 2.0 client ID written as FULLSEND_JIRA_CLIENT_ID to selected repos whose tracker.jira.poll.enabled is true, instead of --jira-token; an omitted value keeps the existing secret; command-line only, never written to repos.yaml") cmd.Flags().StringVar(&opts.jiraClientSecret, "jira-client-secret", "", "Atlassian service account OAuth 2.0 client secret written as FULLSEND_JIRA_CLIENT_SECRET to selected repos whose tracker.jira.poll.enabled is true, instead of --jira-token; an omitted value keeps the existing secret; command-line only, never written to repos.yaml and never logged") - cmd.Flags().BoolVar(&opts.rotateTraceSigningKey, "rotate-trace-signing-key", false, "generate a new trace signing key pair for each selected GitHub repo, written as FULLSEND_TRACE_SIGNING_KEY with its public key recorded in repos.yaml, and keep the previous verification key as retained; on an existing install without trace_context, the first rotation provisions the keys; needs a writable repos.yaml; GitLab repos get no key yet") + cmd.Flags().BoolVar(&opts.rotateTraceSigningKey, "rotate-trace-signing-key", false, "generate a new trace signing key pair for each selected GitHub repo, written as FULLSEND_TRACE_SIGNING_KEY with its public key recorded in repos.yaml, and keep the previous verification key as retained unless the secret cannot hold it; on an existing install without trace_context, the first rotation provisions the keys; needs a writable repos.yaml; GitLab repos get no key yet") cmd.Flags().StringVar(&opts.gitlabRoleRegistry, "gitlab-role-registry", "", "path to administrator GitLab role registry JSON (custom roles; never secret values)") cmd.Flags().StringArrayVar(&opts.gitlabRoleTokens, "gitlab-role-token", nil, "administrator-provided GitLab role PAT (repeatable, role=token); values are never logged") cmd.Flags().BoolVar(&opts.rotateGitLabRoles, "rotate-gitlab-roles", false, "force-rotate GitLab role credentials even if they are not near expiry") diff --git a/internal/cli/repos_trace_keys_test.go b/internal/cli/repos_trace_keys_test.go index 41eff7de6e..daaa7a498c 100644 --- a/internal/cli/repos_trace_keys_test.go +++ b/internal/cli/repos_trace_keys_test.go @@ -10,6 +10,7 @@ import ( "maps" "os" "regexp" + "slices" "strings" "testing" @@ -17,8 +18,10 @@ import ( "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/repos" + "github.com/fullsend-ai/fullsend/internal/scaffold" "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" ) @@ -208,7 +211,9 @@ func TestRunReposInstall_RotateTraceSigningKeyProvisionsExistingInstall(t *testi // repos.yaml records the new key before the first forge write, so a failed // seed write leaves the key recorded and the key ID variable absent. The next // plain run writes a new key and the variable names it; the installation ID -// is kept and the key that was never written stays retained. +// is kept. Neither the variable nor the secret exists and nothing is +// committed, so the secret cannot hold the recorded key: the run replaces it +// instead of retaining it, and names its key ID. func TestRunReposInstall_TraceKeyRetryAfterSecretWriteFailure(t *testing.T) { manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) fc := newInstallFakeClient("acme/api") @@ -233,7 +238,253 @@ func TestRunReposInstall_TraceKeyRetryAfterSecretWriteFailure(t *testing.T) { assert.NotEqual(t, unwritten, pub, "the retry generates a new key") assert.Equal(t, pub, traceValue(traceActiveKeyRe, second), "the written key is active") assert.Equal(t, installationID, traceValue(traceInstallationIDRe, second), "the installation ID is kept") - assert.Regexp(t, `retained:\s*-\s*["']?`+regexp.QuoteMeta(unwritten), second, "the key that was never written stays retained") + assert.NotContains(t, second, unwritten, "the key that was never written is not retained") + assert.Equal(t, 1, strings.Count(out, notRetained(verificationKeyID(t, unwritten))), "the retry names the key it replaces") +} + +// notRetained is how install names a recorded active key that it replaces +// because FULLSEND_TRACE_SIGNING_KEY cannot hold it. +func notRetained(keyID string) string { + return "(recovery); key ID " + keyID + " is not retained: " + forge.SecretTraceSigningKey + + " does not hold it and no committed config lists it" +} + +// verificationKeyID returns the key ID of a public key in standard base64, +// the form trace_context.verification_keys holds. +func verificationKeyID(t *testing.T, pub string) string { + t.Helper() + b, err := base64.StdEncoding.DecodeString(pub) + require.NoError(t, err) + require.Len(t, b, ed25519.PublicKeySize) + return hexTraceKeyID(b) +} + +// apiTrace returns acme/api's trace_context in the manifest at path, or nil. +// It holds public values only. +func apiTrace(t *testing.T, path string) *config.TraceContextConfig { + t.Helper() + m, err := repos.LoadManifest(context.Background(), path) + require.NoError(t, err) + for _, e := range m.AllRepos() { + if e.Name == "acme/api" && e.Config.Writer() != nil { + return e.Config.Writer().TraceContext() + } + } + return nil +} + +// vendorManifestKey is acme/api's .fullsend vendor manifest in the fake. A +// malformed one fails acme/api's convergence before its key step. +var vendorManifestKey = "acme/api/" + scaffold.VendorManifestPath(scaffold.PerRepoVendorPrefix) + +// installTrace runs repos install with the manifest at path against fc, +// after change edits the options, and returns its output and error. +func installTrace(t *testing.T, path string, fc *forge.FakeClient, change func(*reposInstallConfig)) (string, error) { + t.Helper() + opts := githubManagedInstallOpts(path, fc) + if change != nil { + change(opts) + } + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + return out, err +} + +// A run that stops before acme/api's key step, at a run-level input check or +// at one of acme/api's convergence checks, has already recorded a new active +// key whose seed it never writes. The next run replaces that key instead of +// retaining it: FULLSEND_TRACE_SIGNING_KEY cannot hold it, since neither the +// variable nor the secret exists and nothing is committed or, after a +// rotation, the variable still names the previous key, which the committed +// config lists without the new one. Each of two failed runs keeps the +// installation ID, records another active key and names the one it +// replaces, and the retained keys stay as they were (the previous key, after +// a rotation). A run without the cause installs, and its commit delivers the +// entry's block. +func TestRunReposInstall_TraceKeyNeverWrittenIsNotRetained(t *testing.T) { + cases := []struct { + name string + // rotate first installs acme/api, then fails its first run with + // --rotate-trace-signing-key. + rotate bool + // cause makes a run stop before acme/api's key step, with want in + // its error or output. + cause func(fc *forge.FakeClient, opts *reposInstallConfig) + want string + }{ + {name: "missing inference inputs", want: "no credentials were supplied", cause: func(_ *forge.FakeClient, opts *reposInstallConfig) { + opts.inferenceProject, opts.inferenceProjectNumber = "", "" + }}, + {name: "malformed vendor manifest", want: "parsing vendor manifest", cause: func(fc *forge.FakeClient, _ *reposInstallConfig) { + fc.FileContents[vendorManifestKey] = []byte("{not a manifest") + }}, + {name: "unused --jira-token", want: "--jira-token was supplied but no selected repository", cause: func(_ *forge.FakeClient, opts *reposInstallConfig) { + opts.jiraToken = "unused-token" + }}, + {name: "rotation, malformed vendor manifest", rotate: true, want: "parsing vendor manifest", cause: func(fc *forge.FakeClient, _ *reposInstallConfig) { + fc.FileContents[vendorManifestKey] = []byte("{not a manifest") + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + path := writeTestManifest(t, githubUnmanagedManifestYAML) + fc := newInstallFakeClient("acme/api") + var retained []string + if tc.rotate { + _, err := installTrace(t, path, fc, nil) + require.NoError(t, err, "acme/api installs") + retained = []string{apiTrace(t, path).VerificationKeys.Active} + } + + var installation, active string + commits, secrets, variables := repoWrites(fc, "acme/api") + for run := 1; run <= 2; run++ { + out, err := installTrace(t, path, fc, func(opts *reposInstallConfig) { + opts.rotateTraceSigningKey = tc.rotate && run == 1 + tc.cause(fc, opts) + }) + require.Error(t, err, "run %d fails", run) + // Neither is printed: a failed run writes no seed to check + // them against first. + require.True(t, strings.Contains(err.Error()+out, tc.want), "run %d stops at the expected check", run) + c, s, v := repoWrites(fc, "acme/api") + assert.Equal(t, []int{commits, secrets, variables}, []int{c, s, v}, "run %d writes nothing to acme/api", run) + got := apiTrace(t, path) + require.NotNil(t, got, "run %d records trace_context", run) + if run == 1 { + installation = got.InstallationID + assert.Zero(t, strings.Count(out, "is not retained"), "run 1 replaces no key") + } else { + assert.Equal(t, installation, got.InstallationID, "the installation ID is kept") + assert.NotEqual(t, active, got.VerificationKeys.Active, "run 2 records another key") + assert.Equal(t, 1, strings.Count(out, notRetained(verificationKeyID(t, active))), "run 2 names the key it replaces") + } + assert.Equal(t, retained, got.VerificationKeys.Retained, "run %d keeps the retained keys as they were", run) + active = got.VerificationKeys.Active + } + + delete(fc.FileContents, vendorManifestKey) + out, err := installTrace(t, path, fc, nil) + require.NoError(t, err, "the run without the cause installs") + manifest := mustReadFile(t, path) + overlay := fc.FileContents[overlayPath("acme/api")] + _, pub := requireTraceKeyWritten(t, fc, "acme/api", out, manifest, string(overlay)) + got := apiTrace(t, path) + assert.Equal(t, installation, got.InstallationID, "the installation ID is kept") + assert.Equal(t, pub, got.VerificationKeys.Active, "the written key is active") + assert.Equal(t, retained, got.VerificationKeys.Retained, "the retained keys are as they were") + assert.Equal(t, 1, strings.Count(out, notRetained(verificationKeyID(t, active))), "the run names the key it replaces") + committed, err := config.ParsePerRepoConfig(overlay) + require.NoError(t, err) + assert.Equal(t, got, committed.TraceContext(), "the commit delivers the entry's block") + }) + } +} + +// A recovery replaces the recorded active key only when +// FULLSEND_TRACE_SIGNING_KEY cannot hold it, so it also replaces a key whose +// seed was written once but never committed, and still retains one key per +// failed run while the secret may hold the key: +// - L2: the first rotation of an install without keys wrote its seed and +// variable, its commit did not land, and repos uninstall +// --uninstall-only deleted both; the next run replaces that key. +// - H1: a hand-declared trace_context whose key no secret holds and no +// committed config lists; the first run replaces it. +// - R1: FULLSEND_TRACE_SIGNING_KEY_ID was deleted while the secret holds +// the key; each run that stops before its key step retains one more. +// - --uninstall-only after the install's commit landed: likewise. +func TestRunReposInstall_TraceKeyRecoveryBounds(t *testing.T) { + uninstallOnly := func(t *testing.T, path string, fc *forge.FakeClient) { + t.Helper() + require.NoError(t, runReposUninstall(context.Background(), &reposUninstallConfig{ + manifest: path, yes: true, concurrency: 4, uninstallOnly: true, testClient: fc, + }, []string{"acme/api"}), "repos uninstall --uninstall-only") + } + installed := func(t *testing.T, path string, fc *forge.FakeClient) { + t.Helper() + _, err := installTrace(t, path, fc, nil) + require.NoError(t, err, "acme/api installs") + } + cases := []struct { + name string + manifest string + // existing makes acme/api an install without trace keys. + existing bool + // prepare brings acme/api to the row's state. + prepare func(t *testing.T, path string, fc *forge.FakeClient) + // failing makes two runs stop at acme/api's convergence checks; + // otherwise one run installs. + failing bool + // replaced reports that a run replaces the recorded active key + // instead of retaining it. + replaced bool + }{ + {name: "L2: first rotation written, commit not landed, then --uninstall-only", existing: true, replaced: true, + prepare: func(t *testing.T, path string, fc *forge.FakeClient) { + fc.Errors["CommitFiles"] = errors.New("commit refused") + _, err := installTrace(t, path, fc, func(opts *reposInstallConfig) { opts.rotateTraceSigningKey = true }) + require.Error(t, err, "the rotation's commit fails") + delete(fc.Errors, "CommitFiles") + requireTraceKeyWritten(t, fc, "acme/api") + uninstallOnly(t, path, fc) + }}, + {name: "H1: hand-declared key, no secret, nothing committed", replaced: true, + manifest: githubUnmanagedManifestYAML + " config:\n" + + indentLines(" ", traceContextYAML(testTraceInstallationID, forge.SecretTraceSigningKey, testTraceVerificationKey(1)))}, + {name: "R1: key ID variable deleted, secret present", failing: true, + prepare: func(t *testing.T, path string, fc *forge.FakeClient) { + installed(t, path, fc) + delete(fc.VariableValues, "acme/api/"+forge.VarTraceSigningKeyID) + delete(fc.VariablesExist, "acme/api/"+forge.VarTraceSigningKeyID) + }}, + {name: "--uninstall-only after the install's commit landed", failing: true, + prepare: func(t *testing.T, path string, fc *forge.FakeClient) { + installed(t, path, fc) + uninstallOnly(t, path, fc) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + manifest := githubUnmanagedManifestYAML + if tc.manifest != "" { + manifest = tc.manifest + } + path := writeTestManifest(t, manifest) + fc := newInstallFakeClient("acme/api") + if tc.existing { + fc = newInstalledFakeClientCLI("acme/api") + } + if tc.prepare != nil { + tc.prepare(t, path, fc) + } + runs := 1 + if tc.failing { + fc.FileContents[vendorManifestKey] = []byte("{not a manifest") + runs = 2 + } + for run := 1; run <= runs; run++ { + before := apiTrace(t, path) + require.NotNil(t, before, "acme/api's entry has trace_context") + out, err := installTrace(t, path, fc, nil) + got := apiTrace(t, path) + require.NotNil(t, got) + assert.Equal(t, before.InstallationID, got.InstallationID, "the installation ID is kept") + assert.NotEqual(t, before.VerificationKeys.Active, got.VerificationKeys.Active, "run %d records a new key", run) + if tc.replaced { + requireTraceKeyWritten(t, fc, "acme/api", out, mustReadFile(t, path)) + require.NoError(t, err) + assert.Equal(t, before.VerificationKeys.Retained, got.VerificationKeys.Retained, "the recorded key is replaced") + assert.Equal(t, 1, strings.Count(out, notRetained(verificationKeyID(t, before.VerificationKeys.Active))), "the run names the key it replaces") + continue + } + require.Error(t, err, "run %d fails", run) + require.True(t, strings.Contains(err.Error()+out, "parsing vendor manifest"), "run %d stops before the key step", run) + assert.Equal(t, append(slices.Clone(before.VerificationKeys.Retained), before.VerificationKeys.Active), got.VerificationKeys.Retained, + "run %d retains one more key", run) + assert.Zero(t, strings.Count(out, "is not retained"), "run %d replaces no key", run) + } + }) + } } // The token-scope check and the sign-off identity lookup only read, and they diff --git a/internal/repos/trace_keys.go b/internal/repos/trace_keys.go index 47011d40c8..c154c61cbe 100644 --- a/internal/repos/trace_keys.go +++ b/internal/repos/trace_keys.go @@ -105,7 +105,11 @@ var ( // installation ID) from crypto/rand, retains the previous active key, // records the block in the manifest entry (carving an explicit entry out // of a glob like EnsureManagedConfigDefaults) and returns a plan keyed -// "owner/repo". +// "owner/repo". A recovery replaces the active key instead, and progress +// names it, when the secret cannot hold it: the variable names a +// retained key and the committed config does not list the active key, +// or neither the variable nor the secret exists and no block of this +// installation is committed. // // A refused repository gets no plan, no edit and no progress line, and is // returned as a TraceKeyRefusal; the others are still planned. A read, @@ -243,8 +247,13 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo for _, t := range repos { if p := plans[t.name()]; p != nil { where := manifestEntryWhere(t.name(), t.carvedFrom) - progress(t.name(), "manifest", fmt.Sprintf("%s config.trace_context in %s: installation ID %s, new active key ID %s (%s)", - verb, where, t.next.InstallationID, tracecontext.FormatKeyID(p.Key.KeyID()), p.Reason)) + line := fmt.Sprintf("%s config.trace_context in %s: installation ID %s, new active key ID %s (%s)", + verb, where, t.next.InstallationID, tracecontext.FormatKeyID(p.Key.KeyID()), p.Reason) + if t.unwritten { + line += fmt.Sprintf("; key ID %s is not retained: %s does not hold it and no committed config lists it", + tracecontext.FormatKeyID(t.manifest.active), forge.SecretTraceSigningKey) + } + progress(t.name(), "manifest", line) } } return plans, refused, nil @@ -330,6 +339,9 @@ type traceRepo struct { // recordedKeyID is the key ID FULLSEND_TRACE_SIGNING_KEY_ID names, or // nil when the variable is absent. recordedKeyID *[8]byte + // unwritten reports a recovery whose active key the secret cannot hold, + // so provision replaces that key instead of retaining it. + unwritten bool } func (t *traceRepo) name() string { return t.rr.Owner + "/" + t.rr.Repo } @@ -439,10 +451,19 @@ func readTraceRepo(ctx context.Context, m *Manifest, clients ForgeClientFactory, } // A variable that is absent (an interrupted write, a deleted malformed // value, a torn-down install) or that names a retained key means the - // secret may not hold the active key. + // secret may not hold the active key. Recovery retains that key unless + // the secret cannot hold it, as after a run that stopped before its key + // write, or --uninstall-only before the install's first commit landed. switch { case !secretExists, !recorded, keyID != t.manifest.active: t.reason = reasonRecovery + // A key write deletes the variable before the seed, so a variable + // naming another key means the secret never held the active key, + // overlapping installs aside. With no variable, no secret and no + // committed block of this installation, it does not hold it either. + active, in := t.manifest.active, t.installed + t.unwritten = (recorded && keyID != active && (in == nil || !in.has(active, t.manifest.keys[active]))) || + (!recorded && !secretExists && (in == nil || t.ended)) case rotate: t.reason = reasonRotation } @@ -482,8 +503,8 @@ func (t *traceRepo) staleReasons() []string { } // provision generates t's new active key into t.next, keeping the -// installation ID and retaining the previous active key, or starting a -// block with a new installation ID. +// installation ID and retaining the previous active key unless t.unwritten +// replaces it, or starting a block with a new installation ID. func (t *traceRepo) provision() (tracecontext.SigningKey, error) { key, err := tracecontext.NewSigningKey(nil) if err != nil { @@ -500,7 +521,7 @@ func (t *traceRepo) provision() (tracecontext.SigningKey, error) { SigningKey: &config.TraceSigningKeyRef{Secret: config.TraceSigningKeySecret}, VerificationKeys: &config.TraceVerificationKeys{}, } - } else { + } else if !t.unwritten { t.next.VerificationKeys.Retained = append(t.next.VerificationKeys.Retained, t.next.VerificationKeys.Active) } t.next.VerificationKeys.Active = tracecontext.FormatVerificationKey(key.Public()) diff --git a/internal/repos/trace_keys_converge_test.go b/internal/repos/trace_keys_converge_test.go index 46b831b5a0..52f80fde19 100644 --- a/internal/repos/trace_keys_converge_test.go +++ b/internal/repos/trace_keys_converge_test.go @@ -350,9 +350,12 @@ type traceStepFixture struct { // forge's error echoes. After a failed or unmerged commit, which leaves the // key written, the next preflight plans nothing; while a re-enrollment's // commit has not landed, it names the ended installation once. One plain -// retry converges, keeps the installation and every trusted key, and -// delivers the entry's block; a third preflight plans nothing and names no -// ended installation. +// retry converges, keeps the installation, and delivers the entry's block. +// It replaces the stopped run's key, and names it, when the secret cannot +// hold it: the variable still names the previous key, or neither the +// variable nor the secret exists and no block of the installation is +// committed. Otherwise it keeps every trusted key. A third preflight plans +// nothing and names no ended installation. func TestTraceKeys_WriteStepFailureThenRetry(t *testing.T) { old := newTraceKey(1) fixtures := []traceStepFixture{ @@ -387,7 +390,7 @@ func TestTraceKeys_WriteStepFailureThenRetry(t *testing.T) { p := requireTracePlan(t, first, "acme/api") seed, id := p.Key.EncodeSeed(), traceKeyID(p.Key.Public()) before := manifestTrace(t, cfg.Manifest, "acme/api") - installation, eligible := before.InstallationID, traceEligible(before) + installation, eligible, retained := before.InstallationID, traceEligible(before), before.VerificationKeys.Retained oldVar, oldVarSet := keyIDVar(fc) cfg.TraceKeyPlans = first @@ -462,13 +465,26 @@ func TestTraceKeys_WriteStepFailureThenRetry(t *testing.T) { wantEnded = 1 } assert.Equal(t, wantEnded, endedLines(lines, old), "ended installation lines:\n%s", strings.Join(lines, "\n")) + // A failed seed write leaves the old seed of an existing + // install in the secret, which may then hold either key. + replaced := step == "reread" || step == "delete" || step == "seed" && !rotate + wantNamed := 0 + if replaced { + wantNamed = 1 + } + assert.Equal(t, wantNamed, countLines(lines, "(recovery)"+notRetained(id)), "the retry names the key it replaces:\n%s", strings.Join(lines, "\n")) cfg.TraceKeyPlans = second client = &traceFailClient{FakeClient: fc} convergeOK(t, client, cfg, client.land(), seed) after := manifestTrace(t, cfg.Manifest, "acme/api") assert.Equal(t, installation, after.InstallationID, "the installation is kept") assertTraceConverged(t, fc, after) - assert.Subset(t, traceEligible(after), eligible, "no key leaves the eligible set") + if replaced { + assert.NotContains(t, traceEligible(after), before.VerificationKeys.Active, "the key the secret cannot hold is replaced") + assert.Equal(t, retained, after.VerificationKeys.Retained, "the keys retained before are kept") + } else { + assert.Subset(t, traceEligible(after), eligible, "no key leaves the eligible set") + } committed, err := installedTraceContext(context.Background(), fc, "acme", "api", ForgeGitHub) require.NoError(t, err) assert.Equal(t, after, committed, "the commit delivers the entry's block") diff --git a/internal/repos/trace_keys_test.go b/internal/repos/trace_keys_test.go index 4057e36a23..948ff2b0e1 100644 --- a/internal/repos/trace_keys_test.go +++ b/internal/repos/trace_keys_test.go @@ -479,11 +479,21 @@ func TestEnsureTraceSigningKeys_HealthyPlansNothing(t *testing.T) { } } +// notRetained is how progress names a recorded active key that a recovery +// replaces because FULLSEND_TRACE_SIGNING_KEY cannot hold it. +func notRetained(keyID string) string { + return "; key ID " + keyID + " is not retained: " + forge.SecretTraceSigningKey + " does not hold it and no committed config lists it" +} + // Every unhealthy state gets a new active key as "recovery", which wins // over Rotate, and a healthy install gets one as "rotation". The -// installation ID is kept, the previous active key is retained after the -// keys retained before, and the plan carries FULLSEND_TRACE_SIGNING_KEY_ID -// as the preflight read it. +// installation ID is kept, and the plan carries +// FULLSEND_TRACE_SIGNING_KEY_ID as the preflight read it. The previous +// active key is retained after the keys retained before, unless the secret +// cannot hold it: the variable names a retained key and the committed +// config does not list the active key, or neither the variable nor the +// secret exists and no block of the installation is committed. Then the +// recovery replaces it, and progress names its key ID. func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { a, r := newTraceKey(1), newTraceKey(2) keyed := func(t *testing.T, m *Manifest, fc *forge.FakeClient) { @@ -498,18 +508,48 @@ func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { reason string // keyIDVar is the variable's value in the fixture; "" is absent. keyIDVar string + // replaced reports a recovery that replaces a instead of retaining + // it. + replaced bool setup func(t *testing.T, m *Manifest, fc *forge.FakeClient) }{ {name: "variable absent", installed: true, reason: reasonRecovery, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { keyed(t, m, fc) setTraceSecret(fc, "acme/api") }}, + // As a run that failed setting the variable leaves it: the secret + // may hold a. + {name: "variable absent, nothing committed", installed: true, reason: reasonRecovery, + setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a, r)) + setTraceSecret(fc, "acme/api") + }}, {name: "variable and secret absent", installed: true, reason: reasonRecovery, setup: keyed}, + // As a fresh install's run that stopped before its key write leaves + // it, or a hand-declared block whose key no secret holds. + {name: "variable and secret absent, nothing committed", installed: true, reason: reasonRecovery, replaced: true, + setup: func(t *testing.T, m *Manifest, _ *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a, r)) + }}, + // A rotation to a wrote the seed and the variable, then + // --uninstall-only deleted both before the commit that lists a + // landed: a's seed was live, so it stays trusted. + {name: "variable and secret absent, committed config lists only the previous key", reason: reasonRecovery, + setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a, r)) + setInstalledTrace(fc, "acme/api", traceBlock(traceInstallA, r)) + }}, {name: "secret absent", installed: true, reason: reasonRecovery, keyIDVar: a.id(), setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { keyed(t, m, fc) setKeyIDVar(fc, "acme/api", a.id()) }}, - {name: "variable names a retained key", installed: true, reason: reasonRecovery, keyIDVar: r.id(), setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + // The variable names a, so the secret held its seed. + {name: "secret absent, nothing committed", installed: true, reason: reasonRecovery, keyIDVar: a.id(), + setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + setManifestTrace(t, m, "acme/api", traceBlock(traceInstallA, a, r)) + setKeyIDVar(fc, "acme/api", a.id()) + }}, + {name: "variable names a retained key", installed: true, reason: reasonRecovery, keyIDVar: r.id(), replaced: true, setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { // A run recorded a as active, then stopped before its seed // write: the secret, the variable and the committed config // still hold r. @@ -518,6 +558,13 @@ func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { setTraceSecret(fc, "acme/api") setKeyIDVar(fc, "acme/api", r.id()) }}, + // The committed config trusts a, so its seed may have been live. + {name: "variable names a retained key, committed config lists the active key", installed: true, reason: reasonRecovery, keyIDVar: r.id(), + setup: func(t *testing.T, m *Manifest, fc *forge.FakeClient) { + keyed(t, m, fc) + setTraceSecret(fc, "acme/api") + setKeyIDVar(fc, "acme/api", r.id()) + }}, // After repos uninstall --uninstall-only on GitHub: the entry and // the committed config keep the block, and nothing else remains. {name: "after --uninstall-only", reason: reasonRecovery, setup: keyed}, @@ -534,10 +581,15 @@ func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { t.Run(fmt.Sprintf("%s/rotate=%t", tc.name, rotate), func(t *testing.T) { fc, cfg := traceFixture(t, tc.installed, "acme/api") tc.setup(t, cfg.Manifest, fc) + progress := &progressLog{} - plans, err := ensureTrace(t, fc, TraceKeysConfig{Manifest: cfg.Manifest, Rotate: rotate}) + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: cfg.Manifest, Rotate: rotate}, + newTestClientFactory(fc), progress.fn) require.NoError(t, err) + require.Empty(t, refused) p := requireTracePlan(t, plans, "acme/api") + lines := progress.all() + requireNoSeed(t, lines, p.Key.EncodeSeed()) assert.Equal(t, tc.reason, p.Reason) assert.Equal(t, tc.keyIDVar, p.KeyIDVar) assert.Equal(t, tc.keyIDVar != "", p.KeyIDVarExists) @@ -545,8 +597,16 @@ func TestEnsureTraceSigningKeys_RegeneratesKeepingInstallation(t *testing.T) { got := manifestTrace(t, cfg.Manifest, "acme/api") assert.Equal(t, traceInstallA, got.InstallationID, "the installation ID is kept") assertPlanKeyIsActive(t, p, got) - assert.Equal(t, []string{r.pubB64(), a.pubB64()}, got.VerificationKeys.Retained, - "the previous active key is retained after the earlier retained key") + line := "acme/api manifest Would persist config.trace_context in the manifest entry: installation ID " + traceInstallA + + ", new active key ID " + traceKeyID(p.Key.Public()) + " (" + tc.reason + ")" + if tc.replaced { + assert.Equal(t, []string{r.pubB64()}, got.VerificationKeys.Retained, "the active key the secret cannot hold is replaced") + line += notRetained(a.id()) + } else { + assert.Equal(t, []string{r.pubB64(), a.pubB64()}, got.VerificationKeys.Retained, + "the previous active key is retained after the earlier retained key") + } + assert.Equal(t, []string{line}, lines, "progress names the IDs, and a replaced key's ID") assertNoForgeWrites(t, fc) }) } From 202a2f5dc1faf4054c034008c6020dbe760c4305 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 14:03:54 -0500 Subject: [PATCH 09/12] docs(#9060): say when a rotated key is trusted and name every release that lacks the key ID variable On an existing install, repos install writes a new trace signing key's seed and FULLSEND_TRACE_SIGNING_KEY_ID before the commit that adds its public key to .fullsend/config.yaml is on the default branch: until the install pull request merges, also when --direct falls back to a pull request on a protected branch, and after a failed commit until a later run's commit lands. Until then the default branch's config does not list the key the secret holds, and a plain run counts the install as healthy, writes no key and delivers the commit again. The trace context reference (Writes and recovery, Rotation), the write order in the repos CLI reference and the convergence comment now say so. The write order stays. Install cannot publish the key first and switch later: the seed exists only in the run that generates it, GitHub never returns a secret's value, and v1 has one secret name. The compatibility note named v0.56.0 as the release that accepts trace_context but does not manage FULLSEND_TRACE_SIGNING_KEY_ID. v0.56.1 does the same, so the note now names the releases from v0.56.0 without this change. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 13 ++++++++----- docs/reference/trace-context.md | 19 +++++++++++++++---- internal/repos/converge.go | 4 +++- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index d82e77a3ae..a7c907dec4 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -704,7 +704,9 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see in the `FULLSEND_TRACE_SIGNING_KEY_ID` repository variable: GitHub never returns a secret's value, so the variable records which key the secret holds. Install writes `repos.yaml` before the secret and the variable, and - writes them before it commits the managed configuration. + writes them before it commits the managed configuration. On an existing + install, the default branch trusts the new key only once that commit lands, + by default when the install pull request merges. - **When install writes a key.** A fresh install, one whose fullsend workflow is not on the default branch yet, gets an installation ID and a key pair. An existing install whose entry has no `trace_context` gets none from a plain @@ -774,10 +776,11 @@ No fullsend code reads the signing key yet. For the whole lifecycle, see provision them on GitLab yet. - **Compatibility (breaking).** Fullsend v0.37.0 through v0.55.0 refuse a `repos.yaml` that contains `trace_context`, and earlier releases cannot read - this manifest format. v0.56.0 accepts it but does not manage - `FULLSEND_TRACE_SIGNING_KEY_ID`: its `repos status` reports the variable as - orphan drift, and its `repos uninstall` leaves it, after which this release - refuses the repository when you declare it again without keys, until you + this manifest format. Releases from v0.56.0 without this change + accept it but do not manage `FULLSEND_TRACE_SIGNING_KEY_ID`: their + `repos status` reports the variable as orphan drift, and their + `repos uninstall` leaves it, after which this release refuses the + repository when you declare it again without keys, until you delete the variable or restore the entry's `trace_context`. Use a release with this change for every `repos` command on that manifest. Keep and commit the `repos.yaml` edits install makes: a later install from a copy without diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 8b69745f42..4757a3e6c6 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -111,6 +111,15 @@ below). A failure in step 2 or 3 leaves it as it was or absent, and a failure in step 4 or 5 leaves it absent unless the failed step 5 write still reached GitHub. +On an existing install, step 4 changes the seed before step 6's commit +is on the default branch: until the install pull request merges, including +when `--direct` falls back to a pull request on a protected branch, and after +a failed commit until a later run's commit lands. Until then the default +branch's `.fullsend/config.yaml` does not list the key the secret holds, and +install counts the repository as healthy, so a plain run writes no key and +delivers the commit again. A fresh install has no such gap, because no +fullsend workflow is on its default branch until that commit lands. + An install is healthy when the secret exists and the variable names the active key. Install then writes no key unless you pass `--rotate-trace-signing-key`. When the variable is missing or names a retained @@ -157,10 +166,12 @@ install commit lands. `fullsend repos install --rotate-trace-signing-key` generates a new key pair. The previous active key moves to `retained`, so envelopes it signed still -verify. Envelopes carry no timestamp, so a retained key stays trusted. Within -an installation, install never removes a retained key. Enrolling a fully -uninstalled repository again replaces the ended installation's block, keys -included (see [Uninstall](#uninstall)). +verify. Envelopes carry no timestamp, so a retained key stays trusted. The new +key is trusted once the install commit is on the default branch (see +[Writes and recovery](#writes-and-recovery)). Within an installation, install +never removes a retained key. Enrolling a fully uninstalled repository again +replaces the ended installation's block, keys included (see +[Uninstall](#uninstall)). ### When install refuses an entry diff --git a/internal/repos/converge.go b/internal/repos/converge.go index 1ad3695f9c..57afc559aa 100644 --- a/internal/repos/converge.go +++ b/internal/repos/converge.go @@ -1957,7 +1957,9 @@ func convergeRepo(ctx context.Context, cr.Actions = append(cr.Actions, convergeJiraPoll(ctx, d, cfg, jiraDelivery, progress)...) // 2d'': The trace signing key (ADR 0154), before the commit that delivers - // the config naming it. A failure stops the repository here. + // the config naming it. A failure stops the repository here. Until that + // commit is on the default branch, the default branch's config does not + // list the key the secret holds. traceActions := convergeTraceSigningKey(ctx, d, cfg, progress) cr.Actions = append(cr.Actions, traceActions...) if actionsError(traceActions) != nil { From 72f95e5a80bf069e680f3c20f05c38037f8a1c95 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 16:01:54 -0500 Subject: [PATCH 10/12] fix(#9060): copy the glob entry that selected a repository when recording its trace keys Install selects a glob-covered repository with filepath.Match, which is case-sensitive, and takes the first matching glob in manifest order. The trace key step then carved the repository's own entry from the first glob that matches ignoring case. With acme/A* listed before acme/api*, acme/api, selected through acme/api*, got a copy of acme/A*, so recording its keys could change its fullsend_ref, roles or kill_switch, and the proposed-configuration safety check allows that relaxation because the copied value is declared explicitly. Glob expansion now records the glob entry that selected each repository, and the key step copies that entry. A repository selected by name that expansion does not list, such as a fork, still gets the first glob that covers it ignoring case, as its selection does. The first-install tracker default and ResolveConfigWithGlobs still match ignoring case, as in released versions. Install resolved the sign-off identities and the --fullsend-binary and --fullsend-source check before that edit, through the first glob that matches ignoring case. A repository whose copied entry differs could then fail at its scaffold commit, after its trace key and repos.yaml were written, or have those flags refused or silently ignored. Install now resolves both from the edited manifest, after the manifest edits and before the repos.yaml write, so a failure still leaves repos.yaml and the keys unwritten. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 8 +- internal/cli/repos.go | 57 ++++---- internal/cli/repos_test.go | 7 +- internal/cli/repos_trace_keys_test.go | 161 ++++++++++++++++++++- internal/repos/managed_config_writeback.go | 4 +- internal/repos/manifest.go | 7 + internal/repos/manifest_edit.go | 27 ++-- internal/repos/manifest_signoff_test.go | 2 +- internal/repos/trace_keys.go | 4 +- internal/repos/trace_keys_test.go | 19 ++- 10 files changed, 243 insertions(+), 53 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index a7c907dec4..2f27ebcc3d 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -256,14 +256,18 @@ so a run they stop leaves `repos.yaml` unchanged: - the command-line flags, the manifest and the repository selection; - the existing configuration layers: an undeclared base stops the run, and a repository that needs adoption is skipped; -- the token's scopes and the sign-off identity; +- the token's scopes; - the [trace signing keys](#trace-signing-keys): a repository whose keys install refuses, or whose recovery a read-only manifest cannot record, is skipped, and `--rotate-trace-signing-key` with a read-only manifest stops the run; - a read-only manifest that must record the `tracker` default; - the proposed configuration, against the installed layers and against the - effective infrastructure. + effective infrastructure; +- the sign-off identity, and the check that a selected repository resolves + `vendor: true` when `--fullsend-binary` or `--fullsend-source` is given: + install resolves both from the edited manifest, because a new entry copied + from a glob takes that glob's settings. Install also stops before that write when the file changed after the run loaded it, as when another install that uses the same file runs at the same diff --git a/internal/cli/repos.go b/internal/cli/repos.go index f39d53050a..a4f99ac772 100644 --- a/internal/cli/repos.go +++ b/internal/cli/repos.go @@ -684,19 +684,6 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { if err := requireDeclaredSelections(manifest, opts.repoFilter); err != nil { return err } - if opts.fullsendBinary != "" || opts.fullsendSource != "" { - vendored, vendorErr := manifest.VendorSelected(opts.repoFilter) - if vendorErr != nil { - return fmt.Errorf("resolving vendor settings: %w", vendorErr) - } - if !vendored { - flag := "--fullsend-binary" - if opts.fullsendBinary == "" { - flag = "--fullsend-source" - } - return fmt.Errorf("%s is only used for repositories whose repos.yaml settings resolve vendor: true, and no selected repository does; enable vendoring in repos.yaml, for example:\n fullsend repos set defaults.vendor true", flag) - } - } var clients repos.ForgeClientFactory switch { @@ -804,12 +791,11 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { }) } - // The token-scope check and the sign-off identity lookup only read, so - // they run before install plans any manifest edit: a failure leaves - // repos.yaml unchanged instead of recording a trace key whose seed is - // never written (ADR 0154). The manifest edits below carve glob-covered - // repositories into entries copied from their globs, so they change - // neither the targeted forges nor the sign-off settings. + // The token-scope check only reads, so it runs before install plans any + // manifest edit: a failure leaves repos.yaml unchanged instead of + // recording a trace key whose seed is never written (ADR 0154). The + // manifest edits below carve glob-covered repositories into entries + // copied from their globs, so they do not change the targeted forges. targetedForges, err := manifest.DistinctForgesFor(opts.repoFilter) if err != nil { return fmt.Errorf("determining targeted forges: %w", err) @@ -818,15 +804,6 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { return err } - // Signoff comes from the manifest settings. Trailers are resolved once - // per forge before convergence (including dry runs) so a missing - // identity fails before any scaffold commit is made. - signOffTrailers, err := resolveRepoSignOffTrailers(ctx, clients, printer, manifest, - opts.repoFilter, opts.dryRun) - if err != nil { - return err - } - // Install plans its manifest edits below in memory: the initial // tracking writeback and the trace_context of fresh installs, // recoveries and rotations (ADR 0154). Their progress output is held @@ -922,6 +899,30 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { if err := repos.PreflightEffectiveInfrastructure(ctx, manifest, preflightClients, opts.repoFilter, skipped, opts.inferenceProject, opts.inferenceWIFProvider); err != nil { return fmt.Errorf("effective infrastructure preflight: %w", err) } + // Whether --fullsend-binary and --fullsend-source apply, and which forges + // need a sign-off identity, come from the manifest settings. Both are + // resolved here (including dry runs), from the edited manifest, since a + // new entry copied from a glob takes that glob's settings, so a refused + // flag or a missing identity fails before repos.yaml or any key is + // written. Trailers are resolved once per forge before convergence. + if opts.fullsendBinary != "" || opts.fullsendSource != "" { + vendored, vendorErr := manifest.VendorSelected(opts.repoFilter) + if vendorErr != nil { + return fmt.Errorf("resolving vendor settings: %w", vendorErr) + } + if !vendored { + flag := "--fullsend-binary" + if opts.fullsendBinary == "" { + flag = "--fullsend-source" + } + return fmt.Errorf("%s is only used for repositories whose repos.yaml settings resolve vendor: true, and no selected repository does; enable vendoring in repos.yaml, for example:\n fullsend repos set defaults.vendor true", flag) + } + } + signOffTrailers, err := resolveRepoSignOffTrailers(ctx, clients, printer, manifest, + opts.repoFilter, opts.dryRun) + if err != nil { + return err + } // A dry run reports the size refusal that the write below gives. if manifestChanged && opts.dryRun && opts.manifest != "" { if err := repos.CheckManifestSize(opts.manifest, manifest); err != nil { diff --git a/internal/cli/repos_test.go b/internal/cli/repos_test.go index 440bbe3a87..810fb6b2d5 100644 --- a/internal/cli/repos_test.go +++ b/internal/cli/repos_test.go @@ -1154,7 +1154,12 @@ func TestReposInstallCmd_FullsendBinarySourceFlags(t *testing.T) { assert.Equal(t, "", sourceFlag.DefValue) } +// Install checks the vendoring flags after its forge reads, so this command +// test selects no repository: the run reaches the check without the forge, +// and the token stub makes any forge access fail instead of using the host's +// credentials. func TestReposInstallCmd_VendorArtifactsWithoutDeclaredVendor(t *testing.T) { + stubMissingGitHubToken(t) for _, flag := range []string{"--fullsend-binary", "--fullsend-source"} { t.Run(flag, func(t *testing.T) { cmd := newRootCmd() @@ -1162,7 +1167,7 @@ func TestReposInstallCmd_VendorArtifactsWithoutDeclaredVendor(t *testing.T) { cmd.SetErr(io.Discard) cmd.SetArgs([]string{ "repos", "install", - "--manifest", writeTestManifest(t, testManifestYAML), + "--manifest", writeTestManifest(t, emptyReposManifestYAML), flag, "/tmp/fullsend", }) err := cmd.Execute() diff --git a/internal/cli/repos_trace_keys_test.go b/internal/cli/repos_trace_keys_test.go index daaa7a498c..85a937a259 100644 --- a/internal/cli/repos_trace_keys_test.go +++ b/internal/cli/repos_trace_keys_test.go @@ -1,6 +1,7 @@ package cli import ( + "bytes" "context" "crypto/ed25519" "encoding/base64" @@ -20,6 +21,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/layers" "github.com/fullsend-ai/fullsend/internal/repos" "github.com/fullsend-ai/fullsend/internal/scaffold" "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" @@ -208,6 +210,159 @@ func TestRunReposInstall_RotateTraceSigningKeyProvisionsExistingInstall(t *testi } } +// The first --rotate-trace-signing-key run of an existing install that a +// glob covers gives it a repos.yaml entry copied from the glob entry that +// selected it. Selection matches a glob case-sensitively, so acme/A*, listed +// first, covers acme/api only when case is ignored and does not select it: +// the entry copies acme/api*, and the commit keeps the committed kill_switch. +func TestRunReposInstall_FirstRotationCopiesTheGlobThatSelectedTheRepo(t *testing.T) { + manifestPath := writeTestManifest(t, `version: 1 +github: + mint_url: https://mint.example.com + fullsend_ref: v1.0.0 + inference: + auth: vertex-wif + repos: + - name: acme/A* + config: + kill_switch: false + - name: acme/api* + config: + kill_switch: true +`) + fc := newInstalledFakeClientCLI("acme/api") + fc.FileContents[overlayPath("acme/api")] = []byte(managedConfigMarker + "kill_switch: true\n") + opts := githubManagedInstallOpts(manifestPath, fc) + opts.rotateTraceSigningKey = true + var err error + out := captureStdout(t, func() { err = runReposInstall(context.Background(), opts) }) + require.NoError(t, err) + + manifest := mustReadFile(t, manifestPath) + overlay := string(fc.FileContents[overlayPath("acme/api")]) + keyID, _ := requireTraceKeyWritten(t, fc, "acme/api", out, manifest, overlay) + assert.Contains(t, out, "[acme/api] Persisted config.trace_context in the new manifest entry acme/api, copied from the glob entry acme/api*: "+ + "installation ID "+traceValue(traceInstallationIDRe, manifest)+", new active key ID "+keyID+" (rotation)") + assert.Contains(t, manifestEntryYAML(t, manifestPath, "acme/api"), "kill_switch: true", "the new entry copies acme/api*") + assert.Contains(t, overlay, "kill_switch: true", "the commit keeps the committed kill_switch") + assert.NotContains(t, overlay, "kill_switch: false") +} + +// Install resolves the sign-off identity from the edited manifest, so a +// glob-covered repository's scaffold commit follows the signoff of its new +// entry, which install copies from the glob entry that selected it. acme/A*, +// listed first, covers acme/api only when case is ignored and does not +// select it: the entry copies acme/api*. A dry run reports the trailer the +// install adds. +func TestRunReposInstall_SignoffFollowsTheCopiedEntry(t *testing.T) { + const signoff = " signoff: true\n" + globs := func(upper, lower string) string { + return strings.TrimSuffix(githubUnmanagedManifestYAML, " - name: acme/api\n") + + " - name: acme/A*\n" + upper + " - name: acme/api*\n" + lower + } + cases := []struct { + name, manifest string + // installed makes acme/api an existing install, run with + // --rotate-trace-signing-key. + installed, dryRun bool + // signed reports that the scaffold commit carries the trailer. + signed bool + }{ + {name: "fresh install", manifest: globs("", signoff), signed: true}, + {name: "first rotation of an existing install", manifest: globs("", signoff), installed: true, signed: true}, + {name: "signoff only on the glob that does not select it", manifest: globs(signoff, "")}, + {name: "dry run of the fresh install", manifest: globs("", signoff), dryRun: true, signed: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + manifestPath := writeTestManifest(t, tc.manifest) + fc := newInstallFakeClient("acme/api") + if tc.installed { + fc = newInstalledFakeClientCLI("acme/api") + } + fc.AuthenticatedUserIdentity = &forge.UserIdentity{Name: "Install User", Email: "install@example.com"} + out, err := installTrace(t, manifestPath, fc, func(opts *reposInstallConfig) { + opts.rotateTraceSigningKey = tc.installed + opts.dryRun = tc.dryRun + }) + assert.Empty(t, regexp.MustCompile(`FAILED: .*`).FindAllString(out, -1), "no repository fails") + require.NoError(t, err) + assert.Contains(t, regexp.MustCompile(`Install complete: .*`).FindString(out), ", 0 failed") + if tc.dryRun { + assert.Equal(t, "Would add trailer to GitHub scaffold commits: "+signoffTestTrailer, + regexp.MustCompile(`Would add trailer to .*`).FindString(out)) + assert.Empty(t, scaffoldCommitMessages(fc), "a dry run commits nothing") + return + } + if tc.signed { + requireAllSignedOff(t, fc) + } else { + requireNoneSignedOff(t, fc) + } + requireTraceKeyWritten(t, fc, "acme/api", out, mustReadFile(t, manifestPath), string(fc.FileContents[overlayPath("acme/api")])) + }) + } +} + +// Install checks --fullsend-binary against the edited manifest, so the flag +// follows the vendor setting of a glob-covered repository's new entry, which +// install copies from the glob entry that selected it. acme/A*, listed first, +// covers acme/api only when case is ignored and does not select it: the +// entry copies acme/api*. A refusal stops the run before repos.yaml, a key or +// a commit is written, and a dry run gives the install's answer. +func TestRunReposInstall_VendorFlagsFollowTheCopiedEntry(t *testing.T) { + const vendor = " vendor: true\n" + globs := func(upper, lower string) string { + return strings.TrimSuffix(githubUnmanagedManifestYAML, " - name: acme/api\n") + + " - name: acme/A*\n" + upper + " - name: acme/api*\n" + lower + } + cases := []struct { + name, manifest string + dryRun bool + // refused reports that install refuses --fullsend-binary. + refused bool + }{ + {name: "vendor only on the glob that selects it", manifest: globs("", vendor)}, + {name: "vendor only on the glob that does not select it", manifest: globs(vendor, ""), refused: true}, + {name: "dry run with vendor only on the glob that selects it", manifest: globs("", vendor), dryRun: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + manifestPath := writeTestManifest(t, tc.manifest) + fc := newInstallFakeClient("acme/api") + out, err := installTrace(t, manifestPath, fc, func(opts *reposInstallConfig) { + opts.repoFilter = []string{"acme/api"} + opts.fullsendBinary = amd64VendorBinary(t) + opts.dryRun = tc.dryRun + }) + // The checks on out never print it whole. + if tc.refused { + require.Error(t, err) + assert.Contains(t, err.Error(), "--fullsend-binary is only used for repositories whose repos.yaml settings resolve vendor: true, and no selected repository does") + assert.True(t, mustReadFile(t, manifestPath) == tc.manifest, "repos.yaml is byte-identical") + assert.False(t, strings.Contains(out, "Persisted"), "the run reports no repos.yaml edit") + assertNoInstallWrites(t, fc) + return + } + require.NoError(t, err) + assert.Contains(t, regexp.MustCompile(`Install complete: .*`).FindString(out), ", 0 failed") + if tc.dryRun { + assert.True(t, strings.Contains(out, "[acme/api] Would persist config.trace_context in the new manifest entry acme/api, copied from the glob entry acme/api*: "), + "the dry run reports the entry copied from acme/api*") + assert.True(t, mustReadFile(t, manifestPath) == tc.manifest, "a dry run leaves repos.yaml unchanged") + assertNoInstallWrites(t, fc) + return + } + requireTraceKeyWritten(t, fc, "acme/api", out, mustReadFile(t, manifestPath)) + assert.True(t, strings.Contains(out, "[acme/api] Persisted config.trace_context in the new manifest entry acme/api, copied from the glob entry acme/api*: "), + "the install reports the entry copied from acme/api*") + assert.Contains(t, manifestEntryYAML(t, manifestPath, "acme/api"), "vendor: true", "the new entry copies acme/api*") + assert.True(t, bytes.Equal(fc.FileContents["acme/api/"+layers.VendoredBinaryPathPerRepo], minimalLinuxAmd64ELF), + "the scaffold commit carries the vendored binary") + }) + } +} + // repos.yaml records the new key before the first forge write, so a failed // seed write leaves the key recorded and the key ID variable absent. The next // plain run writes a new key and the variable names it; the installation ID @@ -488,9 +643,9 @@ func TestRunReposInstall_TraceKeyRecoveryBounds(t *testing.T) { } // The token-scope check and the sign-off identity lookup only read, and they -// run before install plans any repos.yaml edit: when either fails, repos.yaml -// stays byte-identical, so it records no trace_context for a key that was -// never written, and nothing is written to the forge. +// run before install writes repos.yaml: when either fails, repos.yaml stays +// byte-identical, so it records no trace_context for a key that was never +// written, and nothing is written to the forge. func TestRunReposInstall_ScopeOrIdentityFailureLeavesManifestUnchanged(t *testing.T) { cases := []struct { name, manifest, want string diff --git a/internal/repos/managed_config_writeback.go b/internal/repos/managed_config_writeback.go index f4d6211eec..15e7a17edf 100644 --- a/internal/repos/managed_config_writeback.go +++ b/internal/repos/managed_config_writeback.go @@ -403,7 +403,7 @@ func EnsureManagedConfigDefaults(ctx context.Context, cfg ManagedConfigWriteback entry := findExplicitEntry(m, name) if entry == nil { needsNewEntry[name] = true - carved, glob, err := carveOutForForge(m, name, p.rr.Forge) + carved, glob, err := carveOutForForge(m, name, p.rr.Forge, "") if err != nil { return nil, fmt.Errorf("%s: %w", name, err) } @@ -558,7 +558,7 @@ func newEntrySuggestion(m *Manifest, p pendingWriteback) RepoEntry { entry = *existing } else if platform := m.PlatformFor(p.rr.Forge); platform != nil { scratch := &PlatformConfig{Repos: slices.Clone(platform.Repos)} - if carved, _, _ := carveOutGlobEntry([]*PlatformConfig{scratch}, name); carved != nil { + if carved, _, _ := carveOutGlobEntry([]*PlatformConfig{scratch}, name, ""); carved != nil { entry = *carved } } diff --git a/internal/repos/manifest.go b/internal/repos/manifest.go index 927c4e1c4f..9c39b43bfe 100644 --- a/internal/repos/manifest.go +++ b/internal/repos/manifest.go @@ -282,6 +282,12 @@ type ResolvedRepo struct { Repo string Forge string Entry RepoEntry + // glob names the glob entry that selected the repository in glob + // expansion, such as "acme/api*", and is empty otherwise. For a concrete + // selection that expansion missed, lookupManifestEntry finds the + // covering glob the way carveOutForForge does: ignoring case, the first + // in its forge section. + glob string } // ResolvedConfig is the fully resolved configuration for a single @@ -1203,6 +1209,7 @@ func (m *Manifest) ExpandGlobsFor(ctx context.Context, clients ForgeClientFactor Repo: repo.Name, Forge: p.name, Entry: entry, + glob: g.entry.Name, } } } diff --git a/internal/repos/manifest_edit.go b/internal/repos/manifest_edit.go index 7b73c50f7a..36c34858dd 100644 --- a/internal/repos/manifest_edit.go +++ b/internal/repos/manifest_edit.go @@ -27,9 +27,10 @@ type ManifestRemoveResult struct { // carveOutForForge carves an explicit entry for name from the covering glob // in the discovered forge section, or from the first covering glob across -// forges (GitHub before GitLab) when discovered is empty. It returns the new -// entry and the name of the glob entry it was copied from. -func carveOutForForge(m *Manifest, name, discovered string) (*RepoEntry, string, error) { +// forges (GitHub before GitLab) when discovered is empty; a non-empty glob +// names the glob entry to copy instead. It returns the new entry and the +// name of the glob entry it was copied from. +func carveOutForForge(m *Manifest, name, discovered, glob string) (*RepoEntry, string, error) { order := []string{ForgeGitHub, ForgeGitLab} if discovered != "" { order = []string{discovered} @@ -39,12 +40,12 @@ func carveOutForForge(m *Manifest, name, discovered string) (*RepoEntry, string, if platform == nil { continue } - carved, glob, err := carveOutGlobEntry([]*PlatformConfig{platform}, name) + carved, from, err := carveOutGlobEntry([]*PlatformConfig{platform}, name, glob) if err != nil { return nil, "", err } if carved != nil { - return carved, glob, nil + return carved, from, nil } } return nil, "", nil @@ -63,9 +64,10 @@ func manifestEntryWhere(name, glob string) string { // carveOutGlobEntry appends an explicit entry for name copied from the first // glob entry (GitHub before GitLab, matching resolution order) that covers -// it, and returns a pointer to the new entry and the glob entry's name. It -// returns nil when no glob covers name. -func carveOutGlobEntry(platforms []*PlatformConfig, name string) (*RepoEntry, string, error) { +// it ignoring case, or from the glob entry named glob when glob is not +// empty, and returns a pointer to the new entry and the glob entry's name. +// It returns nil when there is no such glob entry. +func carveOutGlobEntry(platforms []*PlatformConfig, name, glob string) (*RepoEntry, string, error) { for _, platform := range platforms { if platform == nil { continue @@ -74,9 +76,12 @@ func carveOutGlobEntry(platforms []*PlatformConfig, name string) (*RepoEntry, st if !isGlob(entry.Name) { continue } - ok, err := matchesPattern(entry.Name, name) - if err != nil { - return nil, "", fmt.Errorf("invalid manifest repo pattern %q: %w", entry.Name, err) + ok := entry.Name == glob + if glob == "" { + var err error + if ok, err = matchesPattern(entry.Name, name); err != nil { + return nil, "", fmt.Errorf("invalid manifest repo pattern %q: %w", entry.Name, err) + } } if !ok { continue diff --git a/internal/repos/manifest_signoff_test.go b/internal/repos/manifest_signoff_test.go index 678cc34912..70ed0a5fa2 100644 --- a/internal/repos/manifest_signoff_test.go +++ b/internal/repos/manifest_signoff_test.go @@ -265,7 +265,7 @@ func TestCarveOutGlobEntry_CopiesSignoff(t *testing.T) { signoff := true platform := &PlatformConfig{Repos: []RepoEntry{{Name: "acme/*", Signoff: &signoff}}} - carved, _, err := carveOutGlobEntry([]*PlatformConfig{platform}, "acme/api") + carved, _, err := carveOutGlobEntry([]*PlatformConfig{platform}, "acme/api", "") require.NoError(t, err) require.NotNil(t, carved) require.NotNil(t, carved.Signoff) diff --git a/internal/repos/trace_keys.go b/internal/repos/trace_keys.go index c154c61cbe..b7dd64fc1d 100644 --- a/internal/repos/trace_keys.go +++ b/internal/repos/trace_keys.go @@ -104,7 +104,7 @@ var ( // - otherwise generates a key (and, for an entry without keys, an // installation ID) from crypto/rand, retains the previous active key, // records the block in the manifest entry (carving an explicit entry out -// of a glob like EnsureManagedConfigDefaults) and returns a plan keyed +// of the glob that selected the repository) and returns a plan keyed // "owner/repo". A recovery replaces the active key instead, and progress // names it, when the secret cannot hold it: the variable names a // retained key and the committed config does not list the active key, @@ -225,7 +225,7 @@ func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients Fo plans[t.name()] = p entry := findExplicitEntry(m, t.name()) if entry == nil { - carved, glob, err := carveOutForForge(m, t.name(), t.rr.Forge) + carved, glob, err := carveOutForForge(m, t.name(), t.rr.Forge, t.rr.glob) if err != nil { return nil, nil, fmt.Errorf("%s: %w", t.name(), err) } diff --git a/internal/repos/trace_keys_test.go b/internal/repos/trace_keys_test.go index 948ff2b0e1..692082f5dc 100644 --- a/internal/repos/trace_keys_test.go +++ b/internal/repos/trace_keys_test.go @@ -326,9 +326,9 @@ func TestEnsureTraceSigningKeys_NilProgress(t *testing.T) { } // A repository that only a glob covers gets its own GitHub entry, copied -// from the first glob entry that covers it, and progress names that entry -// and that glob, since later edits to the glob no longer reach it; the globs -// and the repositories the run does not select are unchanged. +// from the glob entry that selected it, and progress names that entry and +// that glob, since later edits to the glob no longer reach it; the globs and +// the repositories the run does not select are unchanged. func TestEnsureTraceSigningKeys_GlobCoveredGetsExplicitEntry(t *testing.T) { glob := func(name, ref, role string) RepoEntry { return RepoEntry{Name: name, FullsendRef: ref, Config: mustManagedConfig(t, "roles: ["+role+"]\n")} @@ -336,6 +336,8 @@ func TestEnsureTraceSigningKeys_GlobCoveredGetsExplicitEntry(t *testing.T) { cases := []struct { name string globs []RepoEntry + // fork leaves acme/api out of the org listing. + fork bool // copied is the glob entry acme/api's entry is copied from. copied string }{ @@ -345,6 +347,16 @@ func TestEnsureTraceSigningKeys_GlobCoveredGetsExplicitEntry(t *testing.T) { {name: "first covering glob", globs: []RepoEntry{ glob("acme/w*", "v0.0.1", "coder"), glob("acme/a*", "v1.2.3", "triage"), glob("acme/*", "v9.9.9", "coder"), }, copied: "acme/a*"}, + // Selection matches a glob case-sensitively, so acme/A* covers + // acme/api only when case is ignored and does not select it. + {name: "glob that selected it", globs: []RepoEntry{ + glob("acme/A*", "v9.9.9", "coder"), glob("acme/api*", "v1.2.3", "triage"), + }, copied: "acme/api*"}, + // A fork is selected by name, through the first glob that covers + // it ignoring case, and its entry is copied from that glob. + {name: "fork selected by name", globs: []RepoEntry{ + glob("acme/A*", "v1.2.3", "triage"), glob("acme/api*", "v9.9.9", "coder"), + }, fork: true, copied: "acme/A*"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -352,6 +364,7 @@ func TestEnsureTraceSigningKeys_GlobCoveredGetsExplicitEntry(t *testing.T) { MintURL: "https://mint.example.com", Repos: slices.Clone(tc.globs), }} fc := newFakeClientForBatch("acme/api", "acme/web") + fc.Repos[0].Fork = tc.fork progress := &progressLog{} plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{Manifest: m, RepoFilter: []string{"acme/api"}}, From 91a77e07ddc0503cb646abfd2c880a67368f4bb1 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 16 Nov 2026 19:21:05 -0500 Subject: [PATCH 11/12] fix(#9060): leave repositories install skips out of the sign-off identity lookup A repository whose trace keys install refuses, that needs adoption, or whose GitLab trigger-account containment failed gets no scaffold commit, but SignoffForgesFor still counted it. With a token that has no user identity, such as a GitHub App installation token, such a repository with signoff enabled stopped the whole run at the identity lookup, before any other repository converged. Install now passes the repositories that convergence leaves out, and SignoffForgesFor leaves out an explicit entry or a concrete filter name among them. A glob entry still counts, since it may select other repositories. The --fullsend-binary and --fullsend-source check still counts a skipped repository: the flags are accepted, the other repositories converge, and the skipped one is listed as FAILED. Signed-off-by: Dharit Shah --- docs/cli/repos.md | 5 +- internal/cli/repos.go | 10 ++-- .../cli/repos_gitlab_dispatch_route_test.go | 27 ++++++++++ internal/cli/repos_trace_keys_test.go | 5 ++ internal/repos/manifest.go | 25 +++++++++- internal/repos/manifest_signoff_test.go | 49 +++++++++++++++++-- 6 files changed, 108 insertions(+), 13 deletions(-) diff --git a/docs/cli/repos.md b/docs/cli/repos.md index 2f27ebcc3d..95cdc33c06 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -267,7 +267,8 @@ so a run they stop leaves `repos.yaml` unchanged: - the sign-off identity, and the check that a selected repository resolves `vendor: true` when `--fullsend-binary` or `--fullsend-source` is given: install resolves both from the edited manifest, because a new entry copied - from a glob takes that glob's settings. + from a glob takes that glob's settings. A repository install skips needs no + sign-off identity. Install also stops before that write when the file changed after the run loaded it, as when another install that uses the same file runs at the same @@ -374,7 +375,7 @@ gitlab: A repo entry (or the glob entry that matches the repo) takes precedence over its forge section (`github` or `gitlab`), which takes precedence over `defaults`. Signoff is off when no level sets it. There is no command-line override: the former `--signoff` flag was removed, so set the level you want with, for example, `fullsend repos set defaults.signoff true`. -When signoff is enabled for any selected repo, the identity is resolved once per forge before anything is committed. A missing identity, such as a GitHub App installation token that cannot read `/user`, or an identity without a name or email fails the install before any scaffold commit is made. `--dry-run` runs the same identity check and reports the trailer that would be added. When signoff is disabled, no trailer is added and no identity lookup is made. Uninstall commits (file deletions) do not add a trailer. +When signoff is enabled for any selected repo, the identity is resolved once per forge before anything is committed. A repo that install skips, such as one that needs adoption or whose trace signing keys it refuses, gets no commit, so its signoff setting needs no identity, unless a glob entry with signoff may also select other repos. A missing identity, such as a GitHub App installation token that cannot read `/user`, or an identity without a name or email fails the install before any scaffold commit is made. `--dry-run` runs the same identity check and reports the trailer that would be added. When signoff is disabled, no trailer is added and no identity lookup is made. Uninstall commits (file deletions) do not add a trailer. ### Signed commits diff --git a/internal/cli/repos.go b/internal/cli/repos.go index a4f99ac772..d086f04a04 100644 --- a/internal/cli/repos.go +++ b/internal/cli/repos.go @@ -904,7 +904,9 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { // resolved here (including dry runs), from the edited manifest, since a // new entry copied from a glob takes that glob's settings, so a refused // flag or a missing identity fails before repos.yaml or any key is - // written. Trailers are resolved once per forge before convergence. + // written. Trailers are resolved once per forge before convergence, and + // a repository convergence leaves out gets no commit, so it needs no + // identity. if opts.fullsendBinary != "" || opts.fullsendSource != "" { vendored, vendorErr := manifest.VendorSelected(opts.repoFilter) if vendorErr != nil { @@ -919,7 +921,7 @@ func runReposInstall(ctx context.Context, opts *reposInstallConfig) error { } } signOffTrailers, err := resolveRepoSignOffTrailers(ctx, clients, printer, manifest, - opts.repoFilter, opts.dryRun) + opts.repoFilter, append(containFailedKeys(containFailedRepos), skipped...), opts.dryRun) if err != nil { return err } @@ -1882,8 +1884,8 @@ func checkAllForgeScopes(ctx context.Context, clients repos.ForgeClientFactory, // identity is an error. In a dry run the trailer that would be added is // reported for each forge. func resolveRepoSignOffTrailers(ctx context.Context, clients repos.ForgeClientFactory, printer *ui.Printer, - manifest *repos.Manifest, filter []string, dryRun bool) (map[string]string, error) { - forges, err := manifest.SignoffForgesFor(filter) + manifest *repos.Manifest, filter, skip []string, dryRun bool) (map[string]string, error) { + forges, err := manifest.SignoffForgesFor(filter, skip) if err != nil { return nil, fmt.Errorf("determining signoff settings: %w", err) } diff --git a/internal/cli/repos_gitlab_dispatch_route_test.go b/internal/cli/repos_gitlab_dispatch_route_test.go index 27edf37b6d..8a9d0c8446 100644 --- a/internal/cli/repos_gitlab_dispatch_route_test.go +++ b/internal/cli/repos_gitlab_dispatch_route_test.go @@ -399,3 +399,30 @@ func TestReconcileGitLabWebhookSafety_ContainsElevatedTriggerAccount(t *testing. assert.Zero(t, contained) }) } + +// A GitLab repository whose trigger-account containment failed is left out +// of convergence and gets no commit, so its signoff setting needs no user +// identity: the fake token has none, and the run still lists it as FAILED. +func TestRunReposInstall_ContainmentFailureNeedsNoSignoffIdentity(t *testing.T) { + for _, signoff := range []bool{false, true} { + name, manifest := "signoff off", triggerInstallManifest + if signoff { + name = "signoff on" + manifest = strings.Replace(triggerInstallManifest, " - name: group/project\n", " - name: group/project\n signoff: true\n", 1) + } + t.Run(name, func(t *testing.T) { + manifestPath := writeTestManifest(t, manifest) + fc := newTriggerInstallFake(t) + opts := gitlabInstallOpts(manifestPath, fc) + opts.testContainTriggerAccount = func(context.Context, forge.Client, string, string) error { + return errors.New("restoring Developer access") + } + opts.testConvergeTriggerAccount = func(context.Context, forge.Client, string, string, bool) error { return nil } + var runErr error + output := captureStdout(t, func() { runErr = runReposInstall(context.Background(), opts) }) + require.EqualError(t, runErr, "1 repos failed") + assert.Equal(t, 1, strings.Count(output, "FAILED: group/project")) + assert.Empty(t, fc.CommittedFiles, "no scaffold is committed") + }) + } +} diff --git a/internal/cli/repos_trace_keys_test.go b/internal/cli/repos_trace_keys_test.go index 85a937a259..596e19c377 100644 --- a/internal/cli/repos_trace_keys_test.go +++ b/internal/cli/repos_trace_keys_test.go @@ -816,6 +816,11 @@ func TestRunReposInstall_TraceKeyRefusalSkipsOnlyThatRepo(t *testing.T) { }, sentinel: repos.ErrTraceKeyIDInvalid}, {name: "mint URL conflict", manifest: githubUnmanagedManifestYAML + " config:\n mint_url: https://other-mint.example.com\n" + web, setup: malformed, sentinel: repos.ErrTraceKeyIDInvalid}, + // The fake token has no user identity. acme/api gets no scaffold + // commit, so its sign-off needs none and acme/web still installs. + {name: "sign-off on the refused repository, token without a user identity", + manifest: strings.Replace(githubUnmanagedManifestYAML, " - name: acme/api\n", " - name: acme/api\n signoff: true\n", 1) + web, + setup: malformed, sentinel: repos.ErrTraceKeyIDInvalid}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/repos/manifest.go b/internal/repos/manifest.go index 9c39b43bfe..e66b00155d 100644 --- a/internal/repos/manifest.go +++ b/internal/repos/manifest.go @@ -1706,7 +1706,28 @@ func (m *Manifest) VendorSelected(filter []string) (bool, error) { // up needing a trailer. Even so, a glob entry that an earlier glob entry // fully covers can never win resolution, so it is ignored (see // globShadowedByEarlier). -func (m *Manifest) SignoffForgesFor(filter []string) ([]string, error) { +// +// skip names repositories (owner/repo, any case) that get no scaffold +// commit, such as those install skips: an explicit entry or a concrete +// filter pattern in skip needs no trailer. A glob entry still counts, as it +// may select other repositories. +func (m *Manifest) SignoffForgesFor(filter, skip []string) ([]string, error) { + skipped := make(map[string]bool, len(skip)) + for _, name := range skip { + skipped[strings.ToLower(name)] = true + } + if len(filter) > 0 { + var kept []string + for _, pattern := range filter { + if isGlob(pattern) || !skipped[strings.ToLower(pattern)] { + kept = append(kept, pattern) + } + } + if len(kept) == 0 { + return nil, nil + } + filter = kept + } var forges []string for _, forgeName := range []string{ForgeGitHub, ForgeGitLab} { platform := m.PlatformFor(forgeName) @@ -1714,7 +1735,7 @@ func (m *Manifest) SignoffForgesFor(filter []string) ([]string, error) { continue } for i, e := range platform.Repos { - if globShadowedByEarlier(platform.Repos[:i], e) { + if globShadowedByEarlier(platform.Repos[:i], e) || (!isGlob(e.Name) && skipped[strings.ToLower(e.Name)]) { continue } needed, err := m.entryNeedsSignoff(forgeName, e, filter) diff --git a/internal/repos/manifest_signoff_test.go b/internal/repos/manifest_signoff_test.go index 70ed0a5fa2..eb1a145c63 100644 --- a/internal/repos/manifest_signoff_test.go +++ b/internal/repos/manifest_signoff_test.go @@ -120,7 +120,7 @@ gitlab: } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := m.SignoffForgesFor(tt.filter) + got, err := m.SignoffForgesFor(tt.filter, nil) require.NoError(t, err) assert.Equal(t, tt.want, got) }) @@ -155,7 +155,7 @@ github: } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := m.SignoffForgesFor(tt.filter) + got, err := m.SignoffForgesFor(tt.filter, nil) require.NoError(t, err) assert.Equal(t, tt.want, got) }) @@ -199,7 +199,7 @@ github: } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := tt.m.SignoffForgesFor(tt.filter) + got, err := tt.m.SignoffForgesFor(tt.filter, nil) require.NoError(t, err) assert.Equal(t, tt.want, got) }) @@ -248,7 +248,7 @@ github: } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := m.SignoffForgesFor(tt.filter) + got, err := m.SignoffForgesFor(tt.filter, nil) require.NoError(t, err) assert.Equal(t, tt.want, got) }) @@ -257,7 +257,7 @@ github: func TestSignoffForgesFor_InvalidPattern(t *testing.T) { m := Manifest{Version: 1, GitHub: &PlatformConfig{Repos: []RepoEntry{{Name: "acme/app"}}}} - _, err := m.SignoffForgesFor([]string{"acme/[invalid"}) + _, err := m.SignoffForgesFor([]string{"acme/[invalid"}, nil) require.Error(t, err) } @@ -275,3 +275,42 @@ func TestCarveOutGlobEntry_CopiesSignoff(t *testing.T) { *carved.Signoff = false assert.True(t, *platform.Repos[0].Signoff) } + +// A repository install skips gets no scaffold commit, so it needs no +// trailer. A glob entry still counts, as it may select other repositories. +func TestSignoffForgesFor_SkippedRepos(t *testing.T) { + const explicit = ` +version: 1 +github: + repos: + - name: acme/plain + - name: acme/signed + signoff: true +` + const glob = explicit + ` - name: "other/*" + signoff: true +` + tests := []struct { + name, input string + filter, skip []string + want []string + }{ + {"unfiltered, the signed repo skipped", explicit, nil, []string{"acme/signed"}, nil}, + {"the signed repo named and skipped", explicit, []string{"acme/signed"}, []string{"acme/signed"}, nil}, + {"beside a plain repo", explicit, []string{"acme/plain", "acme/signed"}, []string{"acme/signed"}, nil}, + {"skip ignores case", explicit, []string{"acme/signed"}, []string{"ACME/Signed"}, nil}, + {"another signed repo still counts", glob, []string{"acme/signed", "other/repo"}, []string{"acme/signed"}, []string{ForgeGitHub}}, + {"a signed glob still counts when unfiltered", glob, nil, []string{"acme/signed", "other/repo"}, []string{ForgeGitHub}}, + {"a glob-covered repo named and skipped", glob, []string{"other/repo"}, []string{"other/repo"}, nil}, + {"every named repo skipped beside a signed glob", glob, []string{"acme/signed"}, []string{"acme/signed"}, nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var m Manifest + require.NoError(t, parseManifestBytes([]byte(tt.input), &m)) + got, err := m.SignoffForgesFor(tt.filter, tt.skip) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} From 8b64ef2f23e4d8d5eb0f9d6288682c59a7b44d4e Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 17 Nov 2026 07:45:58 -0500 Subject: [PATCH 12/12] refactor(repos): refuse a nil manifest in EnsureTraceSigningKeys EnsureTraceSigningKeys dereferenced a nil TraceKeysConfig.Manifest, while its sibling EnsureManagedConfigDefaults returns "manifest is required". It now returns the same error. repos install, its only caller, always passes the loaded manifest, so install behaves as before. Signed-off-by: Dharit Shah --- internal/repos/trace_keys.go | 3 +++ internal/repos/trace_keys_test.go | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/internal/repos/trace_keys.go b/internal/repos/trace_keys.go index b7dd64fc1d..d124f17a81 100644 --- a/internal/repos/trace_keys.go +++ b/internal/repos/trace_keys.go @@ -124,6 +124,9 @@ var ( // RequireInferenceAuth are skipped. Progress names installation and key IDs, // and the glob a new entry was copied from, never the seed. func EnsureTraceSigningKeys(ctx context.Context, cfg TraceKeysConfig, clients ForgeClientFactory, progress ProgressFunc) (map[string]*TraceKeyPlan, []TraceKeyRefusal, error) { + if cfg.Manifest == nil { + return nil, nil, fmt.Errorf("manifest is required") + } if progress == nil { progress = func(_, _, _ string) {} } diff --git a/internal/repos/trace_keys_test.go b/internal/repos/trace_keys_test.go index 692082f5dc..63fd62bbbb 100644 --- a/internal/repos/trace_keys_test.go +++ b/internal/repos/trace_keys_test.go @@ -325,6 +325,16 @@ func TestEnsureTraceSigningKeys_NilProgress(t *testing.T) { assert.Equal(t, []string{"acme/api"}, planNames(plans)) } +// A missing manifest is refused, as EnsureManagedConfigDefaults refuses it. +func TestEnsureTraceSigningKeys_NilManifest(t *testing.T) { + fc, _ := traceFixture(t, false, "acme/api") + + plans, refused, err := EnsureTraceSigningKeys(context.Background(), TraceKeysConfig{}, newTestClientFactory(fc), nil) + require.EqualError(t, err, "manifest is required") + assert.Empty(t, plans) + assert.Empty(t, refused) +} + // A repository that only a glob covers gets its own GitHub entry, copied // from the glob entry that selected it, and progress names that entry and // that glob, since later edits to the glob no longer reach it; the globs and