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
45 changes: 37 additions & 8 deletions packages/browser/src/utils/managedTunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,34 @@ import type { BrowserTunnelOptions } from '@sentry/core';
import {
debug,
getTunnelPath,
isURLObjectRelative,
makeDsn,
_INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath,
parseStringToURLObject,
} from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
import type { BrowserOptions } from '../client';
import { WINDOW } from '../helpers';

/**
* Resolves `tunnel: true` or {@link BrowserTunnelOptions} to the managed tunnel's same-origin path. A string is left as
* written, so a tunnel the app serves itself gets the same requests as before.
* written, so a tunnel the app serves itself keeps its URL.
*/
export function resolveBrowserTunnelOption(
options: BrowserOptions,
): Pick<BrowserOptions, 'transportOptions'> & { tunnel: string | undefined } {
const { tunnel, dsn, transportOptions } = options;
if (!tunnel || typeof tunnel === 'string') {
if (!tunnel) {
return { tunnel, transportOptions };
}

if (typeof tunnel === 'string') {
return {
tunnel,
transportOptions: isSameOrigin(tunnel) ? withEnvelopeContentType(transportOptions) : transportOptions,
};
}

const tunnelOptions: BrowserTunnelOptions = tunnel === true ? {} : tunnel;
const dsnComponents = dsn && makeDsn(dsn);
const tunnelPath = tunnelOptions.path ?? (dsnComponents && getTunnelPath(dsnComponents));
Expand All @@ -32,12 +42,31 @@ export function resolveBrowserTunnelOption(

DEBUG_BUILD && debug.log(`Tunneling events to "${resolvedTunnel}"`);

return { tunnel: resolvedTunnel, transportOptions: withEnvelopeContentType(transportOptions) };
}

/**
* Sends envelopes as `application/x-sentry-envelope`. CSRF protection (SvelteKit, Astro) rejects the default
* `text/plain` POST as a form submission, and the Next.js managed tunnel route on Vercel matches on this header.
* Cross-origin it would trigger a CORS preflight, so only same-origin tunnels get it.
*/
function withEnvelopeContentType(
transportOptions: BrowserOptions['transportOptions'],
): BrowserOptions['transportOptions'] {
return {
tunnel: resolvedTunnel,
transportOptions: {
...transportOptions,
// CSRF protection (SvelteKit, Astro) rejects the default `text/plain` POST to the tunnel as a form submission.
headers: { 'Content-Type': 'application/x-sentry-envelope', ...transportOptions?.headers },
},
...transportOptions,
headers: { 'Content-Type': 'application/x-sentry-envelope', ...transportOptions?.headers },
};
}

/**
* Whether the tunnel URL is on the page's origin. Unknown counts as cross-origin.
*/
function isSameOrigin(url: string): boolean {
const urlObject = parseStringToURLObject(url, WINDOW.location?.href);
if (!urlObject) {
return false;
}

return isURLObjectRelative(urlObject) || urlObject.origin === WINDOW.location?.origin;
}
30 changes: 27 additions & 3 deletions packages/browser/test/utils/managedTunnel.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/**
* @vitest-environment jsdom
*/

import { getTunnelPath } from '@sentry/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getClient, getCurrentScope, init } from '../../src';
Expand Down Expand Up @@ -43,15 +47,35 @@ describe('resolveBrowserTunnelOption', () => {
expect(resolveBrowserTunnelOption({ dsn: DSN, tunnel: { path: '/monitor' } }).tunnel).toBe('/monitor');
});

it.each(['https://proxy.example.com/tunnel', '/monitor'])(
'keeps the string tunnel %s and its transport options untouched',
it.each(['/monitor', 'monitor', `${location.origin}/monitor`])(
'sends to the same-origin string tunnel %s as application/x-sentry-envelope too',
tunnel => {
expect(
resolveBrowserTunnelOption({ dsn: DSN, tunnel, transportOptions: { headers: { 'X-Custom': '1' } } }),
).toEqual({
tunnel,
transportOptions: { headers: { 'Content-Type': 'application/x-sentry-envelope', 'X-Custom': '1' } },
});
},
);

it.each(['https://proxy.example.com/tunnel', '//proxy.example.com/tunnel'])(
'keeps the cross-origin string tunnel %s and its transport options untouched, so it needs no CORS preflight',
tunnel => {
const transportOptions = { headers: { 'x-custom': '1' } };

expect(resolveBrowserTunnelOption({ dsn: DSN, tunnel, transportOptions })).toEqual({ tunnel, transportOptions });
},
);

it('lets a user content type override the envelope one', () => {
const transportOptions = { headers: { 'Content-Type': 'text/plain' } };

expect(resolveBrowserTunnelOption({ dsn: DSN, tunnel: '/monitor', transportOptions }).transportOptions).toEqual(
transportOptions,
);
});

it('turns the tunnel off without a valid DSN', () => {
expect(resolveBrowserTunnelOption({ tunnel: true }).tunnel).toBeUndefined();
expect(resolveBrowserTunnelOption({ dsn: 'not-a-dsn', tunnel: true }).tunnel).toBeUndefined();
Expand All @@ -69,7 +93,7 @@ describe('init with `tunnel: true`', () => {
expect(getClient()?.getOptions().tunnel).toBe(getTunnelPath(DSN));
});

it('only sets the envelope content type for a managed tunnel', () => {
it('only sets the envelope content type for a same-origin tunnel', () => {
const transport = vi.fn(makeFetchTransport);

init({ dsn: DSN, tunnel: true, transport });
Expand Down
Loading