From 1a8a91e01df40971cc01495ed71f0648608cc7b2 Mon Sep 17 00:00:00 2001 From: Albert Date: Sun, 8 Nov 2026 09:35:04 +0000 Subject: [PATCH 1/2] fix(config): store Windows secrets in Credential Manager --- .github/workflows/verify.yml | 5 + CHANGELOG.md | 1 + README.md | 14 ++- cli/src/lib/env.ts | 4 +- cli/src/lib/secrets-windows.test.ts | 109 +++++++++++++++++ cli/src/lib/secrets.ts | 42 ++++++- cli/src/lib/windows-credentials.test.ts | 55 +++++++++ cli/src/lib/windows-credentials.ts | 153 ++++++++++++++++++++++++ 8 files changed, 378 insertions(+), 5 deletions(-) create mode 100644 cli/src/lib/secrets-windows.test.ts create mode 100644 cli/src/lib/windows-credentials.test.ts create mode 100644 cli/src/lib/windows-credentials.ts diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 1518988..5e7b9a6 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -130,6 +130,11 @@ jobs: - name: Verify user-directory storage through CLI commands run: bun test tests/user-directories.test.ts + - name: Verify Windows native credential storage + if: runner.os == 'Windows' + working-directory: cli + run: bun test src/lib/windows-credentials.test.ts + - name: Build npm bundle working-directory: cli run: bun run build diff --git a/CHANGELOG.md b/CHANGELOG.md index 712674f..9d7e8b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Store Windows credentials in the current user's Credential Manager by default, migrate existing file credentials after successful native storage, and fail closed on vault errors. The explicit file backend remains available for CI. - Stop queries that run longer than 6 minutes from failing with `Request failed (network error): … (The operation timed out.)`. `--read-timeout` is now the only limit on query streams, and `0` means no limit. - Keep the TypeScript manifest compiler out of CLI downloads by installing it with the cached single-file preview runtime. diff --git a/README.md b/README.md index 233b56d..46ea29b 100644 --- a/README.md +++ b/README.md @@ -238,8 +238,18 @@ Configuration is stored in `ALTERTABLE_CONFIG_HOME` when set, otherwise `$XDG_CONFIG_HOME/altertable`, otherwise `~/.config/altertable`. Directory settings must be absolute. The default home directory follows OS conventions (`HOME` on Unix, `USERPROFILE` on Windows). -Credentials use macOS Keychain when available; the file fallback stores plaintext credentials. -Keep the configuration directory private. +Credentials use macOS Keychain when available and Windows Credential Manager on +Windows. Windows storage uses the current user's native credential vault through +Windows PowerShell; secret values are passed over stdin, not process arguments. +Existing Windows file credentials migrate to Credential Manager when read, and +are removed from the file only after native storage succeeds. Native-store errors +fail the command instead of silently saving plaintext. + +Other systems use a plaintext file with Unix mode `600`. You can explicitly opt +into the file backend with `ALTERTABLE_SECRET_BACKEND=file` (for example, in CI), +or require Windows Credential Manager with `ALTERTABLE_SECRET_BACKEND=windows`. +Keep the configuration directory private; Windows ACLs are not checked when the +file backend is explicitly selected. Named profiles store credentials and endpoint overrides per environment. Global display defaults (`query_layout`, `query_max_width`, `query_pager`) stay in the root config and apply to all profiles. diff --git a/cli/src/lib/env.ts b/cli/src/lib/env.ts index 78d095a..9526d6f 100644 --- a/cli/src/lib/env.ts +++ b/cli/src/lib/env.ts @@ -86,7 +86,9 @@ const ENV_SCHEMA = { ALTERTABLE_OAUTH_REDIRECT_PORT: { parse: port }, ALTERTABLE_OAUTH_SCOPE: { parse: optional }, ALTERTABLE_PROFILE: { parse: optional }, - ALTERTABLE_SECRET_BACKEND: { parse: oneOf(['file', 'keychain'] as const) }, + ALTERTABLE_SECRET_BACKEND: { + parse: oneOf(['file', 'keychain', 'windows'] as const), + }, ALTERTABLE_UPDATE_CHECK: { parse: oneOf(['0', '1', 'false', 'true', 'never'] as const), }, diff --git a/cli/src/lib/secrets-windows.test.ts b/cli/src/lib/secrets-windows.test.ts new file mode 100644 index 0000000..e71d126 --- /dev/null +++ b/cli/src/lib/secrets-windows.test.ts @@ -0,0 +1,109 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { credentialsFile, kvGet, kvSet } from '@/lib/config.ts'; +import { getProfileId } from '@/lib/profile-store.ts'; +import { createSecretStore } from '@/lib/secrets.ts'; + +let directory = ''; +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), 'altertable-wincred-test-')); + process.env.ALTERTABLE_CONFIG_HOME = directory; + delete process.env.ALTERTABLE_SECRET_BACKEND; +}); +afterEach(() => { + rmSync(directory, { recursive: true, force: true }); + delete process.env.ALTERTABLE_CONFIG_HOME; + delete process.env.ALTERTABLE_SECRET_BACKEND; +}); + +function fakeWindowsStore() { + const values = new Map(); + const calls: { args: string[]; input: string }[] = []; + const failures = new Set(); + const store = createSecretStore({ + platform: 'win32', + spawnSync(_command, args, options) { + if (typeof options.input !== 'string') + throw new Error('Expected JSON stdin'); + const input = options.input; + calls.push({ args, input }); + const request = JSON.parse(input) as { + action: string; + account: string; + value?: string; + }; + if (failures.has(request.action)) return { status: 1, stdout: '' }; + if (request.action === 'set') values.set(request.account, request.value!); + if (request.action === 'delete') values.delete(request.account); + return { + status: 0, + stdout: JSON.stringify({ + value: values.get(request.account) ?? null, + exists: values.has(request.account), + }), + }; + }, + }); + return { store, values, calls, failures }; +} + +test('Windows defaults to Credential Manager without writing plaintext', () => { + const { store, values, calls } = fakeWindowsStore(); + store.secretSet('api-key', 'atm_native_test', 'default', { fromArgv: true }); + const account = `profile/${getProfileId('default')}/api-key`; + expect(values.get(account)).toBe('atm_native_test'); + expect(store.secretGet('api-key', 'default')).toBe('atm_native_test'); + expect(store.secretExists('api-key', 'default')).toBe(true); + expect(store.secretStoreDisplay()).toBe('Windows Credential Manager'); + expect(existsSync(credentialsFile())).toBe(false); + expect(calls.some(call => call.input.includes('atm_native_test'))).toBe(true); + expect( + calls.every(call => !call.args.join(' ').includes('atm_native_test')) + ).toBe(true); + store.secretDelete('api-key', 'default'); + expect(store.secretExists('api-key', 'default')).toBe(false); +}); + +test('Windows migrates existing file secrets only after native storage succeeds', () => { + const { store, values, failures } = fakeWindowsStore(); + kvSet(credentialsFile(), 'profile/default/api-key', 'atm_legacy_test'); + failures.add('set'); + expect(() => store.secretGet('api-key', 'default')).toThrow( + 'Windows Credential Manager' + ); + expect(kvGet(credentialsFile(), 'profile/default/api-key')).toBe( + 'atm_legacy_test' + ); + failures.clear(); + store.migrateProfileSecrets('default', ['api-key']); + const account = `profile/${getProfileId('default')}/api-key`; + expect(values.get(account)).toBe('atm_legacy_test'); + expect(values.has('profile/default/api-key')).toBe(false); + expect(kvGet(credentialsFile(), 'profile/default/api-key')).toBe(''); +}); + +test('Windows native failures never fall back to a plaintext write or stale file value', () => { + const { store, failures } = fakeWindowsStore(); + failures.add('set'); + expect(() => + store.secretSet('api-key', 'atm_do_not_write', 'default') + ).toThrow('Windows Credential Manager'); + expect(existsSync(credentialsFile())).toBe(false); + kvSet(credentialsFile(), 'profile/default/api-key', 'atm_stale'); + failures.add('get'); + failures.add('exists'); + failures.add('delete'); + expect(() => store.secretGet('api-key', 'default')).toThrow( + 'Windows Credential Manager' + ); + expect(() => store.secretExists('api-key', 'default')).toThrow( + 'Windows Credential Manager' + ); + expect(() => store.secretDelete('api-key', 'default')).toThrow( + 'Windows Credential Manager' + ); + expect(kvGet(credentialsFile(), 'profile/default/api-key')).toBe('atm_stale'); +}); diff --git a/cli/src/lib/secrets.ts b/cli/src/lib/secrets.ts index e8e7ef3..77bf724 100644 --- a/cli/src/lib/secrets.ts +++ b/cli/src/lib/secrets.ts @@ -12,8 +12,9 @@ import { getProfileId, isFromEnvProfile, } from '@/lib/profile-store.ts'; +import { createWindowsCredentialStore } from '@/lib/windows-credentials.ts'; -type SecretBackend = 'macos' | 'file'; +type SecretBackend = 'macos' | 'windows' | 'file'; // `security` returns errSecItemNotFound (-25300) modulo 256 as its process status. const KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44; @@ -107,6 +108,9 @@ export function createSecretStore( secretProcess: SecretProcess = SYSTEM_SECRET_PROCESS ): SecretStore { let fileBackendWarned = false; + const windowsCredentials = createWindowsCredentialStore( + secretProcess.spawnSync.bind(secretProcess) + ); function warnFileBackendOnce(): void { if (fileBackendWarned) return; @@ -130,6 +134,12 @@ export function createSecretStore( function secretBackend(): SecretBackend { const override = readEnv('ALTERTABLE_SECRET_BACKEND') ?? ''; if (override === 'file') return 'file'; + if (override === 'windows') { + if (secretProcess.platform === 'win32') return 'windows'; + throw new CliError( + 'ALTERTABLE_SECRET_BACKEND=windows requires Windows Credential Manager.' + ); + } if (override === 'keychain') { if (secretProcess.platform === 'darwin' && hasSecurityCommand()) return 'macos'; @@ -139,6 +149,7 @@ export function createSecretStore( } if (secretProcess.platform === 'darwin' && hasSecurityCommand()) return 'macos'; + if (secretProcess.platform === 'win32') return 'windows'; return 'file'; } @@ -165,6 +176,16 @@ export function createSecretStore( } function readStoredSecret(storageAccount: string): string { + if (secretBackend() === 'windows') { + const value = windowsCredentials.get(storageAccount); + if (value !== null) return value; + const legacyValue = kvGet(credentialsFile(), storageAccount); + if (legacyValue !== '') { + windowsCredentials.set(storageAccount, legacyValue); + kvUnset(credentialsFile(), storageAccount); + } + return legacyValue; + } if (secretBackend() === 'macos') { const result = secretProcess.spawnSync( 'security', @@ -192,6 +213,10 @@ export function createSecretStore( } function storedSecretExists(storageAccount: string): boolean { + if (secretBackend() === 'windows') { + if (windowsCredentials.exists(storageAccount)) return true; + return kvGet(credentialsFile(), storageAccount) !== ''; + } if (secretBackend() === 'macos') { const result = secretProcess.spawnSync( 'security', @@ -210,6 +235,9 @@ export function createSecretStore( } function deleteStoredSecret(storageAccount: string): void { + if (secretBackend() === 'windows') { + windowsCredentials.delete(storageAccount); + } if (secretBackend() === 'macos') { const result = secretProcess.spawnSync( 'security', @@ -243,6 +271,11 @@ export function createSecretStore( ensureProfileId(profileName) ); const backend = secretBackend(); + if (backend === 'windows') { + windowsCredentials.set(storageAccount, value); + kvUnset(credentialsFile(), storageAccount); + return; + } if (backend === 'macos' && !options?.fromArgv) { secretSetMacos(storageAccount, value); return; @@ -300,6 +333,8 @@ export function createSecretStore( if (!storedSecretExists(storageAccount)) { if (secretBackend() === 'macos') { secretSetMacos(storageAccount, value); + } else if (secretBackend() === 'windows') { + windowsCredentials.set(storageAccount, value); } else { kvSet(credentialsFile(), storageAccount, value); chmodSync(credentialsFile(), 0o600); @@ -312,7 +347,10 @@ export function createSecretStore( } function secretStoreDisplay(): string { - return secretBackend() === 'macos' ? 'MacOS keychain' : credentialsFile(); + const backend = secretBackend(); + if (backend === 'macos') return 'MacOS keychain'; + if (backend === 'windows') return 'Windows Credential Manager'; + return credentialsFile(); } return { diff --git a/cli/src/lib/windows-credentials.test.ts b/cli/src/lib/windows-credentials.test.ts new file mode 100644 index 0000000..fbf3798 --- /dev/null +++ b/cli/src/lib/windows-credentials.test.ts @@ -0,0 +1,55 @@ +import { expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { credentialsFile, kvGet, kvSet } from '@/lib/config.ts'; +import { getProfileId } from '@/lib/profile-store.ts'; +import { createSecretStore } from '@/lib/secrets.ts'; + +test.skipIf(process.platform !== 'win32')( + 'Windows native credentials round-trip without a plaintext store', + () => { + const directory = mkdtempSync( + join(tmpdir(), 'altertable-native-credentials-') + ); + const oldHome = process.env.ALTERTABLE_CONFIG_HOME; + const oldBackend = process.env.ALTERTABLE_SECRET_BACKEND; + process.env.ALTERTABLE_CONFIG_HOME = directory; + delete process.env.ALTERTABLE_SECRET_BACKEND; + const store = createSecretStore(); + const secret = 'synthetic native credential: Zoë 🔑 \'$"\nsecond line'; + try { + store.secretSet('api-key', secret, 'native-test'); + expect(store.secretStoreDisplay()).toBe('Windows Credential Manager'); + expect(store.secretGet('api-key', 'native-test')).toBe(secret); + expect(store.secretExists('api-key', 'native-test')).toBe(true); + expect(existsSync(credentialsFile())).toBe(false); + store.secretDelete('api-key', 'native-test'); + expect(store.secretExists('api-key', 'native-test')).toBe(false); + + // Upgrade an existing stable-profile plaintext credential, then remove it. + const account = `profile/${getProfileId('native-test')}/api-key`; + kvSet(credentialsFile(), account, 'synthetic legacy credential'); + expect(store.secretGet('api-key', 'native-test')).toBe( + 'synthetic legacy credential' + ); + expect(kvGet(credentialsFile(), account)).toBe(''); + expect(store.secretGet('api-key', 'native-test')).toBe( + 'synthetic legacy credential' + ); + } finally { + try { + store.secretDelete('api-key', 'native-test'); + } finally { + if (oldHome === undefined) delete process.env.ALTERTABLE_CONFIG_HOME; + else process.env.ALTERTABLE_CONFIG_HOME = oldHome; + if (oldBackend === undefined) + delete process.env.ALTERTABLE_SECRET_BACKEND; + else process.env.ALTERTABLE_SECRET_BACKEND = oldBackend; + rmSync(directory, { recursive: true, force: true }); + } + } + }, + 120_000 +); diff --git a/cli/src/lib/windows-credentials.ts b/cli/src/lib/windows-credentials.ts new file mode 100644 index 0000000..1925bec --- /dev/null +++ b/cli/src/lib/windows-credentials.ts @@ -0,0 +1,153 @@ +import type { SpawnSyncOptions } from 'node:child_process'; + +import { CliError } from '@/lib/errors.ts'; + +type CredentialProcess = ( + command: string, + args: string[], + options: SpawnSyncOptions +) => { status: number | null; stdout: string | Buffer; error?: Error }; + +// Static code only: account names and secret values travel over stdin, never +// through PowerShell source, process arguments or a temporary script file. +const CREDENTIAL_SCRIPT = String.raw` +$ErrorActionPreference = 'Stop' +[Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false) +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) +try { + Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +public static class AltertableCredentialManager { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct Credential { + public uint Flags, Type; + public string TargetName, Comment; + public long LastWritten; + public uint CredentialBlobSize; + public IntPtr CredentialBlob; + public uint Persist, AttributeCount; + public IntPtr Attributes; + public string TargetAlias, UserName; + } + [DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool Write(ref Credential credential, uint flags); + [DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool Read(string target, uint type, uint flags, out IntPtr credential); + [DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool Delete(string target, uint type, uint flags); + [DllImport("advapi32.dll")] + private static extern void CredFree(IntPtr credential); + + private static bool Find(string account, out IntPtr pointer) { + if (Read("altertable/" + account, 1, 0, out pointer)) return true; + int error = Marshal.GetLastWin32Error(); + if (error == 1168) return false; + throw new Win32Exception(error); + } + public static string Get(string account) { + IntPtr pointer; + if (!Find(account, out pointer)) return null; + try { + Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential)); + return credential.CredentialBlobSize == 0 ? "" : Marshal.PtrToStringUni(credential.CredentialBlob, checked((int)credential.CredentialBlobSize / 2)); + } finally { CredFree(pointer); } + } + public static bool Exists(string account) { + IntPtr pointer; + if (!Find(account, out pointer)) return false; + CredFree(pointer); + return true; + } + public static void Set(string account, string value) { + IntPtr blob = Marshal.StringToCoTaskMemUni(value); + try { + Credential credential = new Credential(); + credential.Type = 1; + credential.TargetName = "altertable/" + account; + credential.UserName = "Altertable"; + credential.CredentialBlobSize = checked((uint)value.Length * 2); + credential.CredentialBlob = blob; + credential.Persist = 2; + if (!Write(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error()); + } finally { Marshal.ZeroFreeCoTaskMemUnicode(blob); } + } + public static void Remove(string account) { + if (Delete("altertable/" + account, 1, 0)) return; + int error = Marshal.GetLastWin32Error(); + if (error != 1168) throw new Win32Exception(error); + } +} +'@ + $request = [Console]::In.ReadToEnd() | ConvertFrom-Json + $result = @{} + switch ($request.action) { + 'get' { $result.value = [AltertableCredentialManager]::Get($request.account) } + 'exists' { $result.exists = [AltertableCredentialManager]::Exists($request.account) } + 'set' { [AltertableCredentialManager]::Set($request.account, $request.value) } + 'delete' { [AltertableCredentialManager]::Remove($request.account) } + default { throw 'Unknown credential operation' } + } + ConvertTo-Json -InputObject $result -Compress +} catch { + [Console]::Error.WriteLine('Windows Credential Manager operation failed.') + exit 1 +} +`; + +export function createWindowsCredentialStore(run: CredentialProcess) { + function invoke(action: string, account: string, value?: string) { + const result = run( + 'powershell.exe', + [ + '-NoLogo', + '-NoProfile', + '-NonInteractive', + '-Command', + CREDENTIAL_SCRIPT, + ], + { + input: JSON.stringify({ action, account, value }), + encoding: 'utf8', + windowsHide: true, + timeout: 15_000, + maxBuffer: 1024 * 1024, + } + ); + if (result.error || result.status !== 0) { + throw new CliError( + `Failed to ${action} secret in Windows Credential Manager.` + ); + } + try { + return JSON.parse(String(result.stdout)) as Record; + } catch { + throw new CliError('Invalid response from Windows Credential Manager.'); + } + } + + return { + get(account: string): string | null { + const result = invoke('get', account); + if (typeof result.value === 'string' || result.value === null) + return result.value; + throw new CliError( + 'Invalid secret response from Windows Credential Manager.' + ); + }, + exists(account: string): boolean { + const result = invoke('exists', account); + if (typeof result.exists === 'boolean') return result.exists; + throw new CliError( + 'Invalid lookup response from Windows Credential Manager.' + ); + }, + set(account: string, value: string): void { + invoke('set', account, value); + }, + delete(account: string): void { + invoke('delete', account); + }, + }; +} From 3b16d562ee9d29963b86a2307aa3b0e7d6f154c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 12:12:39 +0100 Subject: [PATCH 2/2] fix(config): batch Windows credential reads and explain vault failures - Read all Altertable credentials with one CredEnumerate call and reuse the snapshot until another CLI process writes, tracked by a revision marker, so per-request auth no longer starts PowerShell each time. - Store blobs as UTF-8 and reject secrets over the 2,560-byte vault limit before spawning. - Report PowerShell absence, timeouts, restricted language mode, missing logon-session vaults and Win32 error codes, each with the file-backend opt-out. - Skip deletes for absent credentials and no-op credentials-file rewrites. --- CHANGELOG.md | 2 +- DEVELOPMENT.md | 6 +- README.md | 24 +-- cli/src/lib/config-files.ts | 1 + cli/src/lib/secrets-windows.test.ts | 242 +++++++++++++++++++---- cli/src/lib/secrets.ts | 22 ++- cli/src/lib/windows-credentials.test.ts | 12 ++ cli/src/lib/windows-credentials.ts | 253 +++++++++++++++++++----- 8 files changed, 454 insertions(+), 108 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c17dc47..4499684 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Document the Windows PowerShell installation path, including Bun's native installer and the `bun.exe` requirement for npm launchers. -- Store Windows credentials in the current user's Credential Manager by default, migrate existing file credentials after successful native storage, and fail closed on vault errors. The explicit file backend remains available for CI. +- Store Windows credentials in the current user's Credential Manager by default, migrate existing file credentials after successful native storage, and fail closed on vault errors with the cause and how to opt out. `ALTERTABLE_SECRET_BACKEND=file` keeps the file backend, for example in CI. - Stop queries that run longer than 6 minutes from failing with `Request failed (network error): … (The operation timed out.)`. `--read-timeout` is now the only limit on query streams, and `0` means no limit. - Keep the TypeScript manifest compiler out of CLI downloads by installing it with the cached single-file preview runtime. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 556769b..a2d3d97 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -196,8 +196,10 @@ Keep updater tests hermetic. Use fake `fetch` implementations and temp executabl ## Credential storage - **Non-secret config**: `~/.config/altertable/config` -- **Secrets**: macOS Keychain when available, otherwise `~/.config/altertable/credentials` (`chmod 600`) -- Override backend: `ALTERTABLE_SECRET_BACKEND=keychain|file` +- **Secrets**: macOS Keychain when available, Windows Credential Manager on Windows, otherwise `~/.config/altertable/credentials` (`chmod 600`) +- Override backend: `ALTERTABLE_SECRET_BACKEND=keychain|windows|file` +- On Windows, each process lists the vault once and reuses that snapshot until another CLI process writes credentials; writes replace the random token in `credential-manager.revision` in the config directory +- The real Credential Manager test (`cli/src/lib/windows-credentials.test.ts`) only runs on Windows; CI runs it in the user-directories Windows job ## Local deployment endpoints diff --git a/README.md b/README.md index 486464d..c971c8a 100644 --- a/README.md +++ b/README.md @@ -263,18 +263,18 @@ Configuration is stored in `ALTERTABLE_CONFIG_HOME` when set, otherwise `$XDG_CONFIG_HOME/altertable`, otherwise `~/.config/altertable`. Directory settings must be absolute. The default home directory follows OS conventions (`HOME` on Unix, `USERPROFILE` on Windows). -Credentials use macOS Keychain when available and Windows Credential Manager on -Windows. Windows storage uses the current user's native credential vault through -Windows PowerShell; secret values are passed over stdin, not process arguments. -Existing Windows file credentials migrate to Credential Manager when read, and -are removed from the file only after native storage succeeds. Native-store errors -fail the command instead of silently saving plaintext. - -Other systems use a plaintext file with Unix mode `600`. You can explicitly opt -into the file backend with `ALTERTABLE_SECRET_BACKEND=file` (for example, in CI), -or require Windows Credential Manager with `ALTERTABLE_SECRET_BACKEND=windows`. -Keep the configuration directory private; Windows ACLs are not checked when the -file backend is explicitly selected. +Credentials use macOS Keychain when available and the current user's Windows +Credential Manager on Windows. Windows access goes through Windows PowerShell, with +secret values passed over stdin rather than process arguments. Existing Windows file +credentials move to Credential Manager when first read and leave the file only after +native storage succeeds. Credential Manager errors fail the command instead of +saving plaintext; each Windows secret can be at most 2,560 bytes. + +Other systems use a plaintext file with Unix mode `600`. Set +`ALTERTABLE_SECRET_BACKEND=file` to use the file everywhere (for example, in CI or +where PowerShell is restricted), or `ALTERTABLE_SECRET_BACKEND=windows` to require +Credential Manager. Keep the configuration directory private; Windows ACLs are not +checked when the file backend is selected. Named profiles store credentials and endpoint overrides per environment. Global display defaults (`query_layout`, `query_max_width`, `query_pager`) stay in the root config and apply to all profiles. diff --git a/cli/src/lib/config-files.ts b/cli/src/lib/config-files.ts index 9d5e55e..5fd3541 100644 --- a/cli/src/lib/config-files.ts +++ b/cli/src/lib/config-files.ts @@ -148,5 +148,6 @@ export function kvUnset(filePath: string, key: string): void { .split('\n') .filter(line => configKey(line) !== key) .join('\n'); + if (output === content) return; writeConfigFileAtomically(filePath, output, 'update'); } diff --git a/cli/src/lib/secrets-windows.test.ts b/cli/src/lib/secrets-windows.test.ts index e71d126..e94d0dd 100644 --- a/cli/src/lib/secrets-windows.test.ts +++ b/cli/src/lib/secrets-windows.test.ts @@ -4,9 +4,13 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { credentialsFile, kvGet, kvSet } from '@/lib/config.ts'; -import { getProfileId } from '@/lib/profile-store.ts'; +import { ensureProfileId, getProfileId } from '@/lib/profile-store.ts'; import { createSecretStore } from '@/lib/secrets.ts'; +const savedEnv = { + ALTERTABLE_CONFIG_HOME: process.env.ALTERTABLE_CONFIG_HOME, + ALTERTABLE_SECRET_BACKEND: process.env.ALTERTABLE_SECRET_BACKEND, +}; let directory = ''; beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'altertable-wincred-test-')); @@ -15,95 +19,257 @@ beforeEach(() => { }); afterEach(() => { rmSync(directory, { recursive: true, force: true }); - delete process.env.ALTERTABLE_CONFIG_HOME; - delete process.env.ALTERTABLE_SECRET_BACKEND; + for (const [name, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } }); -function fakeWindowsStore() { - const values = new Map(); - const calls: { args: string[]; input: string }[] = []; - const failures = new Set(); +type ProcessResult = { + status: number | null; + stdout: string; + stderr?: string; + error?: Error; +}; + +// Stands in for powershell.exe: it speaks the wrapper's stdin/stdout protocol +// over an in-memory vault. Pass another fake's values to model a second CLI +// process sharing the same vault. +function fakeWindowsVault(values = new Map()) { + const calls: { command: string; args: string[]; input: string }[] = []; + const failures = new Map(); const store = createSecretStore({ platform: 'win32', - spawnSync(_command, args, options) { + spawnSync(command, args, options) { if (typeof options.input !== 'string') throw new Error('Expected JSON stdin'); - const input = options.input; - calls.push({ args, input }); - const request = JSON.parse(input) as { + calls.push({ command, args, input: options.input }); + const request = JSON.parse(options.input) as { action: string; - account: string; + account?: string; value?: string; }; - if (failures.has(request.action)) return { status: 1, stdout: '' }; - if (request.action === 'set') values.set(request.account, request.value!); - if (request.action === 'delete') values.delete(request.account); - return { - status: 0, - stdout: JSON.stringify({ - value: values.get(request.account) ?? null, - exists: values.has(request.account), - }), - }; + const failure = failures.get(request.action); + if (failure) return failure; + if (request.action === 'list') { + return { + status: 0, + stdout: JSON.stringify({ credentials: Object.fromEntries(values) }), + }; + } + if (request.action === 'set') + values.set(request.account!, request.value!); + if (request.action === 'delete') values.delete(request.account!); + return { status: 0, stdout: '{}' }; }, }); return { store, values, calls, failures }; } +function actions(calls: { input: string }[]): string[] { + return calls.map( + call => (JSON.parse(call.input) as { action: string }).action + ); +} + +function stableAccount(key: string, profileName: string): string { + return `profile/${getProfileId(profileName)}/${key}`; +} + test('Windows defaults to Credential Manager without writing plaintext', () => { - const { store, values, calls } = fakeWindowsStore(); + const { store, values, calls } = fakeWindowsVault(); store.secretSet('api-key', 'atm_native_test', 'default', { fromArgv: true }); - const account = `profile/${getProfileId('default')}/api-key`; - expect(values.get(account)).toBe('atm_native_test'); + + expect(values.get(stableAccount('api-key', 'default'))).toBe( + 'atm_native_test' + ); expect(store.secretGet('api-key', 'default')).toBe('atm_native_test'); expect(store.secretExists('api-key', 'default')).toBe(true); expect(store.secretStoreDisplay()).toBe('Windows Credential Manager'); expect(existsSync(credentialsFile())).toBe(false); + expect(calls.every(call => call.command === 'powershell.exe')).toBe(true); expect(calls.some(call => call.input.includes('atm_native_test'))).toBe(true); expect( calls.every(call => !call.args.join(' ').includes('atm_native_test')) ).toBe(true); + + store.secretDelete('api-key', 'default'); + expect(store.secretExists('api-key', 'default')).toBe(false); +}); + +test('Windows serves a command’s secret lookups from one vault read', () => { + const vault = fakeWindowsVault(); + vault.values.set( + `profile/${ensureProfileId('default')}/api-key`, + 'atm_native_test' + ); + + // A management command looks up the OAuth token (current and pre-ID + // account names) before falling back to the API key. + expect(vault.store.secretGet('oauth/access-token', 'default')).toBe(''); + expect(vault.store.secretGet('api-key', 'default')).toBe('atm_native_test'); + expect(vault.store.secretExists('lakehouse/password', 'default')).toBe(false); + + expect(vault.calls.map(call => JSON.parse(call.input).action)).toEqual([ + 'list', + ]); +}); + +test('Windows reuses one vault read until another CLI process writes', () => { + const first = fakeWindowsVault(); + const second = fakeWindowsVault(first.values); + + first.store.secretSet('api-key', 'atm_one', 'default'); + expect(first.store.secretGet('api-key', 'default')).toBe('atm_one'); + first.store.secretSet('api-key', 'atm_two', 'default'); + expect(first.store.secretGet('api-key', 'default')).toBe('atm_two'); + expect(actions(first.calls)).toEqual(['set', 'list', 'set']); + + second.store.secretSet('api-key', 'atm_three', 'default'); + expect(first.store.secretGet('api-key', 'default')).toBe('atm_three'); + expect(first.store.secretGet('api-key', 'default')).toBe('atm_three'); + expect(actions(first.calls)).toEqual(['set', 'list', 'set', 'list']); +}); + +test('Windows deletes only secrets the vault holds', () => { + const { store, calls } = fakeWindowsVault(); + store.secretSet('api-key', 'atm_native_test', 'default'); + store.secretDelete('api-key', 'default'); + store.secretDelete('lakehouse/password', 'default'); + + // Each key is looked up under its stable and pre-ID account names. + expect(actions(calls)).toEqual(['set', 'list', 'delete']); expect(store.secretExists('api-key', 'default')).toBe(false); }); test('Windows migrates existing file secrets only after native storage succeeds', () => { - const { store, values, failures } = fakeWindowsStore(); + const { store, values, failures } = fakeWindowsVault(); kvSet(credentialsFile(), 'profile/default/api-key', 'atm_legacy_test'); - failures.add('set'); + failures.set('set', { status: 1, stdout: '' }); expect(() => store.secretGet('api-key', 'default')).toThrow( - 'Windows Credential Manager' + 'Windows Credential Manager could not store credentials.' ); expect(kvGet(credentialsFile(), 'profile/default/api-key')).toBe( 'atm_legacy_test' ); + failures.clear(); store.migrateProfileSecrets('default', ['api-key']); - const account = `profile/${getProfileId('default')}/api-key`; - expect(values.get(account)).toBe('atm_legacy_test'); + expect(values.get(stableAccount('api-key', 'default'))).toBe( + 'atm_legacy_test' + ); expect(values.has('profile/default/api-key')).toBe(false); expect(kvGet(credentialsFile(), 'profile/default/api-key')).toBe(''); }); test('Windows native failures never fall back to a plaintext write or stale file value', () => { - const { store, failures } = fakeWindowsStore(); - failures.add('set'); + const { store, values, failures } = fakeWindowsVault(); + failures.set('set', { status: 1, stdout: '' }); expect(() => store.secretSet('api-key', 'atm_do_not_write', 'default') ).toThrow('Windows Credential Manager'); expect(existsSync(credentialsFile())).toBe(false); + kvSet(credentialsFile(), 'profile/default/api-key', 'atm_stale'); - failures.add('get'); - failures.add('exists'); - failures.add('delete'); + failures.set('list', { status: 1, stdout: '' }); + failures.set('delete', { status: 1, stdout: '' }); expect(() => store.secretGet('api-key', 'default')).toThrow( - 'Windows Credential Manager' + 'Windows Credential Manager could not read credentials.' ); expect(() => store.secretExists('api-key', 'default')).toThrow( - 'Windows Credential Manager' + 'Windows Credential Manager could not read credentials.' ); expect(() => store.secretDelete('api-key', 'default')).toThrow( - 'Windows Credential Manager' + 'Windows Credential Manager could not read credentials.' + ); + + failures.delete('list'); + values.set('profile/default/api-key', 'atm_native'); + expect(() => store.secretDelete('api-key', 'default')).toThrow( + 'Windows Credential Manager could not delete credentials.' ); + expect(values.get('profile/default/api-key')).toBe('atm_native'); expect(kvGet(credentialsFile(), 'profile/default/api-key')).toBe('atm_stale'); }); + +test('Windows rejects secrets larger than Credential Manager stores', () => { + const { store, calls } = fakeWindowsVault(); + const oversized = 'x'.repeat(2561); + + expect(() => + store.secretSet('oauth/access-token', oversized, 'default') + ).toThrow( + 'This secret is 2561 bytes; Windows Credential Manager stores at most 2560.' + ); + expect(calls).toHaveLength(0); + expect(existsSync(credentialsFile())).toBe(false); + + store.secretSet('oauth/access-token', 'x'.repeat(2560), 'default'); + expect(store.secretGet('oauth/access-token', 'default')).toHaveLength(2560); +}); + +test.each([ + [ + { + status: null, + stdout: '', + error: Object.assign(new Error('spawn'), { code: 'ENOENT' }), + }, + 'requires Windows PowerShell (powershell.exe), which was not found.', + ], + [ + { + status: null, + stdout: '', + error: Object.assign(new Error('spawn'), { code: 'ETIMEDOUT' }), + }, + 'did not read credentials within 15 seconds.', + ], + [ + { status: 2, stdout: '' }, + 'PowerShell is restricted by a language mode policy', + ], + [ + { status: 3, stdout: '', stderr: '1312' }, + 'this logon session has no credential vault', + ], + [{ status: 3, stdout: '', stderr: '5' }, '(Windows error 5).'], +] satisfies [ProcessResult, string][])( + 'Windows explains native failures and how to opt out: %#', + (failure, reason) => { + const { store, failures } = fakeWindowsVault(); + failures.set('list', failure); + + let message = ''; + try { + store.secretGet('api-key', 'default'); + } catch (error) { + message = (error as Error).message; + } + expect(message).toContain(reason); + expect(message).toContain('Set ALTERTABLE_SECRET_BACKEND=file'); + } +); + +test('Windows backend can be required explicitly, and opted out of', () => { + process.env.ALTERTABLE_SECRET_BACKEND = 'windows'; + expect(fakeWindowsVault().store.secretStoreDisplay()).toBe( + 'Windows Credential Manager' + ); + const linux = createSecretStore({ + platform: 'linux', + spawnSync: () => ({ status: 1, stdout: '' }), + }); + expect(() => linux.secretStoreDisplay()).toThrow( + 'ALTERTABLE_SECRET_BACKEND=windows requires Windows Credential Manager.' + ); + + process.env.ALTERTABLE_SECRET_BACKEND = 'file'; + const { store, calls } = fakeWindowsVault(); + store.secretSet('api-key', 'atm_file_test', 'default'); + expect(kvGet(credentialsFile(), stableAccount('api-key', 'default'))).toBe( + 'atm_file_test' + ); + expect(calls).toHaveLength(0); +}); diff --git a/cli/src/lib/secrets.ts b/cli/src/lib/secrets.ts index 77bf724..cdd6949 100644 --- a/cli/src/lib/secrets.ts +++ b/cli/src/lib/secrets.ts @@ -1,8 +1,15 @@ import type { SpawnSyncOptions } from 'node:child_process'; import { spawnSync } from 'node:child_process'; import { chmodSync, statSync } from 'node:fs'; +import { join } from 'node:path'; -import { credentialsFile, kvGet, kvSet, kvUnset } from '@/lib/config.ts'; +import { + configDir, + credentialsFile, + kvGet, + kvSet, + kvUnset, +} from '@/lib/config.ts'; import { readEnv } from '@/lib/env.ts'; import { CliError } from '@/lib/errors.ts'; import { logWarn } from '@/lib/log.ts'; @@ -12,7 +19,10 @@ import { getProfileId, isFromEnvProfile, } from '@/lib/profile-store.ts'; -import { createWindowsCredentialStore } from '@/lib/windows-credentials.ts'; +import { + createWindowsCredentialStore, + fileCredentialRevision, +} from '@/lib/windows-credentials.ts'; type SecretBackend = 'macos' | 'windows' | 'file'; @@ -22,6 +32,7 @@ const KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44; type SecretProcessResult = { status: number | null; stdout: string | Buffer; + stderr?: string | Buffer; error?: Error; }; @@ -109,7 +120,10 @@ export function createSecretStore( ): SecretStore { let fileBackendWarned = false; const windowsCredentials = createWindowsCredentialStore( - secretProcess.spawnSync.bind(secretProcess) + secretProcess.spawnSync.bind(secretProcess), + fileCredentialRevision(() => + join(configDir(), 'credential-manager.revision') + ) ); function warnFileBackendOnce(): void { @@ -119,7 +133,7 @@ export function createSecretStore( ? 'Windows ACLs are not validated' : 'chmod 600'; logWarn( - `No macOS keychain; storing secrets at ${credentialsFile()} (${protection}). Prefer environment variables in CI.` + `Storing secrets in plaintext at ${credentialsFile()} (${protection}). Prefer environment variables in CI.` ); fileBackendWarned = true; } diff --git a/cli/src/lib/windows-credentials.test.ts b/cli/src/lib/windows-credentials.test.ts index fbf3798..e8b59b8 100644 --- a/cli/src/lib/windows-credentials.test.ts +++ b/cli/src/lib/windows-credentials.test.ts @@ -28,6 +28,17 @@ test.skipIf(process.platform !== 'win32')( store.secretDelete('api-key', 'native-test'); expect(store.secretExists('api-key', 'native-test')).toBe(false); + // Long tokens fit because blobs are UTF-8; a fresh store reads the vault. + const token = 'synthetic.token-'.repeat(150); + store.secretSet('oauth/access-token', token, 'native-test'); + expect( + createSecretStore().secretGet('oauth/access-token', 'native-test') + ).toBe(token); + store.secretDelete('oauth/access-token', 'native-test'); + expect( + createSecretStore().secretExists('oauth/access-token', 'native-test') + ).toBe(false); + // Upgrade an existing stable-profile plaintext credential, then remove it. const account = `profile/${getProfileId('native-test')}/api-key`; kvSet(credentialsFile(), account, 'synthetic legacy credential'); @@ -41,6 +52,7 @@ test.skipIf(process.platform !== 'win32')( } finally { try { store.secretDelete('api-key', 'native-test'); + store.secretDelete('oauth/access-token', 'native-test'); } finally { if (oldHome === undefined) delete process.env.ALTERTABLE_CONFIG_HOME; else process.env.ALTERTABLE_CONFIG_HOME = oldHome; diff --git a/cli/src/lib/windows-credentials.ts b/cli/src/lib/windows-credentials.ts index 1925bec..c17baf1 100644 --- a/cli/src/lib/windows-credentials.ts +++ b/cli/src/lib/windows-credentials.ts @@ -1,4 +1,7 @@ import type { SpawnSyncOptions } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; import { CliError } from '@/lib/errors.ts'; @@ -6,20 +9,75 @@ type CredentialProcess = ( command: string, args: string[], options: SpawnSyncOptions -) => { status: number | null; stdout: string | Buffer; error?: Error }; +) => { + status: number | null; + stdout: string | Buffer; + stderr?: string | Buffer; + error?: Error; +}; + +type CredentialAction = 'list' | 'set' | 'delete'; + +// A marker that changes whenever any CLI process writes the vault, so a +// snapshot can be reused until another process changes credentials. +export type CredentialRevision = { + read(): string; + advance(): string; +}; + +// The marker holds a random token, not a secret; a torn read only causes one +// more vault list. +export function fileCredentialRevision( + markerPath: () => string +): CredentialRevision { + return { + read() { + try { + return readFileSync(markerPath(), 'utf8'); + } catch { + return ''; + } + }, + advance() { + const token = randomUUID(); + mkdirSync(dirname(markerPath()), { recursive: true }); + writeFileSync(markerPath(), token); + return token; + }, + }; +} + +// CRED_MAX_CREDENTIAL_BLOB_SIZE: Credential Manager rejects larger secrets. +const MAX_SECRET_BYTES = 5 * 512; + +const EXIT_RESTRICTED_LANGUAGE = 2; +const EXIT_WIN32_ERROR = 3; +const ERROR_NO_SUCH_LOGON_SESSION = 1312; + +const FILE_BACKEND_HINT = + 'Set ALTERTABLE_SECRET_BACKEND=file to store credentials in the configuration directory instead.'; // Static code only: account names and secret values travel over stdin, never // through PowerShell source, process arguments or a temporary script file. +// Failures report only an exit code and a Win32 error number, because +// exception messages can echo the request that carries the secret. const CREDENTIAL_SCRIPT = String.raw` +if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { exit ${EXIT_RESTRICTED_LANGUAGE} } $ErrorActionPreference = 'Stop' [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false) [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) try { Add-Type -TypeDefinition @' using System; +using System.Collections; using System.ComponentModel; using System.Runtime.InteropServices; +using System.Text; public static class AltertableCredentialManager { + private const string Prefix = "altertable/"; + private const uint GenericType = 1; + private const uint PersistLocalMachine = 2; + private const int ErrorNotFound = 1168; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct Credential { public uint Flags, Type; @@ -33,71 +91,101 @@ public static class AltertableCredentialManager { } [DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool Write(ref Credential credential, uint flags); - [DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern bool Read(string target, uint type, uint flags, out IntPtr credential); + [DllImport("advapi32.dll", EntryPoint = "CredEnumerateW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool Enumerate(string filter, uint flags, out uint count, out IntPtr credentials); [DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool Delete(string target, uint type, uint flags); [DllImport("advapi32.dll")] - private static extern void CredFree(IntPtr credential); + private static extern void CredFree(IntPtr buffer); - private static bool Find(string account, out IntPtr pointer) { - if (Read("altertable/" + account, 1, 0, out pointer)) return true; - int error = Marshal.GetLastWin32Error(); - if (error == 1168) return false; - throw new Win32Exception(error); - } - public static string Get(string account) { - IntPtr pointer; - if (!Find(account, out pointer)) return null; + public static Hashtable List() { + Hashtable values = new Hashtable(); + uint count; + IntPtr list; + if (!Enumerate(Prefix + "*", 0, out count, out list)) { + int error = Marshal.GetLastWin32Error(); + if (error == ErrorNotFound) return values; + throw new Win32Exception(error); + } try { - Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential)); - return credential.CredentialBlobSize == 0 ? "" : Marshal.PtrToStringUni(credential.CredentialBlob, checked((int)credential.CredentialBlobSize / 2)); - } finally { CredFree(pointer); } - } - public static bool Exists(string account) { - IntPtr pointer; - if (!Find(account, out pointer)) return false; - CredFree(pointer); - return true; + for (int index = 0; index < count; index++) { + IntPtr pointer = Marshal.ReadIntPtr(list, index * IntPtr.Size); + Credential credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential)); + if (credential.Type != GenericType) continue; + byte[] blob = new byte[credential.CredentialBlobSize]; + if (blob.Length > 0) Marshal.Copy(credential.CredentialBlob, blob, 0, blob.Length); + values[credential.TargetName.Substring(Prefix.Length)] = Encoding.UTF8.GetString(blob); + Array.Clear(blob, 0, blob.Length); + } + } finally { CredFree(list); } + return values; } public static void Set(string account, string value) { - IntPtr blob = Marshal.StringToCoTaskMemUni(value); + byte[] bytes = Encoding.UTF8.GetBytes(value); + IntPtr blob = Marshal.AllocCoTaskMem(Math.Max(bytes.Length, 1)); try { + Marshal.Copy(bytes, 0, blob, bytes.Length); Credential credential = new Credential(); - credential.Type = 1; - credential.TargetName = "altertable/" + account; + credential.Type = GenericType; + credential.TargetName = Prefix + account; credential.UserName = "Altertable"; - credential.CredentialBlobSize = checked((uint)value.Length * 2); + credential.CredentialBlobSize = (uint)bytes.Length; credential.CredentialBlob = blob; - credential.Persist = 2; + credential.Persist = PersistLocalMachine; if (!Write(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error()); - } finally { Marshal.ZeroFreeCoTaskMemUnicode(blob); } + } finally { + Marshal.Copy(new byte[bytes.Length], 0, blob, bytes.Length); + Marshal.FreeCoTaskMem(blob); + Array.Clear(bytes, 0, bytes.Length); + } } public static void Remove(string account) { - if (Delete("altertable/" + account, 1, 0)) return; + if (Delete(Prefix + account, GenericType, 0)) return; int error = Marshal.GetLastWin32Error(); - if (error != 1168) throw new Win32Exception(error); + if (error != ErrorNotFound) throw new Win32Exception(error); } } '@ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json $result = @{} switch ($request.action) { - 'get' { $result.value = [AltertableCredentialManager]::Get($request.account) } - 'exists' { $result.exists = [AltertableCredentialManager]::Exists($request.account) } + 'list' { $result.credentials = [AltertableCredentialManager]::List() } 'set' { [AltertableCredentialManager]::Set($request.account, $request.value) } 'delete' { [AltertableCredentialManager]::Remove($request.account) } - default { throw 'Unknown credential operation' } + default { exit 1 } } ConvertTo-Json -InputObject $result -Compress } catch { - [Console]::Error.WriteLine('Windows Credential Manager operation failed.') + for ($exception = $_.Exception; $exception; $exception = $exception.InnerException) { + if ($exception -is [System.ComponentModel.Win32Exception]) { + [Console]::Error.Write($exception.NativeErrorCode) + exit ${EXIT_WIN32_ERROR} + } + } exit 1 } `; -export function createWindowsCredentialStore(run: CredentialProcess) { - function invoke(action: string, account: string, value?: string) { +const ACTION_VERBS: Record = { + list: 'read', + set: 'store', + delete: 'delete', +}; + +// Each PowerShell start compiles the native wrapper, which costs hundreds of +// milliseconds and blocks the event loop. Reads therefore share one snapshot +// of every Altertable credential, reused until the revision changes; auth is +// resolved per request, so long-running commands depend on this. +export function createWindowsCredentialStore( + run: CredentialProcess, + revision: CredentialRevision +) { + let snapshot: { values: Map; revision: string } | undefined; + + function invoke( + action: CredentialAction, + request: { account?: string; value?: string } = {} + ): Record { const result = run( 'powershell.exe', [ @@ -108,7 +196,7 @@ export function createWindowsCredentialStore(run: CredentialProcess) { CREDENTIAL_SCRIPT, ], { - input: JSON.stringify({ action, account, value }), + input: JSON.stringify({ action, ...request }), encoding: 'utf8', windowsHide: true, timeout: 15_000, @@ -117,7 +205,7 @@ export function createWindowsCredentialStore(run: CredentialProcess) { ); if (result.error || result.status !== 0) { throw new CliError( - `Failed to ${action} secret in Windows Credential Manager.` + `${failureReason(ACTION_VERBS[action], result)} ${FILE_BACKEND_HINT}` ); } try { @@ -127,27 +215,90 @@ export function createWindowsCredentialStore(run: CredentialProcess) { } } - return { - get(account: string): string | null { - const result = invoke('get', account); - if (typeof result.value === 'string' || result.value === null) - return result.value; + function storedValues(): Map { + // Read the revision before listing: a write racing the list only causes + // one more list later, never a stale snapshot. + const current = revision.read(); + if (snapshot?.revision === current) return snapshot.values; + const { credentials } = invoke('list'); + if (typeof credentials !== 'object' || credentials === null) { throw new CliError( - 'Invalid secret response from Windows Credential Manager.' + 'Invalid credential list from Windows Credential Manager.' ); + } + const values = new Map(); + for (const [account, value] of Object.entries(credentials)) { + if (typeof value === 'string') values.set(account, value); + } + snapshot = { values, revision: current }; + return values; + } + + function write( + action: 'set' | 'delete', + account: string, + value?: string + ): void { + invoke(action, { account, value }); + // Carry the snapshot forward only when no other process wrote since it + // was listed; otherwise the next read lists the vault again. + const current = + snapshot?.revision === revision.read() ? snapshot : undefined; + const next = revision.advance(); + if (!current) { + snapshot = undefined; + return; + } + if (value === undefined) current.values.delete(account); + else current.values.set(account, value); + snapshot = { values: current.values, revision: next }; + } + + return { + get(account: string): string | null { + return storedValues().get(account) ?? null; }, exists(account: string): boolean { - const result = invoke('exists', account); - if (typeof result.exists === 'boolean') return result.exists; - throw new CliError( - 'Invalid lookup response from Windows Credential Manager.' - ); + return storedValues().has(account); }, set(account: string, value: string): void { - invoke('set', account, value); + const size = Buffer.byteLength(value, 'utf8'); + if (size > MAX_SECRET_BYTES) { + throw new CliError( + `This secret is ${size} bytes; Windows Credential Manager stores at most ${MAX_SECRET_BYTES}. ${FILE_BACKEND_HINT}` + ); + } + write('set', account, value); }, delete(account: string): void { - invoke('delete', account); + if (storedValues().has(account)) write('delete', account); }, }; } + +function failureReason( + verb: string, + result: ReturnType +): string { + const code = (result.error as NodeJS.ErrnoException | undefined)?.code; + if (code === 'ENOENT') { + return 'Windows Credential Manager requires Windows PowerShell (powershell.exe), which was not found.'; + } + if (code === 'ETIMEDOUT') { + return `Windows Credential Manager did not ${verb} credentials within 15 seconds.`; + } + if (result.status === EXIT_RESTRICTED_LANGUAGE) { + return 'PowerShell is restricted by a language mode policy, which blocks Windows Credential Manager access.'; + } + const win32Error = + result.status === EXIT_WIN32_ERROR + ? Number.parseInt(String(result.stderr ?? ''), 10) + : Number.NaN; + if (win32Error === ERROR_NO_SUCH_LOGON_SESSION) { + return `Windows Credential Manager could not ${verb} credentials: this logon session has no credential vault (common over SSH and in services).`; + } + if (Number.isInteger(win32Error)) { + return `Windows Credential Manager could not ${verb} credentials (Windows error ${win32Error}).`; + } + return `Windows Credential Manager could not ${verb} credentials.`; +}