Skip to content
Merged
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
1 change: 1 addition & 0 deletions packages/astro/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export {
localVariablesIntegration,
lruMemoizerIntegration,
makeNodeTransport,
getHttpAgent,
modulesIntegration,
nodeRuntimeMetricsIntegration,
type NodeRuntimeMetricsOptions,
Expand Down
1 change: 1 addition & 0 deletions packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export {
withScope,
withIsolationScope,
makeNodeTransport,
getHttpAgent,
NodeClient,
defaultStackParser,
lastEventId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as http from 'node:http';
import * as https from 'node:https';
import { buffer } from 'node:stream/consumers';
import {
consoleSandbox,
Expand All @@ -8,6 +9,7 @@ import {
getEnvelopeEndpointWithUrlEncodedAuth,
makeDsn,
} from '@sentry/core';
import { getHttpAgent } from '@sentry/node';
import { DEBUG_BUILD } from './debug-build';

/**
Expand Down Expand Up @@ -116,7 +118,7 @@ export class AwsLambdaExtension {
/**
* Starts the Sentry tunnel.
*/
public startSentryTunnel(): void {
public startSentryTunnel(port = 9000): http.Server {
const allowedDsnComponents = getSentryDSNFromEnv();

if (!allowedDsnComponents) {
Expand All @@ -134,10 +136,7 @@ export class AwsLambdaExtension {
if (req.method === 'POST' && req.url?.startsWith('/envelope')) {
try {
const buf = await buffer(req);
// Extract the actual bytes from the Buffer by slicing its underlying ArrayBuffer
// This ensures we get only the data portion without any padding or offset
const envelopeBytes = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
const envelope = new TextDecoder().decode(envelopeBytes);
Comment on lines -137 to -140

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we no longer pass the underlying ArrayBuffer around, so this slicing isn't needed anymore

const envelope = buf.toString('utf8');
const piece = envelope.split('\n')[0];
const header = JSON.parse(piece || '{}') as { dsn?: string };
const envelopeDsn = header.dsn;
Expand Down Expand Up @@ -165,14 +164,7 @@ export class AwsLambdaExtension {
res.end(JSON.stringify({ error: 'Invalid DSN' }));
return;
}
const upstreamSentryUrl = getEnvelopeEndpointWithUrlEncodedAuth(dsn);

fetch(upstreamSentryUrl, {
method: 'POST',
body: envelopeBytes as BodyInit,
}).catch(err => {
DEBUG_BUILD && debug.error('Error sending envelope to Sentry', err);
});
forwardEnvelope(new URL(getEnvelopeEndpointWithUrlEncodedAuth(dsn)), buf);

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({}));
Expand All @@ -187,17 +179,34 @@ export class AwsLambdaExtension {
}
});

server.listen(9000, () => {
DEBUG_BUILD && debug.log('Sentry proxy listening on port 9000');
server.listen(port, () => {
DEBUG_BUILD && debug.log(`Sentry proxy listening on port ${port}`);
});

server.on('error', err => {
DEBUG_BUILD && debug.error('Error starting Sentry proxy', err);
process.exit(1);
});

return server;
}
}

function forwardEnvelope(url: URL, body: Buffer): void {
const req = (url.protocol === 'https:' ? https : http).request(
url,
// Without a retry on ECONNRESET, a keep-alive socket left stale by a freeze would drop the envelope.
{ method: 'POST', agent: getHttpAgent(url, { keepAlive: false }) },
res => {
res.resume();
},
);
req.on('error', err => {
DEBUG_BUILD && debug.error('Error sending envelope to Sentry', err);
});
req.end(body);
}

/**
* DSN components allowed for the Lambda extension `/envelope` tunnel, derived from `SENTRY_DSN`.
*
Expand Down
111 changes: 111 additions & 0 deletions packages/aws-serverless/test/aws-lambda-extension.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { once } from 'node:events';
import * as http from 'node:http';
import * as net from 'node:net';
import type { AddressInfo } from 'node:net';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { AwsLambdaExtension, getSentryDSNFromEnv } from '../src/lambda-extension/aws-lambda-extension';
Expand Down Expand Up @@ -89,6 +90,116 @@ describe('AwsLambdaExtension.next', () => {
});
});

describe('AwsLambdaExtension.startSentryTunnel', () => {
const servers: Array<http.Server> = [];

async function listen(server: http.Server): Promise<number> {
servers.push(server);
server.listen(0, '127.0.0.1');
await once(server, 'listening');
return (server.address() as AddressInfo).port;
}

async function setup(): Promise<{
sendEnvelope: () => Promise<void>;
received: Promise<{ url: string | undefined; body: string }>;
upstreamPort: number;
proxyPort: number;
connects: string[];
}> {
let resolveReceived: (value: { url: string | undefined; body: string }) => void;
const received = new Promise<{ url: string | undefined; body: string }>(resolve => {
resolveReceived = resolve;
});
const upstreamPort = await listen(
http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
resolveReceived({ url: req.url, body: Buffer.concat(chunks).toString() });
res.end('{}');
});
}),
);

const connects: string[] = [];
const proxy = http.createServer();
proxy.on('connect', (req: http.IncomingMessage, clientSocket: net.Socket) => {
connects.push(req.url ?? '');
const [host, port] = (req.url ?? '').split(':');
const upstreamSocket = net.connect(Number(port), host, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
upstreamSocket.pipe(clientSocket);
clientSocket.pipe(upstreamSocket);
});
});
const proxyPort = await listen(proxy);

const dsn = `http://public@127.0.0.1:${upstreamPort}/1`;
vi.stubEnv('SENTRY_DSN', dsn);

const tunnel = new AwsLambdaExtension().startSentryTunnel(0);
servers.push(tunnel);
await once(tunnel, 'listening');
const tunnelPort = (tunnel.address() as AddressInfo).port;

const envelope = `${JSON.stringify({ dsn })}\n${JSON.stringify({ type: 'event' })}\n{}`;
const sendEnvelope = async (): Promise<void> => {
const res = await fetch(`http://127.0.0.1:${tunnelPort}/envelope`, { method: 'POST', body: envelope });
expect(res.status).toBe(200);
};

return { sendEnvelope, received, upstreamPort, proxyPort, connects };
}

afterEach(async () => {
vi.unstubAllEnvs();
await Promise.all(
servers.splice(0).map(server => {
server.closeAllConnections();
return new Promise<void>(resolve => server.close(() => resolve()));
}),
);
});

test('forwards envelopes directly when no proxy is set', async () => {
vi.stubEnv('http_proxy', '');
const { sendEnvelope, received, connects } = await setup();

await sendEnvelope();

await expect(received).resolves.toEqual({
url: expect.stringMatching(/^\/api\/1\/envelope\/\?sentry_version=7&sentry_key=public/),
body: expect.stringContaining('"type":"event"'),
});
expect(connects).toEqual([]);
});

test('forwards envelopes through http_proxy', async () => {
const { sendEnvelope, received, upstreamPort, proxyPort, connects } = await setup();
vi.stubEnv('http_proxy', `http://127.0.0.1:${proxyPort}`);

await sendEnvelope();

await expect(received).resolves.toEqual({
url: expect.stringMatching(/^\/api\/1\/envelope\//),
body: expect.stringContaining('"type":"event"'),
});
expect(connects).toEqual([`127.0.0.1:${upstreamPort}`]);
});

test('skips the proxy for hosts in no_proxy', async () => {
const { sendEnvelope, received, proxyPort, connects } = await setup();
vi.stubEnv('http_proxy', `http://127.0.0.1:${proxyPort}`);
vi.stubEnv('no_proxy', '127.0.0.1');

await sendEnvelope();

await expect(received).resolves.toEqual(expect.objectContaining({ url: expect.any(String) }));
expect(connects).toEqual([]);
});
});

describe('getSentryDSNFromEnv', () => {
afterEach(() => {
delete process.env.SENTRY_DSN;
Expand Down
3 changes: 2 additions & 1 deletion packages/aws-serverless/test/lambda-extension-index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Server } from 'node:http';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';

let extension: Awaited<ReturnType<typeof setupExtension>>;
Expand All @@ -17,7 +18,7 @@ afterEach(() => {
async function setupExtension() {
const { AwsLambdaExtension } = await import('../src/lambda-extension/aws-lambda-extension');
vi.spyOn(AwsLambdaExtension.prototype, 'register').mockResolvedValue();
vi.spyOn(AwsLambdaExtension.prototype, 'startSentryTunnel').mockImplementation(() => {});
vi.spyOn(AwsLambdaExtension.prototype, 'startSentryTunnel').mockReturnValue({} as Server);
const next = vi.spyOn(AwsLambdaExtension.prototype, 'next').mockImplementation(() => new Promise(() => {}));
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
const exit = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
Expand Down
1 change: 1 addition & 0 deletions packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export {
withScope,
withIsolationScope,
makeNodeTransport,
getHttpAgent,
NodeClient,
defaultStackParser,
lastEventId,
Expand Down
1 change: 1 addition & 0 deletions packages/google-cloud-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export {
withScope,
withIsolationScope,
makeNodeTransport,
getHttpAgent,
NodeClient,
defaultStackParser,
lastEventId,
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export { workerThreadsIntegration } from './integrations/workerThreads';
export { cron } from './cron';
export { NODE_VERSION } from './nodeVersion';
export { defaultStackParser, getSentryRelease } from './sdk/api';
export { makeNodeTransport } from './transports';
export { getHttpAgent, makeNodeTransport } from './transports';
export { createGetModuleFromFilename } from './utils/module';

export { eveConversationHook, eveIntegration, getInstrumentedModuleNames } from '@sentry/server-utils';
Expand Down
31 changes: 21 additions & 10 deletions packages/node/src/transports/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,21 +60,32 @@ export function makeNodeTransport(options: NodeTransportOptions): Transport {

const isHttps = urlSegments.protocol === 'https:';

// Proxy prioritization: http => `options.proxy` | `process.env.http_proxy`
// Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy`
const nativeHttpModule = isHttps ? https : http;
const agent = getHttpAgent(urlSegments, { proxy: options.proxy, keepAlive: options.keepAlive });

const requestExecutor = createRequestExecutor(options, options.httpModule ?? nativeHttpModule, agent);
return createTransport(options, requestExecutor);
}

/**
* Returns the agent for requests to `url`: a proxy agent when a proxy applies, otherwise a plain keep-alive agent.
*
* Proxy prioritization: http => `options.proxy` | `process.env.http_proxy`
* Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy`
* Hosts listed in `process.env.no_proxy` are never proxied.
*/
export function getHttpAgent(url: URL, options: { proxy?: string; keepAlive?: boolean } = {}): http.Agent {
const isHttps = url.protocol === 'https:';
const proxy = applyNoProxyOption(
urlSegments,
url,
options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy,
);

const nativeHttpModule = isHttps ? https : http;
const keepAlive = options.keepAlive ?? true;
const agent = proxy
? (new HttpsProxyAgent(proxy) as http.Agent)
: new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 });
if (proxy) {
return new HttpsProxyAgent(proxy);
}

const requestExecutor = createRequestExecutor(options, options.httpModule ?? nativeHttpModule, agent);
return createTransport(options, requestExecutor);
return new (isHttps ? https : http).Agent({ keepAlive: options.keepAlive ?? true, maxSockets: 30, timeout: 2000 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extension inherits two-second socket timeout

Medium Severity

The non-proxy agent from getHttpAgent always sets timeout: 2000, including when keepAlive is false. The extension now uses that agent instead of fetch, so two seconds of socket inactivity destroys the connection and drops the envelope. That timeout existed to expire idle keep-alive pool sockets in the Node transport, not to bound one-shot extension uploads.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 71b1c25. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

False positive. The agent's timeout only destroys idle sockets in the agent's free pool. On an active request, Node just emits 'timeout' on the request and leaves the socket open (it "must be destroyed manually"). forwardEnvelope doesn't listen for 'timeout', so a slow upload keeps going.

}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/transports/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export type { NodeTransportOptions } from './http';

export { makeNodeTransport } from './http';
export { getHttpAgent, makeNodeTransport } from './http';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

l: Is it required that getHttpAgent is a public api? We could also return it as __INTERNAL_getHttpAgent and not export it in other SDKs. Once we have it public it is tough to change, keeping it internal for now is a little safer IMO

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not required, but discussed below 😅

IMHO it's also fine to export this as-is then and not as internal-prefixed probably 🤔

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Totally missed that. Thanks for the update

1 change: 1 addition & 0 deletions packages/remix/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export {
linkedErrorsIntegration,
localVariablesIntegration,
makeNodeTransport,
getHttpAgent,
modulesIntegration,
mongoIntegration,
mongooseIntegration,
Expand Down
1 change: 1 addition & 0 deletions packages/sveltekit/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export {
linkedErrorsIntegration,
localVariablesIntegration,
makeNodeTransport,
getHttpAgent,
modulesIntegration,
mongoIntegration,
mongooseIntegration,
Expand Down
Loading