#894

Transact provider config and credential writes (3/4)

OpenPierrunoYTwants to merge intofrom

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-check
  • go vet ./...
  • go test ./...
  • go test -race ./internal/config ./internal/cli ./internal/tui -count=1
  • go run ./cmd/zero-release build
  • go run ./cmd/zero-release smoke
  • make 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-config to 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

125
coderabbitai[bot]3mo ago

NOTE

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 2ed0de15ba306282f037f1b2bb3fe4045bbd018a
  • Latest commit, not reviewed: d1ebea585898a78355faaefe3a8d918c016b4f67

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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

Layer / File(s)Summary
Identity resolution and provider matching
internal/config/..., internal/credstore/...
Provider resolution now supports exact names, normalized identities, catalog ownership, unnamed OpenAI profiles, Unicode distinctions, and ambiguity checks.
Credential transactions and locking
internal/config/credentials.go, internal/config/provider_commit.go, internal/config/provider_lock_*, internal/credstore/credstore.go
Credential and provider changes now use serialized transactions, rollback, OS-level locks, lock-release error handling, and transactional plaintext-key migration.
CLI authentication and provider commands
internal/cli/...
CLI authentication, provider mutations, setup, repair, status, refresh, logout, migration reporting, and dependency wiring now use resolved identities and transactional configuration APIs.
OAuth manager and TUI management
internal/oauth/..., internal/tui/...
OAuth flows now preflight configuration, commit tokens through callbacks, enforce catalog ownership, synchronize provider state, and redact credential-related errors.
Diagnostics and documentation
internal/doctor/..., README*, CHANGELOG.md, docs/oauth-subscriptions.md
Diagnostics report provider-resolution failures, and documentation describes provider repair and OAuth validation behavior.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Gitlawb/zero#366: Both changes centralize dependency wiring and provider construction in internal/cli/app.go.
  • Gitlawb/zero#560: Both changes modify OAuth provider-profile login and provider-management persistence paths.

Suggested reviewers: vasanthdev2004, gnanam1990, anandh8x

Merge Risk: 🟠 High · up to 2ed0d

This 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)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 42.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 351 functions across 52 files.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe 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 prim…
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
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)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot]requested changes3mo ago
coderabbitai[bot]3mo ago

Actionable comments posted: 7

🧹 Nitpick comments (6)
internal/cli/auth_test.go (1)

538-543: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Pin the credential-store backend in these two logout tests.

TestRunAuthLogoutResolvesCatalogIdentity and TestRunAuthLogoutDeletesCatalogIDToken do not set ZERO_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 assert exitSuccess, 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 win

Add an ambiguous-catalog-id failure case.

The table covers only resolutions that succeed. remove is destructive, and the resolution rule that protects it is "reject a catalog id claimed by more than one profile". Nothing here pins that rule for providers use|remove|rename.

Add a case with two profiles sharing catalogId: "acme", address it as acme, 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 value

Do not discard the credentialStore() error in setKey and deleteKey.

The code is correct today. snapshotCredential opens the store first and returns any error, and credentialStore() memoizes op.store, so the second call cannot fail. The safety depends on that call order alone. If snapshotCredential ever returns early before the store is opened, store becomes nil and the next store.Set/store.Delete panics.

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 win

Surface 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.json diverge, 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 rollbackCredentials and join it into the error runProviderProfileOperation returns, 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 value

Store a newly supplied key directly under the new name instead of writing it twice.

When an edit supplies both APIKey and an identity-changing NewName, line 799 stores the key under previousName, then lines 810-820 read it back, store it under newName, and delete previousName. 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.NormalizeProvider directly for the collision check. RenameProvider expresses the identical check through the sameProviderIdentity helper. Use the helper in both places.
  • The migration Get at 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 win

Silent continue on setKey failure leaves the plaintext key in config.json with 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 MigratePlaintextProviderKeys at 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 in config.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.go
  • internal/cli/auth.go
  • internal/cli/auth_test.go
  • internal/cli/dictation.go
  • internal/cli/provider_onboarding.go
  • internal/cli/provider_onboarding_test.go
  • internal/cli/provider_setup.go
  • internal/cli/setup.go
  • internal/config/command_test.go
  • internal/config/credentials.go
  • internal/config/credentials_test.go
  • internal/config/provider_commit.go
  • internal/config/provider_commit_test.go
  • internal/config/resolver.go
  • internal/config/resolver_test.go
  • internal/config/validate_test.go
  • internal/config/writer.go
  • internal/config/writer_test.go
  • internal/credstore/credstore.go
  • internal/oauth/manager.go
  • internal/oauth/manager_test.go
  • internal/tui/oauth_device.go
  • internal/tui/onboarding.go
  • internal/tui/onboarding_test.go
  • internal/tui/provider_manager.go
  • internal/tui/provider_wizard.go
  • internal/tui/provider_wizard_discovery.go
  • internal/tui/provider_wizard_oauth_test.go
  • internal/tui/provider_wizard_test.go
jatmn3mo ago

blocked until #893 lands

PierrunoYT1mo ago

@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.