fix empty repo detection and gpg race

321286b403e6… · Ryan Schanzenbacher ·

parent 555062657fd6… view tree

Changed files

diff --git a/AGENTS.md b/AGENTS.md
index 34fe639..cbc4b20 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -215,10 +215,30 @@ owns the palette. Keep it that way — do not hardcode a colour in Go.
### 10. Empty repositories are a normal state
-A freshly created bare repo has an unborn HEAD. `Repo.Empty()` is checked at
-`Open`, and `Log`/`Tree` return nothing rather than failing. Templates must
-not index into a possibly-empty slice — use `{{ with mod "log" "1" }}{{ with
-index . 0 }}`, not `{{ index (mod "log" "1") 0 }}`, or the render aborts.
+A freshly created bare repo has an unborn HEAD. `Repo.Empty()` reports it, and
+`Log`/`Tree` return nothing rather than failing. Emptiness is read from the
+repository on demand (memoized per request), never cached on the long-lived
+`Repo`: the watcher opens a repo as soon as its directory appears, before
+anything is pushed, and a pushed ref does not touch any file it watches.
+Templates must not index into a possibly-empty slice — use
+`{{ with mod "log" "1" }}{{ with index . 0 }}`, not
+`{{ index (mod "log" "1") 0 }}`, or the render aborts.
+
+### 11. A published `gitx.Repo` is never written to
+
+Every request takes a shallow copy of a `Handle`'s `Repo` (`WithContext`)
+while the watcher may be reconfiguring that repo. A change -- today, only
+the GPG keyring -- builds a new `Repo` (`WithKeyring`/`WithoutKeyring`) that
+`reconcile` publishes in a new `Handle`, together with the `RepoInfo` that
+describes it. Writing a field in place was a data race on that copy, and
+publishing the two separately let one request pair one keyring's signature
+results with another's cache key. Per-request state goes in `repoMemo`,
+which `WithContext` allocates fresh.
+
+An imported keyring's homedir is removed by a finalizer when nothing
+references it, not when it is replaced: a request holding the previous
+`Repo` may still have gpg reading it. `run` keeps the keyring alive across
+the exec for the same reason.
## How to make common changes
@@ -339,8 +359,7 @@ Accurate as of now; update this list when you close one.
- The LRU is bounded by entry count, not bytes, so a large diff and a ref
list occupy one slot each. The `Store` interface is the only thing a
size-aware replacement must satisfy.
-- Repository discovery is one level deep and happens once at startup; a repo
- created afterwards needs a restart.
+- Repository discovery is one level deep.
- README relative-link rewriting assumes every link is a file. A link to a
directory lands on the blob view and 404s. Fixing it properly means a tree
lookup per link.
diff --git a/internal/core/core.go b/internal/core/core.go
index 8862350..77a07a6 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -183,11 +183,12 @@ type RepoInfo struct {
ShareRevokedAfter time.Time
// GPGKeyring is the configured path to a file of armored public keys
- // (gsg.gpgkeyring), if any. Reading it here is just config; the actual
- // import into an isolated keyring happens once at startup (see
- // gitx.Repo.UseKeyring) and, on failure, this is cleared again so
- // templates don't advertise a verification column that isn't backed
- // by anything.
+ // (gsg.gpgkeyring), if any. Reading it here is just config; the import
+ // into an isolated keyring happens in watch.go's reconcile (see
+ // gitx.Repo.WithKeyring). If that import fails, reconcile overwrites
+ // this with the keyring the Handle's Repo actually has -- the previous
+ // one, or "" -- so templates and cache keys describe what is backing
+ // verification, not what was configured.
GPGKeyring string
// CacheMaxAge is gsg.cache-max-age: how long an anonymous (no session,
diff --git a/internal/core/watch.go b/internal/core/watch.go
index 48e4beb..9f80ef9 100644
--- a/internal/core/watch.go
+++ b/internal/core/watch.go
@@ -130,13 +130,30 @@ func (w *watcher) reconcile(name string) {
// Converge the keyring to whatever's configured now, on this call just
// like any other -- no "only import the first time" special case.
+ //
+ // r is never modified: requests are copying it concurrently (see
+ // gitx.Repo). A keyring change builds a new Repo, which is published
+ // below in the same Handle as the Info that describes it, so a request
+ // can never pair one keyring's signature results with another
+ // keyring's cache key.
if info.GPGKeyring != r.KeyringPath() {
if info.GPGKeyring == "" {
- r.ClearKeyring()
- } else if err := r.UseKeyring(info.GPGKeyring); err != nil {
- slog.Warn("gpg keyring: verification disabled", "repo", info.Slug, "err", err)
- info.GPGKeyring = ""
+ r = r.WithoutKeyring()
+ } else if next, err := r.WithKeyring(info.GPGKeyring); err != nil {
+ // Keep whatever r already verifies with, and say so in Info:
+ // the cache key and the templates must describe the keyring
+ // actually in use, not the one that failed to import.
+ slog.Warn("gpg keyring: import failed, keeping previous", "repo", info.Slug,
+ "previous", r.KeyringPath(), "err", err)
+ info.GPGKeyring = r.KeyringPath()
+ } else {
+ r = next
}
+ w.mu.Lock()
+ if _, still := w.repos[name]; still {
+ w.repos[name] = r
+ }
+ w.mu.Unlock()
}
w.site.upsert(Handle{Repo: r, Info: info})
diff --git a/internal/gitx/git.go b/internal/gitx/git.go
index 48512b5..98aa027 100644
--- a/internal/gitx/git.go
+++ b/internal/gitx/git.go
@@ -12,6 +12,7 @@ import (
"os/exec"
"path/filepath"
"regexp"
+ "runtime"
"strconv"
"strings"
"sync"
@@ -30,23 +31,23 @@ const (
escLogR = "%x1e" // record separator, as written in a git-log format
)
+// Repo is immutable once returned to a caller. Every request takes a
+// shallow copy of the long-lived Repo (WithContext) while the watcher may
+// concurrently be reconfiguring it, so nothing may write to a published
+// Repo's fields: a change is a new Repo (WithKeyring, WithoutKeyring) that
+// the caller publishes in its place.
type Repo struct {
- Dir string // path to the git dir (bare repo, or <worktree>/.git)
- Slug string // url-safe short name, derived from the directory
- empty bool // no commits yet (unborn HEAD)
+ Dir string // path to the git dir (bare repo, or <worktree>/.git)
+ Slug string // url-safe short name, derived from the directory
ctx context.Context
maxBytes int64
- // gpgHome, once set by UseKeyring, is an isolated GNUPGHOME containing
- // only the keys the operator imported for this repo. Its presence is
- // also the signal to Log/LogAll to ask git for signature status at all.
- gpgHome string
-
- // keyringPath is the gsg.gpgkeyring value that produced gpgHome, so a
- // caller can tell whether the configured keyring has changed without
- // tracking that separately. Empty when no keyring is imported.
- keyringPath string
+ // kr, when non-nil, is the isolated GNUPGHOME imported from the
+ // operator's gsg.gpgkeyring. Its presence is also the signal to
+ // Log/LogAll to ask git for signature status at all. Shared, read-only,
+ // by every copy of the Repo that was built from it.
+ kr *keyring
// memo caches HeadRef/Refs for the lifetime of one request. It is a
// pointer, allocated fresh by WithContext, rather than a plain field:
@@ -61,6 +62,7 @@ type Repo struct {
type repoMemo struct {
mu sync.Mutex
+ empty *bool
headRef *string
haveRefs bool
refs []Ref
@@ -79,10 +81,48 @@ func (r *Repo) WithContext(ctx context.Context, maxBytes int64) *Repo {
return &c
}
-// Empty reports whether the repository has no commits. This is a normal
-// state for a freshly created bare repo, not an error -- Log and Tree
-// return nothing rather than failing, so a view still renders.
-func (r *Repo) Empty() bool { return r.empty }
+// Empty reports whether the repository has no commits (unborn HEAD). This
+// is a normal state for a freshly created bare repo, not an error -- Log
+// and Tree return nothing rather than failing, so a view still renders.
+//
+// Evaluated on demand and memoized per request (like HeadRef), never
+// latched at Open: core/watch.go opens a repo as soon as its directory
+// appears under root -- gitolite and `git init --bare` both create it
+// before the first push -- and keeps that *Repo for the life of the
+// process. A value captured at Open left a new repo showing no commits
+// after it was pushed to, until a restart re-opened it. Pushes don't touch
+// config or description, so the watcher never sees them; this has to be a
+// read of current state, not something the watcher refreshes.
+func (r *Repo) Empty() bool {
+ if r.memo != nil {
+ r.memo.mu.Lock()
+ cached := r.memo.empty
+ r.memo.mu.Unlock()
+ if cached != nil {
+ return *cached
+ }
+ }
+
+ empty := r.headUnborn()
+
+ if r.memo != nil {
+ r.memo.mu.Lock()
+ r.memo.empty = &empty
+ r.memo.mu.Unlock()
+ }
+ return empty
+}
+
+// headUnborn is true only when git positively reports that HEAD does not
+// resolve: `rev-parse --verify --quiet` exits 1. Any other failure -- the
+// request deadline, git missing -- is not evidence the repo is empty, and
+// treating it as such would turn a timeout into a silently blank page
+// instead of an error.
+func (r *Repo) headUnborn() bool {
+ _, err := r.run("rev-parse", "--verify", "--quiet", "HEAD")
+ var exitErr *exec.ExitError
+ return errors.As(err, &exitErr) && exitErr.ExitCode() == 1
+}
func Open(dir string) (*Repo, error) {
gitDir := dir
@@ -96,8 +136,6 @@ func Open(dir string) (*Repo, error) {
if _, err := r.run("rev-parse", "--git-dir"); err != nil {
return nil, fmt.Errorf("open %s: %w", dir, err)
}
- _, err := r.run("rev-parse", "--verify", "--quiet", "HEAD")
- r.empty = err != nil
return r, nil
}
@@ -118,15 +156,20 @@ func (r *Repo) run(args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, "git", full...)
// Refuse to inherit anything that alters git's behaviour.
cmd.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "GIT_TERMINAL_PROMPT=0", "PATH=" + os.Getenv("PATH")}
- if r.gpgHome != "" {
+ kr := r.kr
+ if kr != nil {
// git shells out to gpg to check %G?; gpg picks this up from its
// own environment, which it inherits from git's.
- cmd.Env = append(cmd.Env, "GNUPGHOME="+r.gpgHome)
+ cmd.Env = append(cmd.Env, "GNUPGHOME="+kr.home)
}
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
err := cmd.Run()
+ // The homedir is removed by kr's finalizer once kr is unreachable. Past
+ // building Env, nothing above reads kr, so without this the GC could
+ // decide it is dead and delete the directory while gpg is reading it.
+ runtime.KeepAlive(kr)
if r.maxBytes > 0 && int64(out.Len()) > r.maxBytes {
return out.Bytes()[:r.maxBytes], ErrTruncated
@@ -165,24 +208,41 @@ func (r *Repo) ConfigFirst(keys ...string) string {
// -------------------------------------------------------------------- gpg
-// UseKeyring points every subsequent git invocation on this Repo (via
-// GNUPGHOME, see run) at an isolated homedir containing only the keys
-// imported from path. Without this, %G? signature checks would fall back
-// to the host's default keyring -- whatever happens to be trusted there,
-// not what this repo's operator vetted.
+// keyring is an imported, isolated GNUPGHOME. Immutable after
+// importKeyring returns.
+//
+// Its directory is deleted by a finalizer when the keyring becomes
+// unreachable, not when the watcher swaps in a replacement: a request that
+// looked its Handle up just before the swap is still holding a copy of the
+// old Repo and may be mid-`git log` with gpg reading this directory.
+// Deleting it eagerly (as an earlier version did) made that request's
+// signatures come back as "signature not checked", and that result was
+// then cached in the module LRU under the old keyring's key. Reachability
+// is exactly "no Repo that could still run gpg against it", so it is the
+// right lifetime.
+type keyring struct {
+ home string // GNUPGHOME
+ path string // the gsg.gpgkeyring value it was imported from
+}
+
+// importKeyring imports the armored keys at path into a fresh homedir.
+// Without this, %G? signature checks would fall back to the host's default
+// keyring -- whatever happens to be trusted there, not what this repo's
+// operator vetted.
//
// The homedir is created directly under /tmp rather than os.TempDir():
// gpg-agent's control socket is a Unix domain socket, capped at ~104
// bytes, and a long TMPDIR (macOS's is typically 50+ characters) pushes
// the full path over that limit and breaks key generation/import in a way
// that just prints "no agent running" with no useful exit code to catch.
-func (r *Repo) UseKeyring(path string) error {
+func importKeyring(path string) (*keyring, error) {
dir, err := os.MkdirTemp("/tmp", "gsg-gpg-")
if err != nil {
- return fmt.Errorf("gpg keyring: %w", err)
+ return nil, fmt.Errorf("gpg keyring: %w", err)
}
if err := os.Chmod(dir, 0700); err != nil {
- return fmt.Errorf("gpg keyring: %w", err)
+ os.RemoveAll(dir)
+ return nil, fmt.Errorf("gpg keyring: %w", err)
}
cmd := exec.Command("gpg", "--batch", "--quiet", "--import", path)
cmd.Env = []string{"GNUPGHOME=" + dir, "HOME=/nonexistent", "PATH=" + os.Getenv("PATH")}
@@ -190,33 +250,45 @@ func (r *Repo) UseKeyring(path string) error {
cmd.Stderr = &errb
if err := cmd.Run(); err != nil {
os.RemoveAll(dir)
- return fmt.Errorf("gpg keyring: import %s: %w: %s", path, err, strings.TrimSpace(errb.String()))
+ return nil, fmt.Errorf("gpg keyring: import %s: %w: %s", path, err, strings.TrimSpace(errb.String()))
}
+ kr := &keyring{home: dir, path: path}
+ runtime.SetFinalizer(kr, func(k *keyring) { os.RemoveAll(k.home) })
+ return kr, nil
+}
- // Only swap the new homedir in -- and clean up the old one -- once the
- // import has actually succeeded, so a bad reconfigure logs a warning and
- // leaves the previously-working keyring active rather than breaking it.
- old := r.gpgHome
- r.gpgHome, r.keyringPath = dir, path
- if old != "" {
- os.RemoveAll(old)
+// WithKeyring returns a copy of r whose git invocations (via GNUPGHOME, see
+// run) see only the keys imported from path. r itself is not modified. On
+// error the caller still has r, so a bad reconfigure leaves the
+// previously-working keyring in effect rather than breaking it.
+func (r *Repo) WithKeyring(path string) (*Repo, error) {
+ kr, err := importKeyring(path)
+ if err != nil {
+ return nil, err
}
- return nil
+ c := *r
+ c.kr = kr
+ return &c, nil
+}
+
+// WithoutKeyring returns a copy of r that does not verify signatures. r
+// itself is not modified; its homedir, if any, goes away once nothing
+// references it.
+func (r *Repo) WithoutKeyring() *Repo {
+ c := *r
+ c.kr = nil
+ return &c
}
-// KeyringPath is the gsg.gpgkeyring value currently imported, or "" if no
-// keyring is active. Callers use this to detect when the configured keyring
+// KeyringPath is the gsg.gpgkeyring value imported into this Repo, or "" if
+// it has no keyring. Callers use this to detect when the configured keyring
// has changed, on any call -- the first or the hundredth -- without needing
// to track that separately.
-func (r *Repo) KeyringPath() string { return r.keyringPath }
-
-// ClearKeyring reverts to unverified signatures, removing any imported
-// keyring's isolated homedir.
-func (r *Repo) ClearKeyring() {
- if r.gpgHome != "" {
- os.RemoveAll(r.gpgHome)
+func (r *Repo) KeyringPath() string {
+ if r.kr == nil {
+ return ""
}
- r.gpgHome, r.keyringPath = "", ""
+ return r.kr.path
}
const placeholderDesc = "Unnamed repository; edit this file 'description' to name the repository."
@@ -399,7 +471,7 @@ type Commit struct {
Parents []string
// Signature is only populated when the caller asked for it (Log, when
- // the repo has a keyring -- see Repo.UseKeyring). SigStatus is git's
+ // the repo has a keyring -- see Repo.WithKeyring). SigStatus is git's
// raw %G? code: G/U good, B bad, X/Y expired, R revoked, E unchecked,
// N unsigned or "" when signature checks weren't requested at all.
SigStatus string
@@ -451,10 +523,10 @@ func (c Commit) SigLabel() string {
// only pass true for small, bounded logs: git forks gpg once per signed
// commit to check it.
func (r *Repo) Log(rev string, n, skip int, verify bool) ([]Commit, error) {
- if r.empty {
+ if r.Empty() {
return nil, nil
}
- verify = verify && r.gpgHome != "" // no keyring configured: nothing to check against
+ verify = verify && r.kr != nil // no keyring configured: nothing to check against
fields := []string{"%H", "%an", "%ae", "%aI", "%P", "%s"}
if verify {
fields = append(fields, "%G?", "%GS", "%GK")
@@ -539,7 +611,7 @@ func (r *Repo) IsAncestor(a, b string) (bool, error) {
// branch graph: --topo-order guarantees a child always precedes its
// parents, which the lane assignment depends on.
func (r *Repo) LogAll(n int) ([]Commit, error) {
- if r.empty {
+ if r.Empty() {
return nil, nil
}
format := strings.Join([]string{"%H", "%an", "%ae", "%aI", "%P", "%s", "%b"}, escLogF)
@@ -567,7 +639,7 @@ func (e Entry) IsSubmodule() bool { return e.Type == "commit" }
// Tree lists one directory level at rev.
func (r *Repo) Tree(rev, path string) ([]Entry, error) {
- if r.empty {
+ if r.Empty() {
return nil, nil
}
spec := rev + ":"
diff --git a/internal/gitx/git_test.go b/internal/gitx/git_test.go
index 73dd814..de756f7 100644
--- a/internal/gitx/git_test.go
+++ b/internal/gitx/git_test.go
@@ -1,6 +1,7 @@
package gitx
import (
+ "context"
"os"
"os/exec"
"testing"
@@ -155,3 +156,46 @@ func TestIsAncestor(t *testing.T) {
}
})
}
+
+// TestEmptyTracksFirstPush guards against latching emptiness at Open. The
+// watcher (core/watch.go) opens a repo the moment its directory appears --
+// gitolite and `git init --bare` both create it before anything is pushed
+// -- and reuses that *Repo for the life of the process, so a value captured
+// at Open kept a repo reading as empty after its first push until restart.
+func TestEmptyTracksFirstPush(t *testing.T) {
+ bare := t.TempDir()
+ runGit(t, bare, "init", "-q", "--bare", "-b", "main")
+
+ r, err := Open(bare)
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ if !r.Empty() {
+ t.Fatal("fresh bare repo: Empty() = false, want true")
+ }
+ if log, err := r.Log(r.HeadRef(), 1, 0, false); err != nil || len(log) != 0 {
+ t.Fatalf("Log on empty repo = %v, %v; want nil, nil", log, err)
+ }
+
+ work := t.TempDir()
+ runGit(t, work, "init", "-q", "-b", "main")
+ runGit(t, work, "commit", "-q", "--allow-empty", "-m", "first")
+ runGit(t, work, "push", "-q", bare, "main")
+
+ // Same *Repo the watcher would still be holding.
+ if r.Empty() {
+ t.Fatal("after push: Empty() = true on the long-lived Repo, want false")
+ }
+ rc := r.WithContext(context.Background(), 0)
+ if rc.Empty() {
+ t.Fatal("after push: Empty() = true on a request-bound Repo, want false")
+ }
+ sha, err := rc.Resolve(rc.HeadRef())
+ if err != nil {
+ t.Fatalf("Resolve after push: %v", err)
+ }
+ log, err := rc.Log(sha, 1, 0, false)
+ if err != nil || len(log) != 1 || log[0].Subject != "first" {
+ t.Fatalf("Log after push = %v, %v; want the pushed commit", log, err)
+ }
+}
diff --git a/internal/gitx/keyring_test.go b/internal/gitx/keyring_test.go
new file mode 100644
index 0000000..96c8cd8
--- /dev/null
+++ b/internal/gitx/keyring_test.go
@@ -0,0 +1,153 @@
+package gitx
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// testPubKey is a throwaway ed25519 public key, generated for these tests
+// only. Any importable key works; nothing here checks a signature by it.
+const testPubKey = `-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+mDMEaugNpRYJKwYBBAHaRw8BAQdALdT0aysVitcgR5XI/83vQs0OikaFIA7iCaz+
+jhDcKme0B1QgPHRAZT6IkwQTFgoAOxYhBDOCxCHguLawIR59W19RDrlDNqKgBQJq
+6A2lAhsDBQsJCAcCAiICBhUKCQgLAgQWAgMBAh4HAheAAAoJEF9RDrlDNqKg7DsB
+APBorNFTKhE59bHCAkYvT30Pi+CH1JlOEvJtOAviTV2DAQD6CpRoMvZ6i9638gZZ
+q9656Bht+aWyGLHAAixEJS6RCg==
+=wJW3
+-----END PGP PUBLIC KEY BLOCK-----
+`
+
+func writeKeyFile(t *testing.T) string {
+ t.Helper()
+ if _, err := exec.LookPath("gpg"); err != nil {
+ t.Skip("gpg not on PATH")
+ }
+ p := filepath.Join(t.TempDir(), "keys.asc")
+ if err := os.WriteFile(p, []byte(testPubKey), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+// withKeyring wraps Repo.WithKeyring and removes the homedir it created
+// when the test ends: finalizers don't run at process exit, so a keyring
+// still reachable then would otherwise be left in /tmp.
+func withKeyring(t *testing.T, r *Repo, path string) (*Repo, error) {
+ t.Helper()
+ next, err := r.WithKeyring(path)
+ if err == nil {
+ home := next.kr.home
+ t.Cleanup(func() { os.RemoveAll(home) })
+ }
+ return next, err
+}
+
+// TestKeyringSwapLeavesOriginal guards the immutability contract: requests
+// copy the published Repo concurrently with the watcher reconfiguring it,
+// so a keyring change must be a new Repo, never a write to the old one.
+func TestKeyringSwapLeavesOriginal(t *testing.T) {
+ keys := writeKeyFile(t)
+ r := newTestRepo(t)
+
+ withKr, err := withKeyring(t, r, keys)
+ if err != nil {
+ t.Fatalf("WithKeyring: %v", err)
+ }
+ if got := r.KeyringPath(); got != "" {
+ t.Fatalf("original after WithKeyring: KeyringPath() = %q, want \"\"", got)
+ }
+ if got := withKr.KeyringPath(); got != keys {
+ t.Fatalf("WithKeyring result: KeyringPath() = %q, want %q", got, keys)
+ }
+
+ home := withKr.kr.home
+ without := withKr.WithoutKeyring()
+ if without.KeyringPath() != "" {
+ t.Fatal("WithoutKeyring result still has a keyring")
+ }
+ // A request holding withKr must still be able to run gpg against it.
+ if _, err := os.Stat(home); err != nil {
+ t.Fatalf("homedir removed while a Repo still references it: %v", err)
+ }
+ if _, err := withKr.WithContext(context.Background(), 0).Log("main", 1, 0, true); err != nil {
+ t.Fatalf("verifying Log on the superseded Repo: %v", err)
+ }
+ runtime.KeepAlive(withKr)
+
+ if _, err := r.WithKeyring(filepath.Join(t.TempDir(), "missing.asc")); err == nil {
+ t.Fatal("WithKeyring on a missing file: want error")
+ }
+}
+
+// TestKeyringHomedirReleased: the homedir outlives the swap (above) but
+// must not leak once nothing can reach it.
+func TestKeyringHomedirReleased(t *testing.T) {
+ keys := writeKeyFile(t)
+ r := newTestRepo(t)
+
+ withKr, err := r.WithKeyring(keys)
+ if err != nil {
+ t.Fatalf("WithKeyring: %v", err)
+ }
+ home := withKr.kr.home
+ withKr = nil
+
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ runtime.GC()
+ if _, err := os.Stat(home); os.IsNotExist(err) {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("homedir %s still present after its keyring became unreachable", home)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+// TestKeyringSwapRace mirrors core/watch.go publishing new Repos while
+// requests copy the current one. Run under -race: the previous in-place
+// UseKeyring raced on the copy in WithContext.
+func TestKeyringSwapRace(t *testing.T) {
+ keys := writeKeyFile(t)
+ var cur atomic.Pointer[Repo]
+ cur.Store(newTestRepo(t))
+
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 6; i++ {
+ r := cur.Load()
+ if r.KeyringPath() == "" {
+ next, err := withKeyring(t, r, keys)
+ if err != nil {
+ t.Errorf("WithKeyring: %v", err)
+ return
+ }
+ cur.Store(next)
+ } else {
+ cur.Store(r.WithoutKeyring())
+ }
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 30; i++ {
+ rc := cur.Load().WithContext(context.Background(), 0)
+ if _, err := rc.Log("main", 1, 0, true); err != nil {
+ t.Errorf("Log: %v", err)
+ return
+ }
+ }
+ }()
+ wg.Wait()
+}