Skip to content

feat(core): Add tunnel server helper #14137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
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
11 changes: 8 additions & 3 deletions dev-packages/node-integration-tests/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,20 @@ export function loggingTransport(_options: BaseTransportOptions): Transport {
* Setting this port to something specific is useful for local debugging but dangerous for
* CI/CD environments where port collisions can cause flakes!
*/
export function startExpressServerAndSendPortToRunner(app: Express, port: number | undefined = undefined): void {
export function startExpressServerAndSendPortToRunner(
app: Express,
port: number | undefined = undefined,
onPort?: (port: number) => void,
): void {
const server = app.listen(port || 0, () => {
const address = server.address() as AddressInfo;

// @ts-expect-error If we write the port to the app we can read it within route handlers in tests
app.port = port || address.port;
const actualPort = (app.port = port || address.port);

// eslint-disable-next-line no-console
console.log(`{"port":${port || address.port}}`);
console.log(`{"port":${actualPort}}`);
if (onPort) onPort(actualPort);
});
}

Expand Down
18 changes: 18 additions & 0 deletions dev-packages/node-integration-tests/suites/tunnel/child.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as Sentry from '@sentry/node';

console.log('Child process started');

Sentry.init({
dsn: 'https://[email protected]/1337',
release: '1.0',
tunnel: `http://localhost:${process.env.PORT}/tunnel`,
autoSessionTracking: false,
transportOptions: {
// I'm sure express.raw() can be made to work without this, but probably not worth trying to figure out how
headers: {
'Content-Type': 'application/octet-stream',
},
},
});

throw new Error('Test error in child process');
34 changes: 34 additions & 0 deletions dev-packages/node-integration-tests/suites/tunnel/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { fork } from 'child_process';
import { join } from 'path';
import { loggingTransport, startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests';
import { handleTunnelEnvelope } from '@sentry/core';
import * as Sentry from '@sentry/node';

const __dirname = new URL('.', import.meta.url).pathname;

Sentry.init({
dsn: 'https://[email protected]/1337',
release: '1.0',
autoSessionTracking: false,
transport: loggingTransport,
});

import express from 'express';

const app = express();

app.post('/tunnel', express.raw(), async (req, res) => {
await handleTunnelEnvelope(req.body);
res.sendStatus(200);
});

startExpressServerAndSendPortToRunner(app, undefined, port => {
const child = fork(join(__dirname, 'child.mjs'), {
stdio: 'inherit',
env: { ...process.env, PORT: port.toString() },
});
child.on('exit', code => {
console.log('Child process exited with code', code);
process.exit(code);
});
});
24 changes: 24 additions & 0 deletions dev-packages/node-integration-tests/suites/tunnel/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { cleanupChildProcesses, createRunner } from '../../utils/runner';

afterEach(() => {
cleanupChildProcesses();
});

const EXPECTED_EVENT = {
exception: {
values: [
{
type: 'Error',
value: 'Test error in child process',
},
],
},
};

test('handleTunnelEnvelope should forward envelopes', done => {
createRunner(__dirname, 'server.mjs')
.expect({
event: EXPECTED_EVENT,
})
.start(done);
});
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ export { instrumentFetchRequest } from './fetch';
export { trpcMiddleware } from './trpc';
export { captureFeedback } from './feedback';
export type { ReportDialogOptions } from './report-dialog';
export { handleTunnelEnvelope } from './tunnel';

// TODO: Make this structure pretty again and don't do "export *"
export * from './utils-hoist/index';
Expand Down
78 changes: 78 additions & 0 deletions packages/core/src/tunnel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { getEnvelopeEndpointWithUrlEncodedAuth } from './api';
import type { Client } from './client';
import { getClient } from './currentScopes';
import type { Transport } from './types-hoist/transport';
import { dsnFromString } from './utils-hoist/dsn';
import { createEnvelope, parseEnvelope } from './utils-hoist/envelope';

interface HandleTunnelOptions {
/**
* A list of DSNs that are allowed to be passed through the server.
*
* Defaults to only server DSN.
*/
dsnAllowList?: string[];
/**
* The client instance to use
*
* Defaults to the global instance.
*/
client?: Client;
}

let CACHED_TRANSPORTS: Map<string, Transport> | undefined;

/**
* Handles envelopes sent from the browser client via the tunnel option.
*/
export async function handleTunnelEnvelope(
envelopeBytes: Uint8Array,
options: HandleTunnelOptions = {},
): Promise<void> {
const client = options?.client || getClient();

if (!client) {
throw new Error('No server client');
}

const [headers, items] = parseEnvelope(envelopeBytes);

if (!headers.dsn) {
throw new Error('DSN missing from envelope headers');
}

// If the DSN in the envelope headers matches the server DSN, we can send it directly.
const clientOptions = client.getOptions();
if (headers.dsn === clientOptions.dsn) {
await client.sendEnvelope(createEnvelope(headers, items));
return;
}

if (!options.dsnAllowList?.includes(headers.dsn)) {
throw new Error('DSN does not match server DSN or allow list');
}

if (!CACHED_TRANSPORTS) {
CACHED_TRANSPORTS = new Map();
}

let transport = CACHED_TRANSPORTS.get(headers.dsn);

if (!transport) {
const dsn = dsnFromString(headers.dsn);
if (!dsn) {
throw new Error('Invalid DSN in envelope headers');
}
const url = getEnvelopeEndpointWithUrlEncodedAuth(dsn);

const createTransport = clientOptions.transport;
transport = createTransport({
...clientOptions.transportOptions,
recordDroppedEvent: client.recordDroppedEvent.bind(client),
url,
});
CACHED_TRANSPORTS.set(headers.dsn, transport);
}

await transport.send(createEnvelope(headers, items));
}
Loading