refactor(cli): auth/workspace cleanup — record-backed token store (#37219)

Co-authored-by: Yunlu Wen <yunlu.wen@dify.ai>
This commit is contained in:
Xiyuan ChenandYunlu Wen authored and GitHub committed 2026-06-12 03:10:54 +00:00
1 parent 62ee1fff62
commit a650ffc00a
45 files changed
+795 -620

No files matched your search

+3 -21
View File
@@ -1,30 +1,12 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { useTempConfigDir } from '@test/fixtures/config-dir'
import { describe, expect, it } from 'vitest'
import { loadConfig } from '@/config/config-loader'
import { emptyConfig } from '@/config/schema'
import { saveConfig } from './config-writer'
import { ENV_CONFIG_DIR } from './dir'
import { getConfigurationStore } from './manager'
describe('saveConfig', () => {
let dir: string
let prevConfigDir: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'difyctl-w-'))
prevConfigDir = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prevConfigDir === undefined)
delete process.env[ENV_CONFIG_DIR]
else
process.env[ENV_CONFIG_DIR] = prevConfigDir
await rm(dir, { recursive: true, force: true })
})
useTempConfigDir('difyctl-w-')
it('stamps schema_version=1 even if caller passed 0', () => {
saveConfig(getConfigurationStore(), { ...emptyConfig() })
+138
View File
@@ -0,0 +1,138 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
type EntryArgs = { service: string, username: string }
const passwords = new Map<string, string>()
const constructed: EntryArgs[] = []
let getPasswordError: Error | null = null
let setPasswordError: Error | null = null
class FakeEntry {
private readonly key: string
constructor(service: string, username: string) {
constructed.push({ service, username })
this.key = `${service}::${username}`
}
setPassword(value: string): void {
if (setPasswordError !== null)
throw setPasswordError
passwords.set(this.key, value)
}
getPassword(): string | null {
if (getPasswordError !== null)
throw getPasswordError
return passwords.get(this.key) ?? null
}
deletePassword(): boolean {
if (!passwords.has(this.key))
return false
passwords.delete(this.key)
return true
}
}
vi.mock('@napi-rs/keyring', () => ({
Entry: FakeEntry,
}))
const { KeychainTokenStore } = await import('./token-store')
const SERVICE = 'difyctl-test'
beforeEach(() => {
passwords.clear()
constructed.length = 0
getPasswordError = null
setPasswordError = null
})
describe('KeychainTokenStore', () => {
it('round-trips a bearer through write/read', () => {
const store = new KeychainTokenStore(SERVICE)
store.write('https://cloud.dify.ai', 'a@x.com', 'dfoa_secret')
expect(store.read('https://cloud.dify.ai', 'a@x.com')).toBe('dfoa_secret')
})
it('returns empty string for an absent credential', () => {
const store = new KeychainTokenStore(SERVICE)
expect(store.read('https://cloud.dify.ai', 'missing@x.com')).toBe('')
})
it('removes a credential, after which read returns empty string', () => {
const store = new KeychainTokenStore(SERVICE)
store.write('h', 'e', 'dfoa_secret')
store.remove('h', 'e')
expect(store.read('h', 'e')).toBe('')
})
it('treats remove of an absent credential as a no-op', () => {
const store = new KeychainTokenStore(SERVICE)
expect(() => store.remove('h', 'absent')).not.toThrow()
})
it('uses the legacy entry name tokens.<host>.<email> (back-compat)', () => {
const store = new KeychainTokenStore(SERVICE)
store.write('https://cloud.dify.ai', 'a@x.com', 'dfoa_secret')
expect(constructed).toContainEqual({
service: SERVICE,
username: 'tokens.https://cloud.dify.ai.a@x.com',
})
})
it('keeps host and email literal — dots, colons, and @ are never split', () => {
const store = new KeychainTokenStore(SERVICE)
const host = 'https://my.dify.example.com:8443'
const email = 'first.last@sub.example.com'
store.write(host, email, 'dfoa_literal')
expect(store.read(host, email)).toBe('dfoa_literal')
expect(constructed).toContainEqual({
service: SERVICE,
username: `tokens.${host}.${email}`,
})
})
it('returns empty string when the stored value decodes to a non-string', () => {
const store = new KeychainTokenStore(SERVICE)
passwords.set(`${SERVICE}::tokens.h.e`, '123')
expect(store.read('h', 'e')).toBe('')
})
it('returns empty string when the stored value is not valid JSON', () => {
const store = new KeychainTokenStore(SERVICE)
passwords.set(`${SERVICE}::tokens.h.e`, 'not-json')
expect(store.read('h', 'e')).toBe('')
})
it('throws KeyringUnavailable (not empty string) when keyring access fails on read', () => {
getPasswordError = new Error('keyring locked')
const store = new KeychainTokenStore(SERVICE)
let caught: unknown
try {
store.read('h', 'e')
}
catch (err) {
caught = err
}
expect(caught).toBeInstanceOf(BaseError)
expect((caught as BaseError).code).toBe(ErrorCode.KeyringUnavailable)
})
it('throws KeyringUnavailable when keyring access fails on write', () => {
setPasswordError = new Error('keyring locked')
const store = new KeychainTokenStore(SERVICE)
let caught: unknown
try {
store.write('h', 'e', 'dfoa_secret')
}
catch (err) {
caught = err
}
expect(caught).toBeInstanceOf(BaseError)
expect((caught as BaseError).code).toBe(ErrorCode.KeyringUnavailable)
})
})
+61 -23
View File
@@ -1,28 +1,29 @@
import type { Key, Store } from './store'
import type { TokenStore } from './token-store'
import { describe, expect, it, vi } from 'vitest'
import { getTokenStore } from './manager'
import { detectTokenStore, getTokenStore } from './manager'
function memStore(label: string): Store & { _label: string } {
const map = new Map<string, unknown>()
function memStore(label: string): TokenStore & { _label: string } {
const map = new Map<string, string>()
const k = (h: string, e: string): string => `${h} ${e}`
return {
_label: label,
get<T>(key: Key<T>): T {
return (map.get(key.key) as T | undefined) ?? key.default
read(host: string, email: string): string {
return map.get(k(host, email)) ?? ''
},
set<T>(key: Key<T>, value: T): void {
map.set(key.key, value)
write(host: string, email: string, bearer: string): void {
map.set(k(host, email), bearer)
},
unset<T>(key: Key<T>): void {
map.delete(key.key)
remove(host: string, email: string): void {
map.delete(k(host, email))
},
}
}
describe('getTokenStore', () => {
describe('detectTokenStore', () => {
it('returns keychain store when probe succeeds', () => {
const k = memStore('keyring')
const f = memStore('file')
const result = getTokenStore({
const result = detectTokenStore({
factory: { keyring: () => k, file: () => f },
})
expect(result.mode).toBe('keychain')
@@ -32,12 +33,10 @@ describe('getTokenStore', () => {
it('falls back to file when keyring set throws', () => {
const k = memStore('keyring')
const f = memStore('file')
k.set = vi.fn(
() => {
throw new Error('locked')
},
)
const result = getTokenStore({
k.write = vi.fn(() => {
throw new Error('locked')
})
const result = detectTokenStore({
factory: { keyring: () => k, file: () => f },
})
expect(result.mode).toBe('file')
@@ -47,8 +46,8 @@ describe('getTokenStore', () => {
it('falls back to file when probe round-trip mismatches', () => {
const k = memStore('keyring')
const f = memStore('file')
k.get = vi.fn(() => 'something-else') as Store['get']
const result = getTokenStore({
k.read = vi.fn(() => 'something-else') as TokenStore['read']
const result = detectTokenStore({
factory: { keyring: () => k, file: () => f },
})
expect(result.mode).toBe('file')
@@ -57,7 +56,7 @@ describe('getTokenStore', () => {
it('falls back to file when keyring constructor throws', () => {
const f = memStore('file')
const result = getTokenStore({
const result = detectTokenStore({
factory: {
keyring: () => { throw new Error('no backend') },
file: () => f,
@@ -70,9 +69,48 @@ describe('getTokenStore', () => {
it('cleans up probe entry after successful probe', () => {
const k = memStore('keyring')
const f = memStore('file')
getTokenStore({
detectTokenStore({
factory: { keyring: () => k, file: () => f },
})
expect(k.get({ key: '__difyctl_probe__', default: '' })).toBe('')
expect(k.read('__difyctl_probe__', '__difyctl_probe__')).toBe('')
})
it('removes the probe entry even when the probe read throws', () => {
const k = memStore('keyring')
const f = memStore('file')
const removeSpy = vi.spyOn(k, 'remove')
k.read = vi.fn(() => {
throw new Error('read boom')
}) as TokenStore['read']
const result = detectTokenStore({
factory: { keyring: () => k, file: () => f },
})
expect(removeSpy).toHaveBeenCalledWith('__difyctl_probe__', '__difyctl_probe__')
expect(result.mode).toBe('file')
expect(result.store).toBe(f)
})
})
describe('getTokenStore', () => {
it('constructs the keychain backend without probing when mode is keychain', () => {
const k = memStore('keyring')
const f = memStore('file')
k.write = vi.fn(() => {
throw new Error('probe must never run on the read path')
})
const store = getTokenStore('keychain', {
factory: { keyring: () => k, file: () => f },
})
expect(store).toBe(k)
})
it('constructs the file backend when mode is file, never touching the keyring', () => {
const keyringFactory = vi.fn(() => memStore('keyring'))
const f = memStore('file')
const store = getTokenStore('file', {
factory: { keyring: keyringFactory, file: () => f },
})
expect(store).toBe(f)
expect(keyringFactory).not.toHaveBeenCalled()
})
})
+34 -31
View File
@@ -1,7 +1,9 @@
import type { Key, StorageMode, Store } from './store'
import type { StorageMode, Store } from './store'
import type { TokenStore } from './token-store'
import { join } from 'node:path'
import { resolveCacheDir, resolveConfigDir } from './dir'
import { KeyringBasedStore, YamlStore } from './store'
import { YamlStore } from './store'
import { FileTokenStore, KeychainTokenStore } from './token-store'
export const CACHE_APP_INFO = 'app-info'
export const CACHE_NUDGE = 'nudge'
@@ -31,51 +33,52 @@ export function getHostStore(): YamlStore {
return getStore(join(resolveConfigDir(), HOSTS_FILE))
}
const PROBE_KEY: Key<string> = { key: '__difyctl_probe__', default: '' }
const PROBE_HOST = '__difyctl_probe__'
const PROBE_EMAIL = '__difyctl_probe__'
const PROBE_VALUE = 'probe-v1'
export type GetTokenStoreOptions = {
readonly factory?: {
readonly keyring?: () => Store
readonly file?: () => Store
readonly keyring?: () => TokenStore
readonly file?: () => TokenStore
}
}
const TOKEN_STORE_OPENERS: Record<StorageMode, (opts: GetTokenStoreOptions) => TokenStore> = {
file: opts => opts.factory?.file?.() ?? new FileTokenStore(join(resolveConfigDir(), TOKENS_FILE)),
keychain: opts => opts.factory?.keyring?.() ?? new KeychainTokenStore(KEYRING_SERVICE),
}
/**
* Single entry point for the credential store. Probes the OS keyring; if it
* round-trips a value, returns the keychain-backed store. Otherwise falls
* back to the YAML file at `<configDir>/tokens.yml`. Both implementations
* satisfy the `Store` interface, so callers interact uniformly.
*
* Business logic should always obtain the token store through this factory
* rather than constructing one directly.
* Decide which credential backend to use by probing the OS keyring with a
* write/read/remove round-trip. The probe MUTATES the keyring, so call this
* only where a credential is about to be written anyway (login).
*/
export function getTokenStore(opts: GetTokenStoreOptions = {}): { store: Store, mode: StorageMode } {
const fileFactory = opts.factory?.file ?? (() => getStore(join(resolveConfigDir(), TOKENS_FILE)))
const keyringFactory = opts.factory?.keyring ?? (() => new KeyringBasedStore(KEYRING_SERVICE))
export function detectTokenStore(opts: GetTokenStoreOptions = {}): { store: TokenStore, mode: StorageMode } {
// DIFY_E2E_NO_KEYRING=1 forces file-based storage in E2E tests to avoid
// macOS keychain UI prompts blocking child processes spawned by vitest.
if (process.env.DIFY_E2E_NO_KEYRING === '1')
return { store: fileFactory(), mode: 'file' }
return { store: TOKEN_STORE_OPENERS.file(opts), mode: 'file' }
try {
const k = keyringFactory()
k.set(PROBE_KEY, PROBE_VALUE)
const got = k.get(PROBE_KEY)
k.unset(PROBE_KEY)
if (got !== PROBE_VALUE)
throw new Error('keyring round-trip mismatch')
return { store: k, mode: 'keychain' }
}
catch {
return { store: fileFactory(), mode: 'file' }
const k = TOKEN_STORE_OPENERS.keychain(opts)
k.write(PROBE_HOST, PROBE_EMAIL, PROBE_VALUE)
let got = ''
try {
got = k.read(PROBE_HOST, PROBE_EMAIL)
}
finally {
k.remove(PROBE_HOST, PROBE_EMAIL)
}
if (got === PROBE_VALUE)
return { store: k, mode: 'keychain' }
}
catch { /* keyring unavailable → fall through to file */ }
return { store: TOKEN_STORE_OPENERS.file(opts), mode: 'file' }
}
/**
* Maps an auth identity (host + accountId) to a `Store` key. All token store
* reads/writes in business logic go through this helper so the on-disk /
* keyring layout stays consistent.
* Construct the credential backend the registry already recorded at login.
*/
export function tokenKey(host: string, accountId: string): Key<string> {
return { key: `tokens.${host}.${accountId}`, default: '' }
export function getTokenStore(mode: StorageMode, opts: GetTokenStoreOptions = {}): TokenStore {
return TOKEN_STORE_OPENERS[mode](opts)
}
+2 -1
View File
@@ -21,7 +21,8 @@ export type Store = {
unset: <T>(key: Key<T>) => void
}
export type StorageMode = 'keychain' | 'file'
export const STORAGE_MODES = ['keychain', 'file'] as const
export type StorageMode = typeof STORAGE_MODES[number]
abstract class FileBasedStore implements Store {
filePath: string
+81
View File
@@ -0,0 +1,81 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { FileTokenStore } from './token-store'
describe('FileTokenStore', () => {
let dir: string
let file: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'difyctl-tok-'))
file = join(dir, 'tokens.yml')
})
afterEach(() => rmSync(dir, { recursive: true, force: true }))
it('returns empty string for a missing credential', () => {
const s = new FileTokenStore(file)
expect(s.read('https://cloud.dify.ai', 'a@x.com')).toBe('')
})
it('round-trips a bearer with dots and @ kept literal', () => {
const s = new FileTokenStore(file)
s.write('https://cloud.dify.ai', 'a.b@x.com', 'dfoa_secret')
expect(s.read('https://cloud.dify.ai', 'a.b@x.com')).toBe('dfoa_secret')
})
it('keeps multiple accounts under one host and isolates hosts', () => {
const s = new FileTokenStore(file)
s.write('https://cloud.dify.ai', 'a@x.com', 'A')
s.write('https://cloud.dify.ai', 'b@x.com', 'B')
s.write('https://self.example.com', 'a@x.com', 'C')
expect(s.read('https://cloud.dify.ai', 'a@x.com')).toBe('A')
expect(s.read('https://cloud.dify.ai', 'b@x.com')).toBe('B')
expect(s.read('https://self.example.com', 'a@x.com')).toBe('C')
})
it('persists the versioned nested shape on disk', () => {
const s = new FileTokenStore(file)
s.write('https://cloud.dify.ai', 'a@x.com', 'A')
const raw = readFileSync(file, 'utf8')
expect(raw).toContain('version: 1')
expect(raw).toContain('https://cloud.dify.ai')
expect(raw).toContain('a@x.com')
})
it('reads empty when the document version is an unknown future version', () => {
writeFileSync(file, 'version: 999\ntokens:\n "h":\n "e": "x"\n')
const s = new FileTokenStore(file)
expect(s.read('h', 'e')).toBe('')
})
it('reads tokens from legacy format (no version field) for transparent migration', () => {
writeFileSync(file, 'tokens:\n "h":\n "e": "dfoa_legacy"\n')
const s = new FileTokenStore(file)
expect(s.read('h', 'e')).toBe('dfoa_legacy')
})
it('preserves existing tokens and stamps version when writing to a legacy file', () => {
writeFileSync(file, 'tokens:\n "h":\n "existing@x": "dfoa_existing"\n')
const s = new FileTokenStore(file)
s.write('h', 'new@x', 'dfoa_new')
expect(s.read('h', 'existing@x')).toBe('dfoa_existing')
expect(s.read('h', 'new@x')).toBe('dfoa_new')
expect(readFileSync(file, 'utf8')).toContain('version: 1')
})
it('remove deletes the credential and prunes the empty host map', () => {
const s = new FileTokenStore(file)
s.write('https://cloud.dify.ai', 'a@x.com', 'A')
s.remove('https://cloud.dify.ai', 'a@x.com')
expect(s.read('https://cloud.dify.ai', 'a@x.com')).toBe('')
const raw = readFileSync(file, 'utf8')
expect(raw).not.toContain('cloud.dify.ai')
})
it('remove is a no-op for an absent credential', () => {
const s = new FileTokenStore(file)
expect(() => s.remove('h', 'e')).not.toThrow()
})
})
+130
View File
@@ -0,0 +1,130 @@
import { Entry } from '@napi-rs/keyring'
import { BaseError } from '@/errors/base'
import { ErrorCode } from '@/errors/codes'
import { YamlStore } from './store'
/**
* Credential store keyed by an opaque (host, email) pair.
*/
export type TokenStore = {
read: (host: string, email: string) => string
write: (host: string, email: string, bearer: string) => void
remove: (host: string, email: string) => void
}
const DOC_VERSION = 1
type TokenDoc = {
version?: number
tokens?: Record<string, Record<string, string>>
}
export class FileTokenStore implements TokenStore {
private readonly store: YamlStore
constructor(filePath: string) {
this.store = new YamlStore(filePath)
}
read(host: string, email: string): string {
const doc = this.store.getTyped<TokenDoc>()
if (doc === null)
return ''
// missing version = legacy pre-v1 format (same data shape); future unknown versions are rejected
if (doc.version !== undefined && doc.version !== DOC_VERSION)
return ''
return doc.tokens?.[host]?.[email] ?? ''
}
write(host: string, email: string, bearer: string): void {
const doc = this.load()
const hostMap = doc.tokens[host] ?? {}
hostMap[email] = bearer
doc.tokens[host] = hostMap
this.store.setTyped(doc)
}
remove(host: string, email: string): void {
const doc = this.store.getTyped<TokenDoc>()
if (doc === null)
return
if (doc.version !== undefined && doc.version !== DOC_VERSION)
return
const tokens = doc.tokens ?? {}
const hostMap = tokens[host]
if (hostMap === undefined || !(email in hostMap))
return
delete hostMap[email]
if (Object.keys(hostMap).length === 0)
delete tokens[host]
this.store.setTyped({ version: DOC_VERSION, tokens })
}
private load(): { version: number, tokens: Record<string, Record<string, string>> } {
const doc = this.store.getTyped<TokenDoc>()
if (doc === null)
return { version: DOC_VERSION, tokens: {} }
if (doc.version !== undefined && doc.version !== DOC_VERSION)
return { version: DOC_VERSION, tokens: {} }
return { version: DOC_VERSION, tokens: (doc.tokens ?? {}) as Record<string, Record<string, string>> }
}
}
/**
* One OS-keyring entry per (host, email).
*/
export class KeychainTokenStore implements TokenStore {
private readonly service: string
constructor(service: string) {
this.service = service
}
read(host: string, email: string): string {
let raw: string | null
try {
raw = new Entry(this.service, entryName(host, email)).getPassword()
}
catch (err) {
throw keyringUnavailableError(err)
}
if (raw === null || raw === undefined || raw === '')
return ''
try {
const parsed: unknown = JSON.parse(raw)
return typeof parsed === 'string' ? parsed : ''
}
catch {
return ''
}
}
write(host: string, email: string, bearer: string): void {
try {
new Entry(this.service, entryName(host, email)).setPassword(JSON.stringify(bearer))
}
catch (err) {
throw keyringUnavailableError(err)
}
}
remove(host: string, email: string): void {
try {
new Entry(this.service, entryName(host, email)).deletePassword()
}
catch { /* missing entry is fine */ }
}
}
function entryName(host: string, email: string): string {
return `tokens.${host}.${email}`
}
function keyringUnavailableError(cause: unknown): BaseError {
return new BaseError({
code: ErrorCode.KeyringUnavailable,
message: 'OS keychain is unreachable',
hint: 'credentials are stored in the system keychain but it could not be accessed; unlock the keychain (or the login session) and retry',
cause,
})
}