import fetch from 'npm-registry-fetch'; import { checkForUpdate } from './checkForUpdate'; import { getNpmRegistryOptions } from './getNpmRegistryOptions'; import { log } from './log'; import { showBorderedMessage } from './showBorderedMessage'; import { getLastVersion } from './state/lastVersion'; import { version } from '../../package.json'; jest.mock('npm-registry-fetch'); jest.mock('./getNpmRegistryOptions'); jest.mock('./log'); jest.mock('./showBorderedMessage'); jest.mock('./state/lastVersion'); const fetchJson = fetch.json as unknown as jest.Mock; const pickRegistry = fetch.pickRegistry as unknown as jest.Mock; // Shaped like minipass-fetch's FetchError, which copies `code` from the TLS error const tlsError = Object.assign( new Error( 'request to https://registry.npmjs.org/alks/latest failed, reason: unable to get local issuer certificate' ), { code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY' } ); // Shaped like npm-registry-fetch's HttpErrorGeneral / HttpErrorAuthUnknown const httpError = (statusCode: number) => Object.assign(new Error(`${statusCode} - GET /alks/latest`), { statusCode, code: `E${statusCode}`, }); const certHint = 'NODE_EXTRA_CA_CERTS'; const registry = 'https://artifactory.example.com/api/npm/npm-remote/'; describe('checkForUpdate', () => { let consoleError: jest.SpyInstance; beforeEach(() => { consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); (getLastVersion as jest.Mock).mockResolvedValue(version); (getNpmRegistryOptions as jest.Mock).mockReturnValue({ registry }); pickRegistry.mockReturnValue(registry); }); afterEach(() => { jest.useRealTimers(); jest.resetAllMocks(); consoleError.mockRestore(); }); describe('registry lookup', () => { it('queries the configured registry with its credentials, a 3s timeout and no retries', async () => { const options = { registry, '//artifactory.example.com/api/npm/npm-remote/:_authToken': 'abc123', }; (getNpmRegistryOptions as jest.Mock).mockReturnValue(options); fetchJson.mockResolvedValue({ version }); await checkForUpdate(); expect(fetchJson).toHaveBeenCalledWith('/alks/latest', { ...options, timeout: 3000, retry: { retries: 0 }, }); expect(consoleError).not.toHaveBeenCalled(); }); it('leaves the registry to npm-registry-fetch when none is configured, so npm’s default applies', async () => { (getNpmRegistryOptions as jest.Mock).mockReturnValue({}); fetchJson.mockResolvedValue({ version }); await checkForUpdate(); expect(fetchJson.mock.calls[0][1]).not.toHaveProperty('registry'); // ...and that default is npm's, not one built into the CLI expect( jest .requireActual('npm-registry-fetch') .pickRegistry('alks', {}) ).toBe('https://registry.npmjs.org/'); }); }); describe('when the check fails', () => { it('warns instead of throwing when the registry request fails', async () => { fetchJson.mockRejectedValue(tlsError); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError).toHaveBeenCalledTimes(1); expect(consoleError.mock.calls[0][0]).toContain( 'WARNING: update check failed: request to https://registry.npmjs.org/alks/latest failed, reason: unable to get local issuer certificate' ); expect(consoleError.mock.calls[0][0]).toContain(certHint); expect(showBorderedMessage).not.toHaveBeenCalled(); expect(log).toHaveBeenCalledWith( 'check for update failed: ' + tlsError.message, { verbose: false } ); }); it.each([ ['connection refused', 'ECONNREFUSED'], ['DNS failure', 'ENOTFOUND'], ])('warns on %s', async (_name, code) => { fetchJson.mockRejectedValue( Object.assign(new Error('request failed'), { code }) ); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError.mock.calls[0][0]).toContain( 'WARNING: update check failed: request failed' ); expect(consoleError.mock.calls[0][0]).not.toContain(certHint); }); it('warns on an HTTP error status', async () => { fetchJson.mockRejectedValue(httpError(503)); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError.mock.calls[0][0]).toContain( 'WARNING: update check failed: 503 - GET /alks/latest' ); expect(consoleError.mock.calls[0][0]).not.toContain(certHint); }); it.each([401, 403])( 'says the login was rejected on a %i, without a certificate workaround', async (status) => { fetchJson.mockRejectedValue(httpError(status)); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError).toHaveBeenCalledTimes(1); const warning = consoleError.mock.calls[0][0]; expect(warning).toContain('WARNING: update check failed:'); expect(warning).toContain(registry); expect(warning).toContain(`rejected the login`); expect(warning).toContain(`HTTP ${status}`); expect(warning).not.toContain(certHint); expect(warning).not.toContain('certificate'); } ); it('never prints credentials embedded in the registry URL', async () => { pickRegistry.mockReturnValue( 'https://user:s3cret@artifactory.example.com/api/npm/npm-remote/' ); fetchJson.mockRejectedValue(httpError(401)); await checkForUpdate(); expect(consoleError.mock.calls[0][0]).not.toContain('s3cret'); expect(consoleError.mock.calls[0][0]).toContain( 'https://artifactory.example.com/api/npm/npm-remote/' ); }); it('removes the whole password when it contains a raw @', async () => { pickRegistry.mockReturnValue('//user:p@ss@artifactory.example.com/npm/'); fetchJson.mockRejectedValue(httpError(401)); await checkForUpdate(); expect(consoleError.mock.calls[0][0]).not.toContain('ss@'); expect(consoleError.mock.calls[0][0]).not.toContain('p@ss'); for (const [message] of (log as jest.Mock).mock.calls) { expect(message).not.toContain('ss@'); expect(message).not.toContain('p@ss'); } expect( (log as jest.Mock).mock.calls.some(([m]) => String(m).includes('//artifactory.example.com/npm/') ) ).toBe(true); }); it('never logs credentials from a registry URL that cannot be parsed', async () => { // A protocol-relative URL is not valid for new URL(), so it can't be // stripped by parsing and has to be redacted as text pickRegistry.mockReturnValue( '//user:s3cret@artifactory.example.com/npm/' ); fetchJson.mockRejectedValue(httpError(401)); await checkForUpdate(); expect(consoleError.mock.calls[0][0]).not.toContain('s3cret'); expect( (log as jest.Mock).mock.calls.some(([m]) => String(m).includes('//artifactory.example.com/npm/') ) ).toBe(true); for (const [message] of (log as jest.Mock).mock.calls) { expect(message).not.toContain('s3cret'); } }); it.each([ '//user:pa/ss@artifactory.example.com/npm/', 'user:pa/ss@artifactory.example.com/npm/', ])('removes a password containing a raw / from %s', async (registry) => { pickRegistry.mockReturnValue(registry); fetchJson.mockRejectedValue(httpError(401)); await checkForUpdate(); expect(consoleError.mock.calls[0][0]).not.toContain('pa/ss'); expect( (log as jest.Mock).mock.calls.some(([m]) => String(m).includes('artifactory.example.com/npm/') ) ).toBe(true); for (const [message] of (log as jest.Mock).mock.calls) { expect(message).not.toContain('pa/ss'); expect(message).not.toContain('user:'); } }); it('never logs credentials from a scheme-less registry value', async () => { // user:pass@host/ parses as an opaque URL with protocol "user:", so the // credential survives parsing and has to be redacted as text pickRegistry.mockReturnValue('user:s3cret@artifactory.example.com/npm/'); fetchJson.mockRejectedValue(httpError(401)); await checkForUpdate(); expect(consoleError.mock.calls[0][0]).not.toContain('s3cret'); expect( (log as jest.Mock).mock.calls.some(([m]) => String(m).includes('artifactory.example.com/npm/') ) ).toBe(true); for (const [message] of (log as jest.Mock).mock.calls) { expect(message).not.toContain('s3cret'); } }); it.each([ [ 'an HTTP error', httpError(503), 'https://user:s3cret@artifactory.example.com/api/npm/npm-remote/', ], [ 'a certificate error', Object.assign( new Error( 'request to https://user:s3cret@artifactory.example.com/api/npm/npm-remote/alks/latest failed, reason: unable to get local issuer certificate' ), { code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY' } ), 'https://user:s3cret@artifactory.example.com/api/npm/npm-remote/', ], [ 'a refused connection', new Error( 'request to http://u53r:s3cret@localhost:9/alks/latest failed, reason: connect ECONNREFUSED' ), 'http://u53r:s3cret@localhost:9/', ], ])( 'never prints credentials from the registry URL on %s', async (_label, error, registryUrl) => { pickRegistry.mockReturnValue(registryUrl); if (error.message.startsWith('503')) { error.message = `503 Service Unavailable - GET ${registryUrl}alks/latest`; } fetchJson.mockRejectedValue(error); await checkForUpdate(); expect(consoleError.mock.calls[0][0]).not.toContain('s3cret'); for (const [message] of (log as jest.Mock).mock.calls) { expect(message).not.toContain('s3cret'); } } ); it('warns instead of throwing when reading the npm configuration fails', async () => { (getNpmRegistryOptions as jest.Mock).mockImplementation(() => { throw new Error('EISDIR: illegal operation on a directory'); }); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError.mock.calls[0][0]).toContain( 'WARNING: update check failed: EISDIR' ); }); it('warns instead of throwing when reading local state fails', async () => { fetchJson.mockResolvedValue({ version }); (getLastVersion as jest.Mock).mockRejectedValue( new Error('EACCES: permission denied') ); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(consoleError.mock.calls[0][0]).toContain( 'WARNING: update check failed: EACCES: permission denied' ); }); }); describe('timeouts', () => { it('skips silently once 3 seconds pass, even if the request fails afterwards', async () => { jest.useFakeTimers(); let rejectFetch: (err: Error) => void = () => {}; fetchJson.mockReturnValue( new Promise((_, reject) => { rejectFetch = reject; }) ); const pending = checkForUpdate(); jest.advanceTimersByTime(2999); expect(log).not.toHaveBeenCalledWith( 'check for update timed out. Skipping...' ); jest.advanceTimersByTime(1); await pending; rejectFetch(tlsError); await Promise.resolve(); await Promise.resolve(); expect(log).toHaveBeenCalledWith( 'check for update timed out. Skipping...' ); expect(consoleError).not.toHaveBeenCalled(); }); it.each([ ['a request timeout', { type: 'request-timeout' }], ['a socket timeout', { code: 'ETIMEDOUT' }], ['a connection timeout', { code: 'ECONNECTIONTIMEOUT' }], ['a response timeout', { code: 'ERESPONSETIMEOUT' }], ])('only logs %s reported by the fetch library', async (_name, props) => { fetchJson.mockRejectedValue(Object.assign(new Error('timed out'), props)); await expect(checkForUpdate()).resolves.toBeUndefined(); expect(log).toHaveBeenCalledWith( 'check for update timed out. Skipping...' ); expect(consoleError).not.toHaveBeenCalled(); }); it('clears the timeout once the check has finished', async () => { jest.useFakeTimers(); fetchJson.mockResolvedValue({ version }); await checkForUpdate(); expect(jest.getTimerCount()).toBe(0); }); }); it('shows the update banner when a newer version exists', async () => { fetchJson.mockResolvedValue({ version: '999.0.0' }); await checkForUpdate(); expect(showBorderedMessage).toHaveBeenCalledWith( 40, expect.stringContaining('999.0.0') ); expect(consoleError).not.toHaveBeenCalled(); }); });