credstore: don't mistake a lost probe-write race for an unavailable keyring

Merged
JE
3mo ago
+185-8

Symptom

A long-running connector polling basecamp every 15s intermittently failed with

{"error": "Not authenticated for profile:production: credentials not found for profile:production", "code": "auth_required"}

— for profiles that are fully authenticated, with tokens sitting in the macOS keychain. It only happened while a second CLI process was running concurrently (another connector on a different profile); every interactive, serial invocation succeeded. The error string is loadFromFile's format, which pins the failing invocations to the file fallback — the keyring probe had failed, silently demoting the process to an empty credentials.json.

Mechanism

Every invocation probes keyring availability by writing and deleting one fixed-name entry (credstore.probe.<service> / __probe__). Two concurrent invocations churn the same keychain item, and on darwin security add-generic-password -U is find-then-create inside the security tool: when a peer's delete lands between the find (miss) and the create, the create fails with errSecDuplicateItem (-25299) on a perfectly healthy keychain. The probe treated any write failure as "keyring unavailable" → file fallback → credentials not found for profile:<name>.

The existing comment "Concurrent probes sharing the name are harmless: Set results are unaffected" turns out to be false on darwin — only the delete race was harmless.

Real credential entries are immune: they are never delete/add churned, so -U reliably takes its update path. Only the probe's write-then-delete pattern creates the race.

Repro (real keychain, before/after)

Two concurrent loops mirroring the probe (add-generic-password -U + delete-generic-password on a scratch service): the losing loop fails 199/200 adds with -25299. Sequential -U adds never fail. Two concurrent probe() loops via the package itself: 99/200 failures before this change, 0/400 after (both bounded and unbounded paths). End-to-end, two concurrent loops of basecamp me -j on different authenticated profiles produced 2/30 auth_required failures on an unpatched binary.

Fix

A probe answer that proves the keychain responsive counts as availability, not grounds for the file fallback:

  • Bounded darwin probe: capture security output; treat errSecDuplicateItem as success and continue to cleanup. Matched by the ABI-stable OSStatus -25299, not the prose message.
  • Unbounded probe (go-keyring returns a bare exec.ExitError with no output to classify): disambiguate a failed Set with a Get. Entry present (the peer's probe) or cleanly absent (ErrNotFound — the peer already cleaned up) proves the keyring answers; only failing both write and read reports unavailability.

make check and go test -race ./credstore/... pass; gofmt clean.