Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/Repeater/RepeaterServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ export type RepeaterServerRequestResponse =
protocol: Protocol;
message?: string;
errorCode?: string;
}
| {
// The payload could not be turned into a Request. Unlike the
// { message, errorCode } variant, this is not a target-side failure.
protocol: Protocol;
protocolError: { code: RepeaterErrorCodes; message: string };
};

export interface RepeaterServerReconnectionFailedEvent {
Expand All @@ -68,6 +74,9 @@ export enum RepeaterErrorCodes {
REPEATER_DEACTIVATED = 'repeater_deactivated',
REPEATER_UNAUTHORIZED = 'repeater_unauthorized',
REPEATER_NO_LONGER_SUPPORTED = 'repeater_no_longer_supported',
// Sent on the per-request `protocolError` ack, not the deploy-time `error`
// event, so it never trips isCriticalError.
MALFORMED_REQUEST = 'malformed_request',
UNKNOWN_ERROR = 'unknown_error',
UNEXPECTED_ERROR = 'unexpected_error'
}
Expand Down
227 changes: 190 additions & 37 deletions src/Repeater/ServerRepeaterLauncher.spec.ts
Original file line number Diff line number Diff line change
@@ -1,60 +1,213 @@
import 'reflect-metadata';
import { ServerRepeaterLauncher } from './ServerRepeaterLauncher';
import { RepeaterServer, RepeaterServerEvents } from './RepeaterServer';
import { RuntimeDetector } from './RuntimeDetector';
import {
RepeaterServer,
RepeaterServerEvents,
RepeaterServerEventHandler,
RepeaterServerRequestEvent,
RepeaterServerRequestResponse,
RepeaterErrorCodes
} from './RepeaterServer';
import { RepeaterCommandHub } from './RepeaterCommandHub';
import { ScriptLoader, VirtualScripts } from '../Scripts';
import { RuntimeDetector } from './RuntimeDetector';
import { StartupManager } from '../StartupScripts';
import { Certificates, RequestExecutorOptions } from '../RequestExecutor';
import { ScriptLoader, VirtualScripts } from '../Scripts';
import {
Certificates,
Protocol,
RequestExecutorOptions,
Response
} from '../RequestExecutor';
import { CliInfo } from '../Config';
import { Logger, logger } from '../Utils';
import { anything, instance, mock, reset, spy, verify, when } from 'ts-mockito';
import { logger } from '../Utils';
import { anything, instance, mock, reset, verify, when } from 'ts-mockito';
import { captureException } from '@sentry/node';

jest.mock('@sentry/node', () => ({
captureException: jest.fn(),
setTag: jest.fn()
}));

describe('ServerRepeaterLauncher', () => {
const mockedRepeaterServer = mock<RepeaterServer>();
const handlers = new Map<string, (payload?: unknown) => unknown>();

let loggerSpy: Logger;
let launcher: ServerRepeaterLauncher;

beforeEach(() => {
loggerSpy = spy(logger);
when(loggerSpy.warn(anything(), anything())).thenReturn();
when(mockedRepeaterServer.on(anything(), anything())).thenCall(
(event: string, handler: (payload?: unknown) => unknown) =>
handlers.set(event, handler)
);
const runtimeDetectorMock = mock<RuntimeDetector>();
const virtualScriptsMock = mock<VirtualScripts>();
const startupManagerMock = mock<StartupManager>();
const commandHubMock = mock<RepeaterCommandHub>();
const certificatesMock = mock<Certificates>();
const scriptLoaderMock = mock<ScriptLoader>();
const requestExecutorOptionsMock = mock<RequestExecutorOptions>();
const cliInfoMock = mock<CliInfo>();

const handlers = new Map<string, RepeaterServerEventHandler<never>>();
const repeaterServer: RepeaterServer = {
disconnect: (): void => undefined,
connect: (): Promise<void> => Promise.resolve(),
deploy: (): Promise<never> => Promise.resolve() as never,
on: (event, handler): void => {
handlers.set(event, handler as RepeaterServerEventHandler<never>);
},
off: (): void => undefined
};

launcher = new ServerRepeaterLauncher(
instance(mock<RuntimeDetector>()),
instance(mock<VirtualScripts>()),
instance(mockedRepeaterServer),
instance(mock<StartupManager>()),
instance(mock<RepeaterCommandHub>()),
instance(mock<Certificates>()),
instance(mock<ScriptLoader>()),
{} as RequestExecutorOptions,
{ version: '1.0.0' } as CliInfo
let sut: ServerRepeaterLauncher;
let loggerErrorSpy: jest.SpyInstance;

const requestHandler = (): ((
event: RepeaterServerRequestEvent
) => Promise<RepeaterServerRequestResponse>) =>
handlers.get(RepeaterServerEvents.REQUEST) as unknown as (
event: RepeaterServerRequestEvent
) => Promise<RepeaterServerRequestResponse>;

beforeEach(async () => {
handlers.clear();
(captureException as jest.Mock).mockClear();
loggerErrorSpy = jest.spyOn(logger, 'error').mockImplementation(() => 0);

when(cliInfoMock.version).thenReturn('0.0.0-test');
when(virtualScriptsMock.size).thenReturn(0);
when(virtualScriptsMock.count(anything())).thenReturn(0);

sut = new ServerRepeaterLauncher(
instance(runtimeDetectorMock),
instance(virtualScriptsMock),
repeaterServer,
instance(startupManagerMock),
instance(commandHubMock),
instance(certificatesMock),
instance(scriptLoaderMock),
instance(requestExecutorOptionsMock),
instance(cliInfoMock)
);

await sut.run('repeater-1');
});

afterEach(() => {
handlers.clear();
reset<RepeaterServer | Logger>(mockedRepeaterServer, loggerSpy);
loggerErrorSpy.mockRestore();
reset(commandHubMock);
});

describe('run', () => {
it('should log a reconnecting warning on a reconnection attempt', async () => {
const okResponse = (): Response =>
({
protocol: Protocol.HTTP,
statusCode: 200,
headers: { 'content-type': 'text/plain' },
body: 'ok'
} as unknown as Response);

it('should ack with a protocol error when the request payload cannot be constructed', async () => {
// arrange
const event: RepeaterServerRequestEvent = {
protocol: Protocol.HTTP,
url: ''
};

// act
const response = await requestHandler()(event);

// assert
expect(response).toEqual({
protocol: Protocol.HTTP,
protocolError: {
code: RepeaterErrorCodes.MALFORMED_REQUEST,
message: 'Invalid URL: '
}
});
});

it('should not invoke the command hub when the request payload cannot be constructed', async () => {
// arrange
const event: RepeaterServerRequestEvent = {
protocol: Protocol.HTTP,
url: ''
};

// act
await requestHandler()(event);

// assert
verify(commandHubMock.sendRequest(anything())).never();
});

it('should ack with message and errorCode when execution itself fails', async () => {
// arrange
when(commandHubMock.sendRequest(anything())).thenResolve({
protocol: Protocol.HTTP,
message: 'Connection refused',
errorCode: 'ECONNREFUSED'
} as unknown as Response);
const event: RepeaterServerRequestEvent = {
protocol: Protocol.HTTP,
url: 'http://valid.test/'
};

// act
const response = await requestHandler()(event);

// assert
expect(response).toMatchObject({
protocol: Protocol.HTTP,
message: 'Connection refused',
errorCode: 'ECONNREFUSED'
});
expect('protocolError' in response).toBe(false);
});

it('should ack with the response fields on a successful request', async () => {
// arrange
when(commandHubMock.sendRequest(anything())).thenResolve(okResponse());
const event: RepeaterServerRequestEvent = {
protocol: Protocol.HTTP,
url: 'http://valid.test/'
};

// act
const response = await requestHandler()(event);

// assert
expect(response).toMatchObject({
protocol: Protocol.HTTP,
statusCode: 200,
body: 'ok'
});
});

it('should not report a rejected payload to Sentry', async () => {
// arrange
const event: RepeaterServerRequestEvent = {
protocol: Protocol.HTTP,
url: ''
};

// act
await requestHandler()(event);

// assert
expect(captureException).not.toHaveBeenCalled();
expect(loggerErrorSpy).toHaveBeenCalled();
});

it('should log a reconnecting warning on a reconnection attempt', () => {
// arrange
await launcher.run('8PY6wKetVqmfMC9K9g4A7Y');
const loggerWarnSpy = jest
.spyOn(logger, 'warn')
.mockImplementation(() => 0);

// act
handlers.get(RepeaterServerEvents.RECONNECT_ATTEMPT)?.({ attempt: 2 });
(
handlers.get(RepeaterServerEvents.RECONNECT_ATTEMPT) as (
payload: unknown
) => unknown
)({ attempt: 2 });

// assert
verify(
loggerSpy.warn('Reconnecting to Bright cloud (attempt %d)', 2)
).once();
expect(loggerWarnSpy).toHaveBeenCalledWith(
'Reconnecting to Bright cloud (attempt %d)',
2
);
loggerWarnSpy.mockRestore();
});
});
});
23 changes: 20 additions & 3 deletions src/Repeater/ServerRepeaterLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,9 +245,26 @@ export class ServerRepeaterLauncher implements RepeaterLauncher {
private requestReceived = async (
event: RepeaterServerRequestEvent
): Promise<RepeaterServerRequestResponse> => {
const response = await this.commandHub.sendRequest(
new Request({ ...event })
);
let request: Request;

try {
request = new Request({ ...event });
} catch (e) {
const reason = e instanceof Error ? e.message : String(e);
// Scanners deliberately send malformed targets; logged but not sent to
// Sentry to avoid noise.
logger.error('Rejecting a malformed request from the bridge: %s', reason);

return {
protocol: event.protocol,
protocolError: {
code: RepeaterErrorCodes.MALFORMED_REQUEST,
message: reason
}
};
}

const response = await this.commandHub.sendRequest(request);

const {
statusCode,
Expand Down
62 changes: 62 additions & 0 deletions src/RequestExecutor/HttpRequestExecutor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2287,4 +2287,66 @@ describe('HttpRequestExecutor', () => {
}).toEqual(expect.objectContaining({ withinBudget: true }));
}, 60000);
});

// Pins the libcurl behaviour on the supported runtime (engines: >=22 <=24).
describe('execute', () => {
// Redefines the readonly url on a valid request to bypass the blank-url
// check in the constructor.
const malformedRequest = (url: string): Request => {
const request = new Request({
url: 'http://placeholder.invalid/',
protocol: Protocol.HTTP
});
Object.defineProperty(request, 'url', { value: url, writable: false });

return request;
};

// libcurl rejects each malformed authority as CURLE_URL_MALFORMAT. What
// matters is that execute returns this failure rather than throwing,
// hanging, or short-circuiting with ERR_INVALID_URL.
const CURL_MALFORMAT_MESSAGE =
'Request failed: URL using bad/illegal format or missing URL';

const cases: [name: string, url: string][] = [
['non-numeric port', 'http://host.invalid:notaport/'],
['port > 65535', 'http://host.invalid:99999/'],
['unbracketed IPv6', 'http://::1/'],
['space in host', 'http://ho st.invalid/'],
['[not-ipv6]', 'http://[not-ipv6]/'],
['empty string', '']
];

it.each(cases)(
'should reach libcurl and return a defined error for %s (not ERR_INVALID_URL, no throw/hang)',
async (_name, url) => {
// arrange
const sut = buildSut();
const request = malformedRequest(url);

// act
const response = await sut.execute(request);

// assert
expect(response.errorCode).toBeDefined();
expect(response.errorCode).not.toBe('ERR_INVALID_URL');
expect(response.message).toBe(CURL_MALFORMAT_MESSAGE);
},
10_000
);

it('should short-circuit an empty authority without reaching a virtual script', async () => {
// arrange — an origin-form target has no hostname, so no virtual script
// lookup is attempted.
const sut = buildSut();
const request = malformedRequest('/origin-form-only');

// act
const response = await sut.execute(request);

// assert
expect(response).toBeDefined();
verify(virtualScriptsMock.find(anything())).never();
});
});
});
Loading
Loading