diff --git a/.github/workflows/desktop-e2e.yml b/.github/workflows/desktop-e2e.yml index 07c1e74b1ce..8db0fe3de33 100644 --- a/.github/workflows/desktop-e2e.yml +++ b/.github/workflows/desktop-e2e.yml @@ -308,6 +308,15 @@ jobs: bunx electron-builder --mac dir --universal --publish never \ -c.mac.identity=- -c.mac.hardenedRuntime=false + # Reads an item from a throwaway keychain it puts on the search list, so it + # stays in CI. A Keychain prompt would block headlessly; the timeout fails it fast. + - name: Read a throwaway Keychain item through the native addon + working-directory: apps/desktop + timeout-minutes: 3 + env: + SIM_KEYCHAIN_ITEM_TEST: '1' + run: bunx vitest run src/main/browser-import/keychain-native.test.ts + - name: Run packaged Electron smoke suite working-directory: apps/desktop run: | diff --git a/apps/desktop/e2e/packaged-smoke.spec.ts b/apps/desktop/e2e/packaged-smoke.spec.ts index c2be201f8d7..54bc5337b91 100644 --- a/apps/desktop/e2e/packaged-smoke.spec.ts +++ b/apps/desktop/e2e/packaged-smoke.spec.ts @@ -1,7 +1,7 @@ import { spawn } from 'node:child_process' import { existsSync, mkdtempSync, readFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { FuseV1Options, FuseVersion, getCurrentFuseWire } from '@electron/fuses' import { type Browser, chromium } from '@playwright/test' import { expect, stopAndRemoveProfile, test } from './harness' @@ -43,6 +43,17 @@ test('packaged Electron binary has the production fuse policy', async () => { } }) +// Native addons cannot be dlopen'd from inside app.asar; one left packed fails +// only when the feature that loads it runs (the Keychain one, during an import). +test('packaged app ships every native addon outside the asar', () => { + const executablePath = process.env.SIM_DESKTOP_EXECUTABLE + if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') + const unpacked = join(dirname(executablePath), '..', 'Resources', 'app.asar.unpacked') + for (const addon of ['directory', 'help-search', 'keychain']) { + expect(existsSync(join(unpacked, 'dist', 'native', `${addon}.node`)), addon).toBe(true) + } +}) + // The unpackaged suite cannot see this: the bundled pages live inside app.asar // only once packaged, and the file-protocol fuse is only off once packaged. // v0.8.13 through v0.8.19 shipped both pages blank because nothing loaded them diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml index 245663c584f..e791f19e9bc 100644 --- a/apps/desktop/electron-builder.yml +++ b/apps/desktop/electron-builder.yml @@ -22,8 +22,8 @@ extraResources: asar: true -# Native modules cannot be dlopen'd from inside an asar. The Help-search addon -# is already universal; `scripts/ensure-pty-prebuilds.ts` guarantees both pty +# Native modules cannot be dlopen'd from inside an asar. The native addons are +# already universal; `scripts/ensure-pty-prebuilds.ts` guarantees both pty # prebuilds are present before packaging. asarUnpack: - "**/node_modules/@lydell/node-pty-*/prebuilds/**" diff --git a/apps/desktop/native/keychain.mm b/apps/desktop/native/keychain.mm new file mode 100644 index 00000000000..9db8ba4b083 --- /dev/null +++ b/apps/desktop/native/keychain.mm @@ -0,0 +1,210 @@ +// memset_s is the C11 Annex K wipe the optimizer may not elide; string.h only declares it on request. +#define __STDC_WANT_LIB_EXT1__ 1 + +#import +#import + +#include + +#include + +#include +#include +#include + +/** + * Reads a generic-password Keychain item inside the Sim process, so the + * Keychain prompt names Sim and "Always Allow" trusts Sim rather than a shared + * system tool that any other process could run. Nothing here caches a secret: + * each read copies the password into JS and wipes the buffer it owns. + */ + +enum class ReadStatus { kFound, kMissing, kDenied, kFailed }; + +struct ReadRequest { + std::string service; + std::string account; + std::vector password; + ReadStatus status = ReadStatus::kFailed; + OSStatus os_status = errSecSuccess; + napi_deferred deferred = nullptr; + napi_async_work work = nullptr; +}; + +static void Wipe(std::vector* buffer) { + if (!buffer->empty()) { + memset_s(buffer->data(), buffer->size(), 0, buffer->size()); + } + buffer->clear(); +} + +static NSString* StringFromUTF8(const std::string& value) { + return [[NSString alloc] initWithBytes:value.data() + length:value.size() + encoding:NSUTF8StringEncoding]; +} + +static ReadStatus StatusFor(OSStatus status) { + switch (status) { + case errSecItemNotFound: + return ReadStatus::kMissing; + case errSecUserCanceled: + case errSecAuthFailed: + case errSecInteractionNotAllowed: + return ReadStatus::kDenied; + default: + return ReadStatus::kFailed; + } +} + +/** Runs off the JS thread: the call blocks for as long as the user sits on the Keychain prompt. */ +static void ExecuteRead(napi_env env, void* data) { + (void)env; + ReadRequest* request = static_cast(data); + @autoreleasepool { + NSString* service = StringFromUTF8(request->service); + NSString* account = StringFromUTF8(request->account); + if (!service || !account) { + request->status = ReadStatus::kFailed; + request->os_status = errSecParam; + return; + } + NSDictionary* query = @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrService : service, + (__bridge id)kSecAttrAccount : account, + (__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitOne, + (__bridge id)kSecReturnData : @YES, + }; + CFTypeRef result = nullptr; + OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); + request->os_status = status; + if (status == errSecSuccess) { + if (result && CFGetTypeID(result) == CFDataGetTypeID()) { + CFDataRef password = static_cast(result); + CFIndex length = CFDataGetLength(password); + if (length > 0) { + request->password.resize(static_cast(length)); + CFDataGetBytes(password, CFRangeMake(0, length), + reinterpret_cast(request->password.data())); + } + request->status = ReadStatus::kFound; + } else { + request->status = ReadStatus::kFailed; + } + } else { + request->status = StatusFor(status); + } + if (result) { + CFRelease(result); + } + } +} + +static const char* StatusName(ReadStatus status) { + switch (status) { + case ReadStatus::kFound: + return "found"; + case ReadStatus::kMissing: + return "missing"; + case ReadStatus::kDenied: + return "denied"; + case ReadStatus::kFailed: + return "failed"; + } + return "failed"; +} + +static void SetString(napi_env env, napi_value object, const char* name, const char* value, + size_t length) { + napi_value string; + napi_create_string_utf8(env, value, length, &string); + napi_set_named_property(env, object, name, string); +} + +static void CompleteRead(napi_env env, napi_status status, void* data) { + ReadRequest* request = static_cast(data); + if (status == napi_ok) { + napi_value result; + napi_create_object(env, &result); + SetString(env, result, "status", StatusName(request->status), NAPI_AUTO_LENGTH); + if (request->status == ReadStatus::kFound) { + SetString(env, result, "password", request->password.data(), request->password.size()); + } else { + napi_value code; + napi_create_int32(env, request->os_status, &code); + napi_set_named_property(env, result, "code", code); + } + napi_resolve_deferred(env, request->deferred, result); + } else { + napi_value message; + napi_value error; + napi_create_string_utf8(env, "Keychain read was cancelled", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &error); + napi_reject_deferred(env, request->deferred, error); + } + Wipe(&request->password); + napi_delete_async_work(env, request->work); + delete request; +} + +static bool ReadString(napi_env env, napi_value value, const char* name, std::string* output) { + napi_valuetype type; + size_t length = 0; + if (napi_typeof(env, value, &type) != napi_ok || type != napi_string || + napi_get_value_string_utf8(env, value, nullptr, 0, &length) != napi_ok) { + std::string message = std::string(name) + " must be a string"; + napi_throw_type_error(env, nullptr, message.c_str()); + return false; + } + std::vector buffer(length + 1); + if (napi_get_value_string_utf8(env, value, buffer.data(), buffer.size(), &length) != napi_ok) { + std::string message = std::string("could not read ") + name; + napi_throw_type_error(env, nullptr, message.c_str()); + return false; + } + output->assign(buffer.data(), length); + return true; +} + +/** `readGenericPassword(service, account)` resolves `{ status, password?, code? }`. */ +static napi_value ReadGenericPassword(napi_env env, napi_callback_info info) { + size_t argument_count = 2; + napi_value arguments[2]; + if (napi_get_cb_info(env, info, &argument_count, arguments, nullptr, nullptr) != napi_ok || + argument_count != 2) { + napi_throw_type_error(env, nullptr, "readGenericPassword expects a service and an account"); + return nullptr; + } + ReadRequest* request = new ReadRequest(); + if (!ReadString(env, arguments[0], "service", &request->service) || + !ReadString(env, arguments[1], "account", &request->account)) { + delete request; + return nullptr; + } + napi_value promise; + napi_value resource_name; + if (napi_create_promise(env, &request->deferred, &promise) != napi_ok || + napi_create_string_utf8(env, "SimKeychainRead", NAPI_AUTO_LENGTH, &resource_name) != + napi_ok || + napi_create_async_work(env, nullptr, resource_name, ExecuteRead, CompleteRead, request, + &request->work) != napi_ok || + napi_queue_async_work(env, request->work) != napi_ok) { + if (request->work) { + napi_delete_async_work(env, request->work); + } + delete request; + napi_throw_error(env, nullptr, "could not start the Keychain read"); + return nullptr; + } + return promise; +} + +NAPI_MODULE_INIT() { + napi_property_descriptor properties[] = { + {"readGenericPassword", nullptr, ReadGenericPassword, nullptr, nullptr, nullptr, + napi_default, nullptr}, + }; + napi_define_properties(env, exports, std::size(properties), properties); + return exports; +} diff --git a/apps/desktop/scripts/build-native.ts b/apps/desktop/scripts/build-native.ts index eb0d3f1e99d..e016d19ac44 100644 --- a/apps/desktop/scripts/build-native.ts +++ b/apps/desktop/scripts/build-native.ts @@ -19,10 +19,17 @@ if (process.platform !== 'darwin' && process.platform !== 'linux') { const includeDirectory = nodeIncludeDirectory() const outputDirectory = 'dist/native' mkdirSync(outputDirectory, { recursive: true }) -const modules = [ - { name: 'directory', source: 'native/directory.cc', appKit: false }, +const modules: { name: string; source: string; frameworks: string[] }[] = [ + { name: 'directory', source: 'native/directory.cc', frameworks: [] }, ...(process.platform === 'darwin' - ? [{ name: 'help-search', source: 'native/help-search.mm', appKit: true }] + ? [ + { + name: 'help-search', + source: 'native/help-search.mm', + frameworks: ['AppKit', 'Foundation'], + }, + { name: 'keychain', source: 'native/keychain.mm', frameworks: ['Security', 'Foundation'] }, + ] : []), ] for (const module of modules) { @@ -61,8 +68,12 @@ for (const module of modules) { : ['-shared', '-fPIC']), '-I', includeDirectory, - ...(module.appKit - ? ['-fobjc-arc', '-fblocks', '-framework', 'AppKit', '-framework', 'Foundation'] + ...(module.frameworks.length > 0 + ? [ + '-fobjc-arc', + '-fblocks', + ...module.frameworks.flatMap((framework) => ['-framework', framework]), + ] : []), '-o', output, diff --git a/apps/desktop/scripts/native-build-cache.ts b/apps/desktop/scripts/native-build-cache.ts index d42ed8db280..f9323592029 100644 --- a/apps/desktop/scripts/native-build-cache.ts +++ b/apps/desktop/scripts/native-build-cache.ts @@ -13,6 +13,7 @@ interface NativeOutput { const SOURCES = [ 'native/directory.cc', 'native/help-search.mm', + 'native/keychain.mm', 'native/computer-use/ComputerUse.swift', 'native/computer-use/Info.plist', 'scripts/build.ts', diff --git a/apps/desktop/src/main/browser-import/chromium-crypto.test.ts b/apps/desktop/src/main/browser-import/chromium-crypto.test.ts index b2e5104e03d..7e095572093 100644 --- a/apps/desktop/src/main/browser-import/chromium-crypto.test.ts +++ b/apps/desktop/src/main/browser-import/chromium-crypto.test.ts @@ -1,5 +1,5 @@ import { createCipheriv, createHash } from 'node:crypto' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, type Mock, vi } from 'vitest' import { decryptChromiumValue, deriveEncryptionKey, @@ -56,33 +56,116 @@ describe('decryptChromiumValue', () => { }) }) +type SecurityToolRead = (service: string, account: string) => Promise + describe('readSafeStoragePassword', () => { const ARC_ITEM = { service: 'Arc Safe Storage', account: 'Arc' } - it('reads the item belonging to the browser being imported', async () => { + function nativeRuntime(read: Mock) { + const readWithSecurityTool = vi.fn().mockResolvedValue('security-password') + return { + runtime: { loadNative: () => ({ readGenericPassword: read }), readWithSecurityTool }, + readWithSecurityTool, + } + } + + function securityToolRuntime(readWithSecurityTool: Mock) { + return { + loadNative: () => { + throw new Error("Cannot find module 'keychain.node'") + }, + readWithSecurityTool, + } + } + + it('reads the browser’s own item in-process instead of through the security tool', async () => { // Each browser names its own item. Asking for the wrong one would prompt // the user about a browser they did not choose. - const read = vi.fn().mockResolvedValue('arc-password') + const read = vi.fn().mockResolvedValue({ status: 'found', password: 'arc-password' }) + const { runtime, readWithSecurityTool } = nativeRuntime(read) - await expect(readSafeStoragePassword(ARC_ITEM, read)).resolves.toBe('arc-password') + await expect(readSafeStoragePassword(ARC_ITEM, runtime)).resolves.toBe('arc-password') expect(read).toHaveBeenCalledExactlyOnceWith('Arc Safe Storage', 'Arc') + expect(readWithSecurityTool).not.toHaveBeenCalled() }) - it('fails closed when access is denied', async () => { - const read = vi.fn().mockRejectedValue(new Error('User denied access')) - await expect(readSafeStoragePassword(ARC_ITEM, read)).resolves.toBeNull() - }) + it.each([ + { status: 'denied', code: -128 }, + { status: 'failed', code: -67671 }, + ])( + 'fails closed on a $status read without prompting again through the security tool', + async (result) => { + const { runtime, readWithSecurityTool } = nativeRuntime(vi.fn().mockResolvedValue(result)) + + await expect(readSafeStoragePassword(ARC_ITEM, runtime)).resolves.toBeNull() + expect(readWithSecurityTool).not.toHaveBeenCalled() + } + ) it('tells a missing item apart from a refused prompt, so the user is not sent to retry', async () => { - // `security` exits with the low byte of errSecItemNotFound (-25300). - const read = vi.fn().mockRejectedValue(Object.assign(new Error('not found'), { code: 44 })) - await expect(readSafeStoragePassword(ARC_ITEM, read)).rejects.toMatchObject({ + const { runtime } = nativeRuntime( + vi.fn().mockResolvedValue({ status: 'missing', code: -25300 }) + ) + await expect(readSafeStoragePassword(ARC_ITEM, runtime)).rejects.toMatchObject({ code: 'keychain-item-missing', }) }) + it('fails closed when the native read itself throws', async () => { + const { runtime, readWithSecurityTool } = nativeRuntime( + vi.fn().mockRejectedValue(new Error('cancelled')) + ) + await expect(readSafeStoragePassword(ARC_ITEM, runtime)).resolves.toBeNull() + expect(readWithSecurityTool).not.toHaveBeenCalled() + }) + + it('fails closed instead of hanging when the native read never settles', async () => { + vi.useFakeTimers() + try { + const { runtime, readWithSecurityTool } = nativeRuntime( + vi.fn().mockReturnValue(new Promise(() => {})) + ) + const password = readSafeStoragePassword(ARC_ITEM, runtime) + await vi.advanceTimersByTimeAsync(120_000) + await expect(password).resolves.toBeNull() + expect(readWithSecurityTool).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + it('treats an empty password as unavailable', async () => { - const read = vi.fn().mockResolvedValue(' ') - await expect(readSafeStoragePassword(ARC_ITEM, read)).resolves.toBeNull() + const { runtime } = nativeRuntime( + vi.fn().mockResolvedValue({ status: 'found', password: ' ' }) + ) + await expect(readSafeStoragePassword(ARC_ITEM, runtime)).resolves.toBeNull() + }) + + it('falls back to the security tool only when the native addon cannot load', async () => { + const readWithSecurityTool = vi.fn().mockResolvedValue('arc-password\n') + await expect( + readSafeStoragePassword(ARC_ITEM, securityToolRuntime(readWithSecurityTool)) + ).resolves.toBe('arc-password') + expect(readWithSecurityTool).toHaveBeenCalledExactlyOnceWith('Arc Safe Storage', 'Arc') + }) + + it('falls back when the addon loads without the expected interface', async () => { + const readWithSecurityTool = vi.fn().mockResolvedValue('arc-password') + await expect( + readSafeStoragePassword(ARC_ITEM, { loadNative: () => ({}), readWithSecurityTool }) + ).resolves.toBe('arc-password') + }) + + it('keeps the security tool’s missing-item and denial meanings on the fallback path', async () => { + // `security` exits with the low byte of errSecItemNotFound (-25300). + const missing = vi + .fn() + .mockRejectedValue(Object.assign(new Error('not found'), { code: 44 })) + await expect( + readSafeStoragePassword(ARC_ITEM, securityToolRuntime(missing)) + ).rejects.toMatchObject({ code: 'keychain-item-missing' }) + + const denied = vi.fn().mockRejectedValue(new Error('User denied access')) + await expect(readSafeStoragePassword(ARC_ITEM, securityToolRuntime(denied))).resolves.toBeNull() }) }) diff --git a/apps/desktop/src/main/browser-import/chromium-crypto.ts b/apps/desktop/src/main/browser-import/chromium-crypto.ts index 4d2a736df11..adc12ae68c9 100644 --- a/apps/desktop/src/main/browser-import/chromium-crypto.ts +++ b/apps/desktop/src/main/browser-import/chromium-crypto.ts @@ -1,6 +1,9 @@ import { execFile } from 'node:child_process' import { createDecipheriv, createHash, pbkdf2Sync } from 'node:crypto' +import { join } from 'node:path' import { promisify } from 'node:util' +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' import { ImportFailure } from '@/main/browser-import/types' @@ -8,16 +11,19 @@ import { ImportFailure } from '@/main/browser-import/types' * Chrome's macOS value encryption (Chromium's `OSCrypt`, scheme `v10`). * * The key is derived from a random password Chrome stores in the login - * Keychain. Reading it goes through the documented `security` tool, so macOS - * applies its own Keychain ACL — the user gets the standard "allow access" - * prompt for a binary that is not on the item's ACL, and a denial is a hard - * failure here. Nothing in this module weakens or works around that check. + * Keychain. Sim reads it in-process through the native `keychain` addon, so + * macOS applies its own Keychain ACL to Sim itself: the user gets the standard + * "allow access" prompt naming Sim, and "Always Allow" trusts only Sim. A + * denial is a hard failure here. Nothing in this module weakens or works + * around that check. * * On Windows this scheme does not apply: Chrome's App-Bound Encryption is * designed to stop other applications decrypting profile data, and the * importer deliberately does not attempt it. */ +const logger = createLogger('DesktopBrowserImportKeychain') + const execFileAsync = promisify(execFile) /** Fixed Chromium `OSCrypt` parameters for macOS. */ @@ -33,23 +39,79 @@ const DOMAIN_HASH_LENGTH = 32 /** * The user could sit on the Keychain prompt for a while, so this is a - * safety net against a wedged child process, not a UI deadline. + * safety net against a wedged read, not a UI deadline. */ const KEYCHAIN_TIMEOUT_MS = 120_000 -export type KeychainPasswordReader = (service: string, account: string) => Promise +/** `security` exits with the low byte of `errSecItemNotFound` (-25300). */ +const SECURITY_ITEM_NOT_FOUND_EXIT_CODE = 44 + +type NativeKeychainRead = + | { status: 'found'; password: string } + | { status: 'missing' | 'denied' | 'failed'; code: number } -const readKeychainItem: KeychainPasswordReader = async (service, account) => { - const { stdout } = await execFileAsync( - '/usr/bin/security', - ['find-generic-password', '-w', '-s', service, '-a', account], - { timeout: KEYCHAIN_TIMEOUT_MS, maxBuffer: 64 * 1024 } - ) - return stdout.trim() +interface NativeKeychainBridge { + readGenericPassword: (service: string, account: string) => Promise } -/** `security` exits with the low byte of `errSecItemNotFound` (-25300). */ -const SECURITY_ITEM_NOT_FOUND_EXIT_CODE = 44 +interface KeychainRuntime { + /** Loads the in-process Keychain addon; throws when it is not built. */ + loadNative: () => unknown + /** Development fallback: resolves `security -w` stdout, rejects with its exit code. */ + readWithSecurityTool: (service: string, account: string) => Promise +} + +const nativeRuntime: KeychainRuntime = { + loadNative: () => require(join(__dirname, 'native', 'keychain.node')), + readWithSecurityTool: async (service, account) => { + const { stdout } = await execFileAsync( + '/usr/bin/security', + ['find-generic-password', '-w', '-s', service, '-a', account], + { timeout: KEYCHAIN_TIMEOUT_MS, maxBuffer: 64 * 1024 } + ) + return stdout + }, +} + +function isNativeKeychainBridge(value: unknown): value is NativeKeychainBridge { + return isRecordLike(value) && typeof value.readGenericPassword === 'function' +} + +function loadNativeKeychain(runtime: KeychainRuntime): NativeKeychainBridge | null { + try { + const bridge = runtime.loadNative() + if (isNativeKeychainBridge(bridge)) return bridge + logger.warn('Native Keychain addon has an invalid interface') + } catch (error) { + logger.warn('Native Keychain addon is unavailable', { error: getErrorMessage(error) }) + } + return null +} + +/** + * Rejects once the read outlives `KEYCHAIN_TIMEOUT_MS`. The native read cannot + * be cancelled, so a late result is dropped unread. + */ +async function withDeadline(read: Promise): Promise { + let timer: ReturnType | undefined + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Keychain read timed out')), KEYCHAIN_TIMEOUT_MS) + }) + try { + return await Promise.race([read, deadline]) + } finally { + clearTimeout(timer) + } +} + +function itemMissing(): ImportFailure { + return new ImportFailure('keychain-item-missing', 'The Safe Storage item does not exist.') +} + +function usablePassword(password: string): string | null { + const trimmed = password.trim() + return trimmed.length > 0 ? trimmed : null +} /** * The Safe Storage password for one browser's Keychain item, or null when the @@ -60,19 +122,36 @@ const SECURITY_ITEM_NOT_FOUND_EXIT_CODE = 44 * and so on), so the item is passed in rather than guessed at: asking for the * wrong one would prompt the user about a browser they did not choose. * + * The `security` tool is only a fallback for when the native addon cannot + * load (development without a native build). A denial from the addon never + * falls back: that would prompt again, for a binary every process can run. + * * The return value is a secret. It must never be logged, persisted, or sent * anywhere. Callers should derive a key and drop the reference immediately. */ export async function readSafeStoragePassword( item: { service: string; account: string }, - read: KeychainPasswordReader = readKeychainItem + runtime: KeychainRuntime = nativeRuntime ): Promise { + const bridge = loadNativeKeychain(runtime) + if (bridge) { + let read: NativeKeychainRead + try { + read = await withDeadline(bridge.readGenericPassword(item.service, item.account)) + } catch (error) { + logger.warn('Native Keychain read failed', { error: getErrorMessage(error) }) + return null + } + if (read.status === 'found') return usablePassword(read.password) + if (read.status === 'missing') throw itemMissing() + if (read.status === 'failed') logger.warn('Keychain read failed', { status: read.code }) + return null + } try { - const password = (await read(item.service, item.account)).trim() - return password.length > 0 ? password : null + return usablePassword(await runtime.readWithSecurityTool(item.service, item.account)) } catch (error) { if (isRecordLike(error) && error.code === SECURITY_ITEM_NOT_FOUND_EXIT_CODE) { - throw new ImportFailure('keychain-item-missing', 'The Safe Storage item does not exist.') + throw itemMissing() } // Access denied, or the read failed. Fail closed. return null diff --git a/apps/desktop/src/main/browser-import/keychain-native.test.ts b/apps/desktop/src/main/browser-import/keychain-native.test.ts new file mode 100644 index 00000000000..de767572b4b --- /dev/null +++ b/apps/desktop/src/main/browser-import/keychain-native.test.ts @@ -0,0 +1,111 @@ +import { execFileSync, spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { generateId } from '@sim/utils/id' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +/** + * Exercises the real `keychain.node` addon against the real Keychain. Every + * item it touches has a fresh random name, so no browser's Safe Storage item + * is ever read. + */ + +interface KeychainAddon { + readGenericPassword: (service: string, account: string) => Promise> +} + +const ADDON_PATH = resolve(__dirname, '../../../dist/native/keychain.node') +const ERR_SEC_ITEM_NOT_FOUND = -25300 + +const loadAddon = () => createRequire(__filename)(ADDON_PATH) as KeychainAddon + +describe.skipIf(process.platform !== 'darwin')('keychain addon', () => { + /** + * Puts a throwaway keychain on the user search list, so this runs only where + * it is asked for: the macOS CI job that packages the app. Items `security` + * creates carry its partition list, so the test runner's own code-signing + * partition is added; without it macOS prompts even for an `-A` item. It + * runs first: Security caches the search list on a process's first lookup. + */ + describe.skipIf(process.env.SIM_KEYCHAIN_ITEM_TEST !== '1')('with a throwaway item', () => { + const service = `Sim Test ${generateId()}` + const account = `sim-test-${generateId()}` + const password = `pässwörd-${generateId()}` + const keychainPassword = generateId() + let directory = '' + let keychain = '' + let searchList: string[] = [] + + const security = (...args: string[]) => + execFileSync('/usr/bin/security', args, { encoding: 'utf8', timeout: 30_000 }) + + function runnerPartition(): string { + const signature = spawnSync('/usr/bin/codesign', ['-dv', '--verbose=2', process.execPath], { + encoding: 'utf8', + }).stderr + const team = /^TeamIdentifier=(.+)$/m.exec(signature)?.[1] + if (team && team !== 'not set') return `teamid:${team}` + const cdhash = /^CDHash=(.+)$/m.exec(signature)?.[1] + if (!cdhash) throw new Error('Could not read the test runner code signature') + return `cdhash:${cdhash}` + } + + beforeAll(() => { + directory = mkdtempSync(join(tmpdir(), 'sim-keychain-test-')) + keychain = join(directory, 'sim-test.keychain-db') + searchList = [...security('list-keychains', '-d', 'user').matchAll(/"([^"]+)"/g)].map( + (match) => match[1] + ) + security('create-keychain', '-p', keychainPassword, keychain) + security('unlock-keychain', '-p', keychainPassword, keychain) + security('list-keychains', '-d', 'user', '-s', keychain, ...searchList) + security('add-generic-password', '-s', service, '-a', account, '-w', password, '-A', keychain) + security( + 'set-generic-password-partition-list', + '-S', + `apple-tool:,apple:,${runnerPartition()}`, + '-s', + service, + '-k', + keychainPassword, + keychain + ) + security('find-generic-password', '-s', service, '-a', account) + }) + + afterAll(() => { + security('list-keychains', '-d', 'user', '-s', ...searchList) + security('delete-keychain', keychain) + rmSync(directory, { recursive: true, force: true }) + }) + + it('reads the password in-process, byte for byte', async () => { + await expect(loadAddon().readGenericPassword(service, account)).resolves.toEqual({ + status: 'found', + password, + }) + }) + + it('does not match an item by service alone', async () => { + await expect( + loadAddon().readGenericPassword(service, `${account}-other`) + ).resolves.toMatchObject({ status: 'missing' }) + }) + }) + + it('reports an item that does not exist as missing, without prompting', async () => { + const result = await loadAddon().readGenericPassword( + `Sim Test ${generateId()}`, + `sim-test-${generateId()}` + ) + expect(result).toEqual({ status: 'missing', code: ERR_SEC_ITEM_NOT_FOUND }) + }) + + it('rejects arguments that are not strings', () => { + const addon = loadAddon() as unknown as Record unknown> + expect(() => addon.readGenericPassword('service')).toThrow(TypeError) + expect(() => addon.readGenericPassword('service', 42)).toThrow(TypeError) + }) +})