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 a92f107..4499684 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +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 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 0524f87..c971c8a 100644 --- a/README.md +++ b/README.md @@ -263,8 +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; the file fallback stores plaintext credentials. -Keep the configuration directory private. +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/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..e94d0dd --- /dev/null +++ b/cli/src/lib/secrets-windows.test.ts @@ -0,0 +1,275 @@ +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 { 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-')); + process.env.ALTERTABLE_CONFIG_HOME = directory; + delete process.env.ALTERTABLE_SECRET_BACKEND; +}); +afterEach(() => { + rmSync(directory, { recursive: true, force: true }); + for (const [name, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } +}); + +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) { + if (typeof options.input !== 'string') + throw new Error('Expected JSON stdin'); + calls.push({ command, args, input: options.input }); + const request = JSON.parse(options.input) as { + action: string; + account?: string; + value?: string; + }; + 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 } = fakeWindowsVault(); + store.secretSet('api-key', 'atm_native_test', 'default', { fromArgv: true }); + + 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 } = fakeWindowsVault(); + kvSet(credentialsFile(), 'profile/default/api-key', 'atm_legacy_test'); + failures.set('set', { status: 1, stdout: '' }); + expect(() => store.secretGet('api-key', 'default')).toThrow( + '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']); + 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, 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.set('list', { status: 1, stdout: '' }); + failures.set('delete', { status: 1, stdout: '' }); + expect(() => store.secretGet('api-key', 'default')).toThrow( + 'Windows Credential Manager could not read credentials.' + ); + expect(() => store.secretExists('api-key', 'default')).toThrow( + 'Windows Credential Manager could not read credentials.' + ); + expect(() => store.secretDelete('api-key', 'default')).toThrow( + '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 e8e7ef3..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,8 +19,12 @@ import { getProfileId, isFromEnvProfile, } from '@/lib/profile-store.ts'; +import { + createWindowsCredentialStore, + fileCredentialRevision, +} 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; @@ -21,6 +32,7 @@ const KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44; type SecretProcessResult = { status: number | null; stdout: string | Buffer; + stderr?: string | Buffer; error?: Error; }; @@ -107,6 +119,12 @@ export function createSecretStore( secretProcess: SecretProcess = SYSTEM_SECRET_PROCESS ): SecretStore { let fileBackendWarned = false; + const windowsCredentials = createWindowsCredentialStore( + secretProcess.spawnSync.bind(secretProcess), + fileCredentialRevision(() => + join(configDir(), 'credential-manager.revision') + ) + ); function warnFileBackendOnce(): void { if (fileBackendWarned) return; @@ -115,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; } @@ -130,6 +148,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 +163,7 @@ export function createSecretStore( } if (secretProcess.platform === 'darwin' && hasSecurityCommand()) return 'macos'; + if (secretProcess.platform === 'win32') return 'windows'; return 'file'; } @@ -165,6 +190,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 +227,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 +249,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 +285,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 +347,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 +361,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..e8b59b8 --- /dev/null +++ b/cli/src/lib/windows-credentials.test.ts @@ -0,0 +1,67 @@ +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); + + // 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'); + 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'); + store.secretDelete('oauth/access-token', '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..c17baf1 --- /dev/null +++ b/cli/src/lib/windows-credentials.ts @@ -0,0 +1,304 @@ +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'; + +type CredentialProcess = ( + command: string, + args: string[], + options: SpawnSyncOptions +) => { + 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; + 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 = "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 buffer); + + 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 { + 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) { + 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 = GenericType; + credential.TargetName = Prefix + account; + credential.UserName = "Altertable"; + credential.CredentialBlobSize = (uint)bytes.Length; + credential.CredentialBlob = blob; + credential.Persist = PersistLocalMachine; + if (!Write(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error()); + } 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(Prefix + account, GenericType, 0)) return; + int error = Marshal.GetLastWin32Error(); + if (error != ErrorNotFound) throw new Win32Exception(error); + } +} +'@ + $request = [Console]::In.ReadToEnd() | ConvertFrom-Json + $result = @{} + switch ($request.action) { + 'list' { $result.credentials = [AltertableCredentialManager]::List() } + 'set' { [AltertableCredentialManager]::Set($request.account, $request.value) } + 'delete' { [AltertableCredentialManager]::Remove($request.account) } + default { exit 1 } + } + ConvertTo-Json -InputObject $result -Compress +} catch { + for ($exception = $_.Exception; $exception; $exception = $exception.InnerException) { + if ($exception -is [System.ComponentModel.Win32Exception]) { + [Console]::Error.Write($exception.NativeErrorCode) + exit ${EXIT_WIN32_ERROR} + } + } + exit 1 +} +`; + +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', + [ + '-NoLogo', + '-NoProfile', + '-NonInteractive', + '-Command', + CREDENTIAL_SCRIPT, + ], + { + input: JSON.stringify({ action, ...request }), + encoding: 'utf8', + windowsHide: true, + timeout: 15_000, + maxBuffer: 1024 * 1024, + } + ); + if (result.error || result.status !== 0) { + throw new CliError( + `${failureReason(ACTION_VERBS[action], result)} ${FILE_BACKEND_HINT}` + ); + } + try { + return JSON.parse(String(result.stdout)) as Record; + } catch { + throw new CliError('Invalid response from Windows Credential Manager.'); + } + } + + 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 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 { + return storedValues().has(account); + }, + set(account: string, value: string): void { + 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 { + 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.`; +}