-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Framework-agnostic Tunnel Handler #18892
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
nikolovlazar
wants to merge
12
commits into
develop
Choose a base branch
from
nikolovlazar/agnostic-tunnel-handler
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+222
−2
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
171f927
feat(tunnel): framework-agnostic tunnel handler + tanstack start adapter
nikolovlazar 64add32
feat(tunnel): using parseEnvelope instead of manually extracting enve…
nikolovlazar 99f39eb
feat(tunnel): removing createTunnelHandler from tanstackstart-react p…
nikolovlazar d4d5634
refactor(tunnel): renamed handleTunnelRequest and made it receive Req…
nikolovlazar 1407dd6
test(tunnel): adding unit tests for createTunnelRequest
nikolovlazar a68c653
refactor(tunnel): refactoring core tunnel back to handle the request …
nikolovlazar b21e46e
Merge branch 'develop' into nikolovlazar/agnostic-tunnel-handler
nikolovlazar 105b75a
fix(tunnel): use getEnvelopeEndpointWithUrlEncodedAuth for proper ing…
nikolovlazar ecda7c2
fix(tunnel): handle malformed envelope JSON with 400 response
nikolovlazar c56c38b
fix(tanstackstart-react): linting error in client/index.ts
nikolovlazar 81e14fb
fix(tanstackstart-react): client/index.ts formatting
nikolovlazar 9bdceee
Merge branch 'develop' into nikolovlazar/agnostic-tunnel-handler
nikolovlazar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { getEnvelopeEndpointWithUrlEncodedAuth } from '../api'; | ||
| import { debug } from './debug-logger'; | ||
| import { makeDsn } from './dsn'; | ||
| import { parseEnvelope } from './envelope'; | ||
|
|
||
| export interface HandleTunnelRequestOptions { | ||
| /** Incoming request containing the Sentry envelope as its body */ | ||
| request: Request; | ||
| /** Pre-parsed array of allowed DSN strings */ | ||
| allowedDsns: Array<string>; | ||
| } | ||
|
|
||
| /** | ||
| * Core Sentry tunnel handler - framework agnostic. | ||
| * | ||
| * Validates the envelope DSN against allowed DSNs, then forwards the | ||
| * envelope to the Sentry ingest endpoint. | ||
| * | ||
| * @returns A `Response` — either the upstream Sentry response on success, or an error response. | ||
| */ | ||
| export async function handleTunnelRequest(options: HandleTunnelRequestOptions): Promise<Response> { | ||
| const { request, allowedDsns } = options; | ||
|
|
||
| if (allowedDsns.length === 0) { | ||
| return new Response('Tunnel not configured', { status: 500 }); | ||
| } | ||
|
|
||
| const body = new Uint8Array(await request.arrayBuffer()); | ||
|
|
||
| let envelopeHeader; | ||
| try { | ||
| [envelopeHeader] = parseEnvelope(body); | ||
| } catch { | ||
| return new Response('Invalid envelope', { status: 400 }); | ||
| } | ||
|
|
||
| if (!envelopeHeader) { | ||
| return new Response('Invalid envelope: missing header', { status: 400 }); | ||
| } | ||
|
|
||
| const dsn = envelopeHeader.dsn; | ||
| if (!dsn) { | ||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return new Response('Invalid envelope: missing DSN', { status: 400 }); | ||
| } | ||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // SECURITY: Validate that the envelope DSN matches one of the allowed DSNs | ||
| // This prevents SSRF attacks where attackers send crafted envelopes | ||
| // with malicious DSNs pointing to arbitrary hosts | ||
| const isAllowed = allowedDsns.some(allowed => allowed === dsn); | ||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (!isAllowed) { | ||
| debug.warn(`Sentry tunnel: rejected request with unauthorized DSN (${dsn})`); | ||
| return new Response('DSN not allowed', { status: 403 }); | ||
| } | ||
|
|
||
| const dsnComponents = makeDsn(dsn); | ||
| if (!dsnComponents) { | ||
| debug.warn(`Could not extract DSN Components from: ${dsn}`); | ||
| return new Response('Invalid DSN', { status: 403 }); | ||
| } | ||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const sentryIngestUrl = getEnvelopeEndpointWithUrlEncodedAuth(dsnComponents); | ||
|
|
||
| try { | ||
| return await fetch(sentryIngestUrl, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/x-sentry-envelope', | ||
| }, | ||
| body, | ||
| }); | ||
| } catch (error) { | ||
| debug.error('Sentry tunnel: failed to forward envelope', error); | ||
| return new Response('Failed to forward envelope to Sentry', { status: 500 }); | ||
| } | ||
| } | ||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import { getEnvelopeEndpointWithUrlEncodedAuth } from '../../../src/api'; | ||
| import { makeDsn } from '../../../src/utils/dsn'; | ||
| import { createEnvelope, serializeEnvelope } from '../../../src/utils/envelope'; | ||
| import { handleTunnelRequest } from '../../../src/utils/tunnel'; | ||
|
|
||
| const TEST_DSN = 'https://public@dsn.ingest.sentry.io/1337'; | ||
|
|
||
| function makeEnvelopeRequest(envelopeHeader: Record<string, unknown>): Request { | ||
| const envelope = createEnvelope(envelopeHeader, []); | ||
| const body = serializeEnvelope(envelope); | ||
| return new Request('http://localhost/tunnel', { method: 'POST', body }); | ||
| } | ||
|
|
||
| describe('handleTunnelRequest', () => { | ||
| let fetchMock: ReturnType<typeof vi.fn>; | ||
|
|
||
| beforeEach(() => { | ||
| fetchMock = vi.fn(); | ||
| vi.stubGlobal('fetch', fetchMock); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it('forwards the envelope to Sentry and returns the upstream response', async () => { | ||
| const upstreamResponse = new Response('ok', { status: 200 }); | ||
| fetchMock.mockResolvedValueOnce(upstreamResponse); | ||
|
|
||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({ dsn: TEST_DSN }), | ||
| allowedDsns: [TEST_DSN], | ||
| }); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledOnce(); | ||
| const [url, init] = fetchMock.mock.calls[0]!; | ||
| expect(url).toBe(getEnvelopeEndpointWithUrlEncodedAuth(makeDsn(TEST_DSN)!)); | ||
| expect(init.method).toBe('POST'); | ||
| expect(init.headers).toEqual({ 'Content-Type': 'application/x-sentry-envelope' }); | ||
| expect(init.body).toBeInstanceOf(Uint8Array); | ||
|
|
||
| expect(result).toBe(upstreamResponse); | ||
| }); | ||
|
|
||
| it('returns 500 when allowedDsns is empty', async () => { | ||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({ dsn: TEST_DSN }), | ||
| allowedDsns: [], | ||
| }); | ||
|
|
||
| expect(result).toBeInstanceOf(Response); | ||
| expect(result.status).toBe(500); | ||
| expect(await result.text()).toBe('Tunnel not configured'); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns 400 when the envelope has no DSN in the header', async () => { | ||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({}), | ||
| allowedDsns: [TEST_DSN], | ||
| }); | ||
|
|
||
| expect(result).toBeInstanceOf(Response); | ||
| expect(result.status).toBe(400); | ||
| expect(await result.text()).toBe('Invalid envelope: missing DSN'); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns 400 when the envelope body contains malformed JSON', async () => { | ||
| const result = await handleTunnelRequest({ | ||
| request: new Request('http://localhost/tunnel', { method: 'POST', body: 'not valid envelope data{{{' }), | ||
| allowedDsns: [TEST_DSN], | ||
| }); | ||
|
|
||
| expect(result).toBeInstanceOf(Response); | ||
| expect(result.status).toBe(400); | ||
| expect(await result.text()).toBe('Invalid envelope'); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns 403 when the envelope DSN is not in allowedDsns', async () => { | ||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({ dsn: 'https://other@example.com/9999' }), | ||
| allowedDsns: [TEST_DSN], | ||
| }); | ||
|
|
||
| expect(result).toBeInstanceOf(Response); | ||
| expect(result.status).toBe(403); | ||
| expect(await result.text()).toBe('DSN not allowed'); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns 403 when the DSN string cannot be parsed into components', async () => { | ||
| const malformedDsn = 'not-a-valid-dsn'; | ||
|
|
||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({ dsn: malformedDsn }), | ||
| allowedDsns: [malformedDsn], | ||
| }); | ||
|
|
||
| expect(result).toBeInstanceOf(Response); | ||
| expect(result.status).toBe(403); | ||
| expect(await result.text()).toBe('Invalid DSN'); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('forwards the envelope when multiple DSNs are configured', async () => { | ||
| const otherDsn = 'https://other@example.com/9999'; | ||
| const upstreamResponse = new Response('ok', { status: 200 }); | ||
| fetchMock.mockResolvedValueOnce(upstreamResponse); | ||
|
|
||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({ dsn: TEST_DSN }), | ||
| allowedDsns: [otherDsn, TEST_DSN], | ||
| }); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledOnce(); | ||
| const [url] = fetchMock.mock.calls[0]!; | ||
| expect(url).toBe(getEnvelopeEndpointWithUrlEncodedAuth(makeDsn(TEST_DSN)!)); | ||
| expect(result).toBe(upstreamResponse); | ||
| }); | ||
|
|
||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| it('returns 500 when fetch throws a network error', async () => { | ||
| fetchMock.mockRejectedValueOnce(new Error('Network failure')); | ||
|
|
||
| const result = await handleTunnelRequest({ | ||
| request: makeEnvelopeRequest({ dsn: TEST_DSN }), | ||
| allowedDsns: [TEST_DSN], | ||
| }); | ||
|
|
||
| expect(result).toBeInstanceOf(Response); | ||
| expect(result.status).toBe(500); | ||
| expect(await result.text()).toBe('Failed to forward envelope to Sentry'); | ||
| }); | ||
| }); | ||
nikolovlazar marked this conversation as resolved.
Show resolved
Hide resolved
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. m: This file is still a leftover from the tanstack start changes, correct? Let's remove it before we merge this. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.