-
Notifications
You must be signed in to change notification settings - Fork 0
feat(auth): add createKeyringTokenStore multi-account TokenStore (3/4) #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,12 @@ | ||
| export { SecureStoreUnavailableError, createSecureStore } from './secure-store.js' | ||
| export type { CreateSecureStoreOptions, SecureStore } from './secure-store.js' | ||
|
|
||
| export { createKeyringTokenStore } from './token-store.js' | ||
| export type { CreateKeyringTokenStoreOptions, KeyringTokenStore } from './token-store.js' | ||
|
|
||
| export type { | ||
| TokenStorageLocation, | ||
| TokenStorageResult, | ||
| UserRecord, | ||
| UserRecordStore, | ||
| } from './types.js' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import { describe, expect, it } from 'vitest' | ||
|
|
||
| import { buildSingleSlot, buildUserRecords } from '../../test-support/keyring-mocks.js' | ||
| import { writeRecordWithKeyringFallback } from './record-write.js' | ||
| import { SecureStoreUnavailableError } from './secure-store.js' | ||
|
|
||
| type Account = { id: string; label?: string; email: string } | ||
|
|
||
| const account: Account = { id: '42', label: 'me', email: 'a@b.c' } | ||
|
|
||
| describe('writeRecordWithKeyringFallback', () => { | ||
| it('writes to the keyring slot and upserts a record with no fallbackToken on the happy path', async () => { | ||
| const secureStore = buildSingleSlot() | ||
| const { store: userRecords, state, upsertSpy } = buildUserRecords<Account>() | ||
|
|
||
| const result = await writeRecordWithKeyringFallback({ | ||
| secureStore, | ||
| userRecords, | ||
| account, | ||
| token: ' tok_secret ', | ||
| }) | ||
|
|
||
| expect(result.storedSecurely).toBe(true) | ||
| expect(secureStore.setSpy).toHaveBeenCalledWith('tok_secret') | ||
| expect(upsertSpy).toHaveBeenCalledWith({ account }) | ||
| expect(state.records.get('42')?.fallbackToken).toBeUndefined() | ||
| }) | ||
|
|
||
| it('falls back to fallbackToken on the user record when the keyring is offline', async () => { | ||
| const secureStore = buildSingleSlot() | ||
| secureStore.setSpy.mockRejectedValueOnce(new SecureStoreUnavailableError('no dbus')) | ||
| const { store: userRecords, state } = buildUserRecords<Account>() | ||
|
|
||
| const result = await writeRecordWithKeyringFallback({ | ||
| secureStore, | ||
| userRecords, | ||
| account, | ||
| token: 'tok_plain', | ||
| }) | ||
|
|
||
| expect(result.storedSecurely).toBe(false) | ||
| expect(state.records.get('42')?.fallbackToken).toBe('tok_plain') | ||
| }) | ||
|
|
||
| it('rethrows non-keyring errors from setSecret without writing the record', async () => { | ||
| const secureStore = buildSingleSlot() | ||
| const cause = new Error('unexpected backend explosion') | ||
| secureStore.setSpy.mockRejectedValueOnce(cause) | ||
| const { store: userRecords, state } = buildUserRecords<Account>() | ||
|
|
||
| await expect( | ||
| writeRecordWithKeyringFallback({ | ||
| secureStore, | ||
| userRecords, | ||
| account, | ||
| token: 'tok', | ||
| }), | ||
| ).rejects.toBe(cause) | ||
| expect(state.records.size).toBe(0) | ||
| }) | ||
|
|
||
| it('rolls back the keyring write when upsert fails (no orphan credential)', async () => { | ||
| const secureStore = buildSingleSlot() | ||
| const { store: userRecords, upsertSpy } = buildUserRecords<Account>() | ||
| upsertSpy.mockRejectedValueOnce(new Error('disk full')) | ||
|
|
||
| await expect( | ||
| writeRecordWithKeyringFallback({ | ||
| secureStore, | ||
| userRecords, | ||
| account, | ||
| token: 'tok', | ||
| }), | ||
| ).rejects.toThrow('disk full') | ||
| expect(secureStore.deleteSpy).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it('does not rollback the keyring on upsert failure when the write went to fallbackToken', async () => { | ||
| // No successful keyring write happened, so there is nothing to roll | ||
| // back. Verify the helper doesn't accidentally call deleteSecret | ||
| // in this branch. | ||
| const secureStore = buildSingleSlot() | ||
| secureStore.setSpy.mockRejectedValueOnce(new SecureStoreUnavailableError('no dbus')) | ||
| const { store: userRecords, upsertSpy } = buildUserRecords<Account>() | ||
| upsertSpy.mockRejectedValueOnce(new Error('disk full')) | ||
|
|
||
| await expect( | ||
| writeRecordWithKeyringFallback({ | ||
| secureStore, | ||
| userRecords, | ||
| account, | ||
| token: 'tok', | ||
| }), | ||
| ).rejects.toThrow('disk full') | ||
| expect(secureStore.deleteSpy).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import type { AuthAccount } from '../types.js' | ||
| import { type SecureStore, SecureStoreUnavailableError } from './secure-store.js' | ||
| import type { UserRecord, UserRecordStore } from './types.js' | ||
|
|
||
| type WriteRecordOptions<TAccount extends AuthAccount> = { | ||
| /** Per-account keyring slot, already configured by the caller (e.g. via `createSecureStore`). */ | ||
| secureStore: SecureStore | ||
| userRecords: UserRecordStore<TAccount> | ||
| account: TAccount | ||
| token: string | ||
| } | ||
|
|
||
| type WriteRecordResult = { | ||
| /** `true` when the secret landed in the OS keyring; `false` when the keyring was unavailable and the token was written to `fallbackToken` on the user record. */ | ||
| storedSecurely: boolean | ||
| } | ||
|
|
||
| /** | ||
| * Shared keyring-then-record write used by `createKeyringTokenStore.set` and | ||
| * `migrateLegacyAuth`. Encapsulates the order-of-operations contract that | ||
| * matters for credential safety: | ||
| * | ||
| * 1. Keyring `setSecret` first. On `SecureStoreUnavailableError`, swallow | ||
| * the failure and record a `fallbackToken` on the user record instead. | ||
| * Any other error rethrows. | ||
| * 2. `userRecords.upsert(record)`. On failure, best-effort rollback the | ||
| * keyring write so we don't leave an orphan credential for an account | ||
| * cli-core never managed to register. Original error rethrows. | ||
| * | ||
| * Default promotion (`setDefaultId`) is intentionally **not** in here — both | ||
| * call sites do it best-effort outside the critical section because it is a | ||
| * preference, not a correctness requirement, and an error there must not | ||
| * dirty up a successful credential write. | ||
| */ | ||
| export async function writeRecordWithKeyringFallback<TAccount extends AuthAccount>( | ||
|
scottlovegrove marked this conversation as resolved.
|
||
| options: WriteRecordOptions<TAccount>, | ||
| ): Promise<WriteRecordResult> { | ||
| const { secureStore, userRecords, account, token } = options | ||
| const trimmed = token.trim() | ||
|
|
||
| let storedSecurely = false | ||
| try { | ||
| await secureStore.setSecret(trimmed) | ||
| storedSecurely = true | ||
| } catch (error) { | ||
| if (!(error instanceof SecureStoreUnavailableError)) throw error | ||
| } | ||
|
|
||
| const record: UserRecord<TAccount> = storedSecurely | ||
| ? { account } | ||
| : { account, fallbackToken: trimmed } | ||
|
|
||
| try { | ||
| await userRecords.upsert(record) | ||
| } catch (error) { | ||
| if (storedSecurely) { | ||
| try { | ||
| await secureStore.deleteSecret() | ||
| } catch { | ||
| // best-effort — the user record failure is the real cause | ||
| } | ||
| } | ||
| throw error | ||
| } | ||
|
|
||
| return { storedSecurely } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.