// Tests for the keystore adapter over @napi-rs/keyring (TASK-2). // The adapter (getKeytar) is the single boundary that translates the library's // entry-object API (`new AsyncEntry(service, account)`) into the module-style // getPassword/setPassword/deletePassword(service, account) surface the three // call sites already use — so getTokenFromKeystore/storeToken/removeToken stay // unchanged. These tests pin the two behavioral gotchas the spec called out: // a missing entry must read back as `undefined` (not surface a NoEntry error), // and deleting a missing entry must be a no-op — whether the binding signals // "missing" by returning null/false (its behavior on macOS) or by throwing a // NoEntry error (its documented behavior on other platforms/versions). // Test doubles below define several fake AsyncEntry classes and intentionally // empty stubs; relax the rules that don't fit test fixtures. /* tslint:disable:max-classes-per-file no-empty */ type GetKeytar = typeof import('./getKeytar').getKeytar; // Build an in-memory fake of @napi-rs/keyring's AsyncEntry backed by a shared // store, so separate `new AsyncEntry(...)` calls per operation see one another. // The store holds raw bytes, mirroring the real credential stores: the adapter // talks to setSecret/getSecret, not setPassword/getPassword. function inMemoryKeyring() { const store = new Map(); const ctorArgs: [string, string][] = []; class AsyncEntry { private key: string; constructor(service: string, account: string) { this.key = `${service}::${account}`; ctorArgs.push([service, account]); } async getSecret(): Promise { return store.has(this.key) ? (store.get(this.key) as Uint8Array) : null; } async setSecret(secret: Uint8Array): Promise { store.set(this.key, secret); } async deletePassword(): Promise { return store.delete(this.key); } } return { module: { AsyncEntry }, store, ctorArgs }; } // A keyring whose get/delete reject with a configurable error — used to model // both a missing credential (must be swallowed) and a genuine failure (must // propagate). makeError returns a fresh error per call. function rejectingKeyring(makeError: () => Error) { class AsyncEntry { constructor(_service: string, _account: string) {} async getSecret(): Promise { throw makeError(); } async setSecret(_secret: Uint8Array): Promise { /* not exercised */ } async deletePassword(): Promise { throw makeError(); } } return { module: { AsyncEntry } }; } // A keyring pre-seeded with a credential whose bytes were written by an earlier // version of the CLI, to exercise the read-compatibility paths. function preSeededKeyring(service: string, account: string, blob: Uint8Array) { const harness = inMemoryKeyring(); harness.store.set(`${service}::${account}`, blob); return harness; } // A missing credential signalled by error CODE (the reliable, primary signal). function throwingKeyring() { return rejectingKeyring(() => { const err = new Error( 'No matching entry found in secure storage' ) as Error & { code?: string }; err.code = 'NoEntry'; return err; }); } // Load getKeytar fresh with the given @napi-rs/keyring mock and a silent log. function loadGetKeytar(keyringModule: unknown): GetKeytar { jest.resetModules(); jest.doMock('@napi-rs/keyring', () => keyringModule, { virtual: true }); jest.doMock('./log', () => ({ log: jest.fn() })); // eslint-disable-next-line @typescript-eslint/no-var-requires return require('./getKeytar').getKeytar; } // Load getKeytar where importing the native library fails, to exercise the // error-surfacing path. function loadGetKeytarWithImportError(cause: Error): GetKeytar { jest.resetModules(); jest.doMock( '@napi-rs/keyring', () => { throw cause; }, { virtual: true } ); jest.doMock('./log', () => ({ log: jest.fn() })); // eslint-disable-next-line @typescript-eslint/no-var-requires return require('./getKeytar').getKeytar; } const SERVICE = 'alkscli'; const ACCOUNT = 'alkstoken'; afterEach(() => { jest.resetModules(); jest.clearAllMocks(); }); describe('getKeytar adapter', () => { it('round-trips a secret: set then get returns the stored value (AC-1.2)', async () => { const keytar = await loadGetKeytar(inMemoryKeyring().module)(); await keytar.setPassword(SERVICE, ACCOUNT, 'refresh-token-abc'); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBe( 'refresh-token-abc' ); }); // Windows Credential Manager caps a credential blob at // CRED_MAX_CREDENTIAL_BLOB_SIZE. keyring's setPassword() UTF-16-encodes first // and validates the doubled length against that cap, which capped tokens at // 1280 characters and made `alks developer configure` fail outright on // Windows for every real (~1700 char) ALKS refresh token. The adapter must // therefore write raw UTF-8 bytes via setSecret(). describe('secret encoding — Windows credential blob limit', () => { const CRED_MAX_CREDENTIAL_BLOB_SIZE = 2560; it('stores an ASCII token as UTF-8 bytes, one byte per character', async () => { const harness = inMemoryKeyring(); const keytar = await loadGetKeytar(harness.module)(); const token = 'refresh-token-abc'; await keytar.setPassword(SERVICE, ACCOUNT, token); const stored = harness.store.get(`${SERVICE}::${ACCOUNT}`) as Uint8Array; expect(Buffer.from(stored)).toEqual(Buffer.from(token, 'utf8')); expect(stored.length).toBe(token.length); // A UTF-16 encoding would interleave NUL bytes and double the size — // reverting to setPassword() would trip this. expect(Array.from(stored)).not.toContain(0x00); }); it('round-trips a realistic ~1700-character refresh token within the Windows blob limit', async () => { const harness = inMemoryKeyring(); const keytar = await loadGetKeytar(harness.module)(); // Representative of a real ALKS refresh token: printable ASCII, longer // than the 1280-character ceiling UTF-16 encoding would impose. const token = '1' + 'a1B2c3D4'.repeat(212); expect(token.length).toBe(1697); await keytar.setPassword(SERVICE, ACCOUNT, token); const stored = harness.store.get(`${SERVICE}::${ACCOUNT}`) as Uint8Array; expect(stored.length).toBeLessThanOrEqual(CRED_MAX_CREDENTIAL_BLOB_SIZE); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBe(token); }); it('keeps a non-ASCII token intact (multi-byte UTF-8 is not mistaken for UTF-16)', async () => { const harness = inMemoryKeyring(); const keytar = await loadGetKeytar(harness.module)(); const token = 'töken-jwt'; await keytar.setPassword(SERVICE, ACCOUNT, token); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBe(token); }); }); // The same credential may have been written by an older CLI. Reads must cope // with both historical encodings or an upgrade silently yields a corrupt // token: keytar wrote UTF-8, alks 4.1.0 wrote UTF-16LE. describe('read compatibility with tokens stored by earlier versions', () => { it('reads a keytar-written UTF-8 blob (alks <= 4.0.2)', async () => { const token = 'keytar-era-refresh-token'; const harness = preSeededKeyring( SERVICE, ACCOUNT, Buffer.from(token, 'utf8') ); const keytar = await loadGetKeytar(harness.module)(); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBe(token); }); it('reads a UTF-16LE blob written by alks 4.1.0 setPassword() instead of returning mojibake', async () => { const token = 'four-one-zero-refresh-token'; const harness = preSeededKeyring( SERVICE, ACCOUNT, Buffer.from(token, 'utf16le') ); const keytar = await loadGetKeytar(harness.module)(); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBe(token); }); }); it('exposes getPassword/setPassword/deletePassword taking (service, account) (AC-1.6)', async () => { const harness = inMemoryKeyring(); const keytar = await loadGetKeytar(harness.module)(); expect(typeof keytar.getPassword).toBe('function'); expect(typeof keytar.setPassword).toBe('function'); expect(typeof keytar.deletePassword).toBe('function'); await keytar.getPassword(SERVICE, ACCOUNT); // The adapter constructs the entry from the (service, account) it was given, // so call sites keep passing those keys unchanged. expect(harness.ctorArgs).toContainEqual([SERVICE, ACCOUNT]); }); describe('missing entry — binding returns null/false (macOS behavior)', () => { it('getPassword resolves undefined when no entry exists (AC-1.3)', async () => { const keytar = await loadGetKeytar(inMemoryKeyring().module)(); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBeUndefined(); }); it('deletePassword is a no-op when no entry exists (AC-1.4)', async () => { const keytar = await loadGetKeytar(inMemoryKeyring().module)(); await expect( keytar.deletePassword(SERVICE, ACCOUNT) ).resolves.not.toThrow(); }); }); describe('missing entry — binding throws NoEntry (cross-platform behavior)', () => { it('getPassword maps a NoEntry rejection to undefined (AC-1.3)', async () => { const keytar = await loadGetKeytar(throwingKeyring().module)(); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBeUndefined(); }); it('deletePassword swallows a NoEntry rejection as a no-op (AC-1.4)', async () => { const keytar = await loadGetKeytar(throwingKeyring().module)(); await expect( keytar.deletePassword(SERVICE, ACCOUNT) ).resolves.not.toThrow(); }); it('getPassword swallows a message-only NoEntry (no code) — e.g. macOS phrasing (AC-1.3)', async () => { const mod = rejectingKeyring( () => new Error('The specified item could not be found in the keychain.') ).module; const keytar = await loadGetKeytar(mod)(); expect(await keytar.getPassword(SERVICE, ACCOUNT)).toBeUndefined(); }); }); describe('genuine (non-NoEntry) errors must propagate, not be swallowed', () => { it('getPassword rejects on a real keychain failure (NFR-4)', async () => { const mod = rejectingKeyring( () => new Error('keychain access denied') ).module; const keytar = await loadGetKeytar(mod)(); await expect(keytar.getPassword(SERVICE, ACCOUNT)).rejects.toThrow( /access denied/ ); }); it('deletePassword rejects on a real keychain failure (NFR-4)', async () => { const mod = rejectingKeyring( () => new Error('keychain access denied') ).module; const keytar = await loadGetKeytar(mod)(); await expect(keytar.deletePassword(SERVICE, ACCOUNT)).rejects.toThrow( /access denied/ ); }); it('does NOT misclassify an unrelated "file not found" error as a missing entry (NFR-4)', async () => { // Guards the narrowed isNoEntryError heuristic: a generic "not found" // must surface, not be swallowed into a plaintext fallback. const mod = rejectingKeyring( () => new Error('ENOENT: no such file or directory, open config') ).module; const keytar = await loadGetKeytar(mod)(); await expect(keytar.getPassword(SERVICE, ACCOUNT)).rejects.toThrow( /no such file/ ); }); it('does NOT swallow a literal "file not found" error (guards a regex revert to /not found/) (NFR-4)', async () => { // Uses the exact "not found" phrasing so that widening isNoEntryError back // to a broad /not found/i would make this test fail. const mod = rejectingKeyring(() => new Error('file not found')).module; const keytar = await loadGetKeytar(mod)(); await expect(keytar.getPassword(SERVICE, ACCOUNT)).rejects.toThrow( /file not found/ ); }); }); it('surfaces the real underlying error when the native library fails to load (AC-2.1)', async () => { const cause = new Error( "Cannot find module '../build/Release/keyring.node'" ); const getKeytar = loadGetKeytarWithImportError(cause); // The real cause must be visible; the old generic "No keychain could be // found" / bare "reinstall" masking must not be the whole message. await expect(getKeytar()).rejects.toThrow( /Cannot find module .*keyring\.node/ ); await expect(getKeytar()).rejects.not.toThrow( /^No keychain could be found$/ ); }); });