Summary
This is PR 3 of the 4-PR split of #725, following the review request to separate provider identity, credential ownership, transactional persistence, and selection UX into independently reviewable contracts.
IMPORTANT
This PR is stacked on #893 and should be merged after it. GitHub requires this cross-fork PR to target an upstream branch, so the displayed diff includes #892 and #893. Review only the final commit:
fix(providers): transact provider config and keys. Once the predecessors merge, this diff will collapse to that commit.
What changed
- Adds one config-layer provider transaction owning exclusive cross-process locking, config read and validation, in-memory mutation, credential changes, atomic config publication, conditional rollback, and ownership-checked release.
- Fails closed when lock acquisition, timeout, creation, cleanup, or release fails. Age-based lock stealing is intentionally removed because a slow live keyring holder cannot safely be distinguished from an abandoned lock by age.
- Routes provider add/setup, catalog ensure, OpenRouter key persistence, active/model writes, manager edit/rename/remove, marker cleanup, logout API-key cleanup, STT credential writes, and plaintext-key migration through the shared boundary.
- Commits OpenRouter profile creation, minted-key storage, and marker publication together.
- Rolls credentials back only when the stored value still exactly matches the value written by the failed transaction.
Scope
Provider-selection presentation, ZERO_PROVIDER explanations, and case-only live-session synchronization remain in PR 4.
Validation
make fmt-checkgo vet ./...go test ./...go test -race ./internal/config ./internal/cli ./internal/tui -count=1go run ./cmd/zero-release buildgo run ./cmd/zero-release smokemake lint-static(0 issues.)make vulncheck(No vulnerabilities found.)git diff HEAD --check
Refs #721. Split of #725. Stacked on #893.
Summary by CodeRabbit
-
New Features
- Added ChatGPT OAuth login support across CLI and setup flows.
- Added
providers repair-configto recover legacy unnamed profiles. - Improved provider and catalog identity matching, including aliases, case variations, and Unicode distinctions.
- Nameless OpenAI profiles are recognized automatically.
- Provider and model changes remain synchronized across configuration, credentials, and active sessions.
-
Bug Fixes
- Added preflight validation before authentication and credential changes.
- Improved transactional credential storage, migration, cleanup, and rollback.
- Safely reject ambiguous or invalid provider identities.
- Diagnostic checks now provide actionable repair guidance.
Activity
125Actionable comments posted: 7
🧹 Nitpick comments (6)
internal/cli/auth_test.go (1)
538-543: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPin the credential-store backend in these two logout tests.
TestRunAuthLogoutResolvesCatalogIdentityandTestRunAuthLogoutDeletesCatalogIDTokendo not setZERO_CRED_STORAGE. Every other logout test in this file does (Lines 610, 654, 702, 742, 872, 919, 962).Both tests still reach
config.DeleteProviderCredentials, which opens the provider key store. Without the override the backend can resolve to the OS keyring. Both tests assertexitSuccess, so a keyring that is absent or locked turns them into environment-dependent failures on a headless runner.💚 Proposed fix
func TestRunAuthLogoutResolvesCatalogIdentity(t *testing.T) { + t.Setenv("ZERO_CRED_STORAGE", "encrypted-file") storePath := withAuthStore(t)func TestRunAuthLogoutDeletesCatalogIDToken(t *testing.T) { + t.Setenv("ZERO_CRED_STORAGE", "encrypted-file") storePath := withAuthStore(t)As per coding guidelines: "Code and tests must pass on Linux, macOS, and Windows".
Also applies to: 575-580
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/auth_test.go` around lines 538 - 543, Set ZERO_CRED_STORAGE to the test store backend in both TestRunAuthLogoutResolvesCatalogIdentity and TestRunAuthLogoutDeletesCatalogIDToken, matching the setup used by the other logout tests. Ensure the override is applied before invoking logout so config.DeleteProviderCredentials does not use the OS keyring.Source: Coding guidelines
internal/cli/provider_onboarding_test.go (1)
46-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd an ambiguous-catalog-id failure case.
The table covers only resolutions that succeed.
removeis destructive, and the resolution rule that protects it is "reject a catalog id claimed by more than one profile". Nothing here pins that rule forproviders use|remove|rename.Add a case with two profiles sharing
catalogId: "acme", address it asacme, and assert a non-zero exit with both profiles still present.💚 Proposed additional test
func TestProviderMutationsRejectAmbiguousCatalogID(t *testing.T) { for _, command := range []string{"use", "remove", "rename"} { t.Run(command, func(t *testing.T) { configPath := filepath.Join(t.TempDir(), "config.json") writeProviderOnboardingConfig(t, configPath, config.FileConfig{ ActiveProvider: "other", Providers: []config.ProviderProfile{ {Name: "work", CatalogID: "acme", ProviderKind: config.ProviderKindOpenAICompatible, BaseURL: "https://work.example/v1", Model: "m1"}, {Name: "personal", CatalogID: "acme", ProviderKind: config.ProviderKindOpenAICompatible, BaseURL: "https://personal.example/v1", Model: "m2"}, {Name: "other", ProviderKind: config.ProviderKindOpenAICompatible, BaseURL: "https://other.example/v1", Model: "m3"}, }, }) args := []string{"providers", command, "acme"} if command == "rename" { args = append(args, "renamed") } var stdout, stderr bytes.Buffer if code := runWithDeps(args, &stdout, &stderr, providerSetupDeps(configPath)); code == exitSuccess { t.Fatalf("an ambiguous catalog id must not mutate a profile; stdout = %q", stdout.String()) } cfg := readFileConfig(t, configPath) if len(cfg.Providers) != 3 || cfg.ActiveProvider != "other" { t.Fatalf("config mutated on an ambiguous address: %+v", cfg) } }) } }As per coding guidelines: "Every behavior or security-boundary change requires a regression test, including failure paths".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/provider_onboarding_test.go` around lines 46 - 58, Add a regression test alongside TestProviderMutationsResolvePersistedIdentity that runs providers use, remove, and rename against two profiles sharing catalog ID "acme". Assert each command exits non-zero and verify the configuration remains unchanged, including all profiles and the active provider.Source: Coding guidelines
internal/config/provider_commit.go (2)
117-146: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueDo not discard the
credentialStore()error insetKeyanddeleteKey.The code is correct today.
snapshotCredentialopens the store first and returns any error, andcredentialStore()memoizesop.store, so the second call cannot fail. The safety depends on that call order alone. IfsnapshotCredentialever returns early before the store is opened,storebecomes nil and the nextstore.Set/store.Deletepanics.Propagate the error instead of discarding it.
♻️ Proposed fix
func (op *providerProfileOperation) setKey(name, value string) error { identity := credstore.NormalizeProvider(name) snapshot, err := op.snapshotCredential(name) if err != nil { return err } - store, _ := op.credentialStore() + store, err := op.credentialStore() + if err != nil { + return err + } if err := store.Set(name, value); err != nil { return err }Apply the same change in
deleteKey.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/provider_commit.go` around lines 117 - 146, Update setKey and deleteKey to capture and propagate the error returned by credentialStore() instead of discarding it; return the error before invoking store.Set or store.Delete, while preserving the existing snapshot and mutation flow.
148-163: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winSurface rollback failures instead of discarding them.
The value-comparison guard is right: a credential is only restored when the store still holds exactly what this transaction wrote, so a concurrent winner's secret is never clobbered.
The two restore calls discard their errors. If publication fails and the restore also fails, the credential store and
config.jsondiverge, and the caller sees only the publication error. The user then has a stored key with no matching row, and no signal that cleanup failed.Return the rollback error from
rollbackCredentialsand join it into the errorrunProviderProfileOperationreturns, the same way the lock-release error is joined at line 52.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/provider_commit.go` around lines 148 - 163, Change providerProfileOperation.rollbackCredentials to return restoration errors from store.Set or store.Delete instead of discarding them, while preserving the existing comparison guard and continuing rollback processing. Update runProviderProfileOperation to receive the rollback error and join it with the publication error, using the existing lock-release error-joining pattern.internal/config/writer.go (1)
780-822: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStore a newly supplied key directly under the new name instead of writing it twice.
When an edit supplies both
APIKeyand an identity-changingNewName, line 799 stores the key underpreviousName, then lines 810-820 read it back, store it undernewName, and deletepreviousName. The result is correct, and rollback covers every intermediate step, but one logical edit becomes two store writes plus a delete.Two smaller points in the same block:
- Lines 783 and 790 call
credstore.NormalizeProviderdirectly for the collision check.RenameProviderexpresses the identical check through thesameProviderIdentityhelper. Use the helper in both places.- The migration
Getat line 810 reads a value this same transaction may have just written, which makes the data flow harder to follow than it needs to be.Resolve the target name first, then capture the key once under that name.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/writer.go` around lines 780 - 822, Update RenameProvider to use sameProviderIdentity for provider collision checks, resolve the destination name before handling edit.APIKey, and write a newly supplied key directly under newName. Capture the existing key once for identity-changing renames, avoiding a transaction-local Get of a key just written and eliminating the redundant previousName write/migration delete sequence.internal/config/credentials.go (1)
211-233: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winSilent
continueonsetKeyfailure leaves the plaintext key inconfig.jsonwith no signal.Leaving the plaintext key in place on a failed store write is the right call, and it matches the documented behavior of the legacy
MigratePlaintextProviderKeysat lines 194-197. The new function drops the comment that explained why. Keep that rationale here, since this is the production startup path.The gap is reporting. A credential-store failure produces
(migrated, nil). Startup continues, the secret stays in cleartext inconfig.json, and nothing tells the user the migration did not complete. Return a count of skipped profiles or a joined error so the caller can warn.♻️ Proposed change
migrated := 0 + var skipped error _, err := runProviderProfileOperation(path, true, false, func(op *providerProfileOperation) error { for index := range op.config.Providers { profile := &op.config.Providers[index] key := strings.TrimSpace(profile.APIKey) if key == "" || strings.TrimSpace(profile.Name) == "" { continue } if err := op.setKey(profile.Name, key); err != nil { + // Leave the plaintext key untouched; a failed Set must not strand it. + skipped = errors.Join(skipped, fmt.Errorf("migrate stored key for %q: %w", profile.Name, err)) continue }Do not put the key value in the error text.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/credentials.go` around lines 211 - 233, Update MigratePlaintextProviderKeysTransactional to retain the rationale comment for leaving plaintext keys unchanged when op.setKey fails, and report those failures to the caller without exposing key values. Track skipped profiles or aggregate an error while continuing migration, then return that signal alongside the migrated count so startup can warn; preserve successful migration behavior and publishing logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/provider_setup.go`:
- Around line 56-64: Both CommitProviderProfile call sites must preserve its
sanitized persisted profile. In internal/cli/provider_setup.go lines 56-64,
replace the Name-only assignment with the full committed.Persisted assignment so
JSON output omits plaintext API keys and reports APIKeyStored. In
internal/cli/setup.go lines 267-274, return committed.Persisted as
tui.SetupResult.Provider while supplying verifySetupProvider with a separate
key-bearing copy, or apply config.ApplyStoredAPIKey within verifySetupProvider.
In `@internal/config/provider_commit_test.go`:
- Around line 230-268: Set ZERO_CRED_STORAGE to encrypted-file at the start of
TestCommitProviderProfileCrossProcessCaseVariantsKeepOneKey, allowing the
setting to propagate to child processes and ensuring the parent reads the same
backend. Apply the same setup to
TestCommitProviderProfileFailsClosedWhenLockIsBusy and
TestCommitProviderProfileFailsClosedWhenLockCannotBeCreated before their
ProviderKeyStoreAt calls.
In `@internal/config/provider_commit.go`:
- Around line 264-275: Restrict the os.ErrPermission contention handling in the
provider config/key transaction lock acquisition loop to Windows, while
continuing to treat os.ErrExist as contention on all platforms. On Unix, return
permission errors immediately instead of retrying until the deadline, and add a
regression test covering this behavior in the relevant lock acquisition tests.
In `@internal/config/resolver.go`:
- Around line 958-960: Update the active-provider selection logic around
activeName so that when exactly one provider is present and its trimmed name is
empty, activeName defaults to openai before activeIndex and resolution are
computed. Preserve explicit activeProvider values and existing named-provider
behavior, and add a regression test covering a single nameless provider with no
activeProvider.
In `@internal/config/validate_test.go`:
- Around line 32-40: Update TestValidateBytesSelectsNamelessOpenAIProvider to
call normalizeProviders with cfg.Providers and cfg.ActiveProvider, then assert
the returned active profile has Name equal to "openai". Retain the providerKind
field as the intentional legacy alias and keep the existing validation
assertion.
In `@internal/config/writer.go`:
- Around line 826-839: Document the intentional replacement semantics of
ProviderEdit.Description: an empty value clears the saved description rather
than leaving it unchanged. Update only the field’s documentation, preserving the
existing unconditional assignment and partial-edit behavior of the other
ProviderEdit fields.
In `@internal/oauth/manager.go`:
- Around line 152-157: Replace the preflight beforeSave checks with an atomic
config-and-token commit boundary that validates ownership and persists the OAuth
token together, failing closed on validation, lease, or permission errors. Apply
this to the manager persistence flow at internal/oauth/manager.go lines 152-157
and device-login completion at lines 213-218; update
internal/tui/oauth_device.go lines 62-75 to pass the atomic commit operation,
and move ChatGPT persistence at internal/tui/provider_wizard.go lines 209-212
plus generic token login at lines 281-299 onto the same manager commit path.
---
Nitpick comments:
In `@internal/cli/auth_test.go`:
- Around line 538-543: Set ZERO_CRED_STORAGE to the test store backend in both
TestRunAuthLogoutResolvesCatalogIdentity and
TestRunAuthLogoutDeletesCatalogIDToken, matching the setup used by the other
logout tests. Ensure the override is applied before invoking logout so
config.DeleteProviderCredentials does not use the OS keyring.
In `@internal/cli/provider_onboarding_test.go`:
- Around line 46-58: Add a regression test alongside
TestProviderMutationsResolvePersistedIdentity that runs providers use, remove,
and rename against two profiles sharing catalog ID "acme". Assert each command
exits non-zero and verify the configuration remains unchanged, including all
profiles and the active provider.
In `@internal/config/credentials.go`:
- Around line 211-233: Update MigratePlaintextProviderKeysTransactional to
retain the rationale comment for leaving plaintext keys unchanged when op.setKey
fails, and report those failures to the caller without exposing key values.
Track skipped profiles or aggregate an error while continuing migration, then
return that signal alongside the migrated count so startup can warn; preserve
successful migration behavior and publishing logic.
In `@internal/config/provider_commit.go`:
- Around line 117-146: Update setKey and deleteKey to capture and propagate the
error returned by credentialStore() instead of discarding it; return the error
before invoking store.Set or store.Delete, while preserving the existing
snapshot and mutation flow.
- Around line 148-163: Change providerProfileOperation.rollbackCredentials to
return restoration errors from store.Set or store.Delete instead of discarding
them, while preserving the existing comparison guard and continuing rollback
processing. Update runProviderProfileOperation to receive the rollback error and
join it with the publication error, using the existing lock-release
error-joining pattern.
In `@internal/config/writer.go`:
- Around line 780-822: Update RenameProvider to use sameProviderIdentity for
provider collision checks, resolve the destination name before handling
edit.APIKey, and write a newly supplied key directly under newName. Capture the
existing key once for identity-changing renames, avoiding a transaction-local
Get of a key just written and eliminating the redundant previousName
write/migration delete sequence.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 9f6364aa-a637-4cb8-a118-4172aa01f608
📥 Commits
Reviewing files that changed from the base of the PR and between cabfeefc4eb9d247d907d3dee0786fe2e745207d and bf0eba30b7431c993ec4f9f0d04b83a91732619f.
📒 Files selected for processing (29)
internal/cli/app.gointernal/cli/auth.gointernal/cli/auth_test.gointernal/cli/dictation.gointernal/cli/provider_onboarding.gointernal/cli/provider_onboarding_test.gointernal/cli/provider_setup.gointernal/cli/setup.gointernal/config/command_test.gointernal/config/credentials.gointernal/config/credentials_test.gointernal/config/provider_commit.gointernal/config/provider_commit_test.gointernal/config/resolver.gointernal/config/resolver_test.gointernal/config/validate_test.gointernal/config/writer.gointernal/config/writer_test.gointernal/credstore/credstore.gointernal/oauth/manager.gointernal/oauth/manager_test.gointernal/tui/oauth_device.gointernal/tui/onboarding.gointernal/tui/onboarding_test.gointernal/tui/provider_manager.gointernal/tui/provider_wizard.gointernal/tui/provider_wizard_discovery.gointernal/tui/provider_wizard_oauth_test.gointernal/tui/provider_wizard_test.go
blocked until #893 lands
7778f9f9bdd076d1ebea5@Vasanthdev2004 Fixed in d826ec77; the stack is refreshed on top as d1ebea58.
writeConfigData now reports a directory-sync failure after the rename as configPublishedError. The message is unchanged, and Unwrap keeps errors.Is working for existing callers. When runProviderProfileOperation sees that error it keeps the credentials, still returns the error ("provider configuration was committed, but making it durable failed: sync config directory …"), and marks the transaction as published.
TestPublishProviderCredentialKeepsKeyWhenSyncFailsAfterPublish is your probe with assertions. The injected syncConfigDirFn failure fires only once the config on disk already says "apiKeyStored": true, so it really happens after the rename, and the test asserts it was reached. Without the fix:
published config marks apiKeyStored but the store lost the key (present=false, len=0, err=<nil>)The merge also ports #892's new browser-flow pre-save test to this PR's CommitToken hook. The snapshot-consistency and contention Close threads are left for later, as you suggested.
Walkthrough
This change centralizes provider identity resolution and credential mutations. Provider writes now use transactions with locking and rollback. CLI and TUI authentication flows preflight configuration before saving credentials. Provider repair, status, refresh, logout, and model management use canonical identities.
Changes
Provider identity and credential transaction safety
internal/config/...,internal/credstore/...internal/config/credentials.go,internal/config/provider_commit.go,internal/config/provider_lock_*,internal/credstore/credstore.gointernal/cli/...internal/oauth/...,internal/tui/...internal/doctor/...,README*,CHANGELOG.md,docs/oauth-subscriptions.mdEstimated code review effort: 5 (Critical) | ~120 minutes
Possibly related PRs
internal/cli/app.go.Suggested reviewers:
vasanthdev2004,gnanam1990,anandh8xMerge Risk: 🟠 High · up to
2ed0dThis PR centralizes provider and credential writes behind cross-process transactions, but a lock ownership race can still permit concurrent updates and cause provider or credential changes to be lost or overwritten. Some error paths may also expose configuration details, and tests depend on the host credential backend. The lock race should be fixed before merging.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Title check
Explanation
The title clearly summarizes the main change: transactional provider configuration and credential writes. The “(3/4)” suffix accurately identifies the stacked PR sequence and does not obscure the primary purpose.
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment
@coderabbitai helpto get the list of available commands.