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
Original file line number Diff line number Diff line change
Expand Up @@ -106,5 +106,23 @@ IMPORT_SURFACES.forEach(({ name, apiPrefix }) => {
}),
);
});

test('filters a secret of the query string in the error event', async ({ request }) => {
const errorPromise = waitForError('nuxt-4', errorEvent => {
return (
errorEvent?.exception?.values?.[0]?.value === 'Nuxt 4 Server error' &&
errorEvent.request?.url?.includes(`${apiPrefix}/server-error`) === true &&
errorEvent.request?.query_string?.startsWith('include=profile') === true
);
});

await request.get(`${apiPrefix}/server-error?include=profile&auth=very-secret`);

const error = await errorPromise;

expect(error.transaction).toBe(`GET ${apiPrefix}/server-error`);
expect(error.contexts?.nuxt?.path).toBe(`${apiPrefix}/server-error?include=profile&auth=[Filtered]`);
expect(JSON.stringify(error)).not.toContain('very-secret');
});
});
});
23 changes: 13 additions & 10 deletions packages/nuxt/src/runtime/hooks/captureErrorHook.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { captureException, getClient, getCurrentScope } from '@sentry/core';
import { captureException, getClient, stripUrlQueryAndFragment, withScope } from '@sentry/core';
import { flushIfServerless } from '@sentry/core/server';
import type { CapturedErrorContext } from 'nitropack/types';
import { extractErrorContext, getEventRequestInfo } from '../utils';
Expand Down Expand Up @@ -59,17 +59,20 @@ export async function sentryCaptureErrorHook(error: Error, errorContext: Capture
}
}

const { method = '', path } = getEventRequestInfo(errorContext.event);

if (path) {
getCurrentScope().setTransactionName(`${method} ${path}`);
}

const { method = '', path = '' } = getEventRequestInfo(errorContext.event);
const pathname = stripUrlQueryAndFragment(path);
const structuredContext = extractErrorContext(errorContext);

captureException(error, {
captureContext: { contexts: { nuxt: structuredContext } },
mechanism: { handled: false, type: 'auto.function.nuxt.nitro' },
// On the current scope, the name would also apply to every later event of that scope.
withScope(scope => {
if (pathname) {
scope.setTransactionName(`${method} ${pathname}`);
}

captureException(error, {
captureContext: { contexts: { nuxt: structuredContext } },
mechanism: { handled: false, type: 'auto.function.nuxt.nitro' },
});
});

await flushIfServerless();
Expand Down
5 changes: 3 additions & 2 deletions packages/nuxt/src/runtime/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ClientOptions, Context, SerializedTraceData } from '@sentry/core';
import { captureException, debug, getClient, getTraceMetaTags, isObjectLike } from '@sentry/core';
import { captureException, debug, filterCollectedUrl, getClient, getTraceMetaTags, isObjectLike } from '@sentry/core';
import type { CapturedErrorContext } from 'nitropack/types';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import type { ComponentPublicInstance } from 'vue';
Expand Down Expand Up @@ -39,7 +39,8 @@ export function extractErrorContext(errorContext: CapturedErrorContext | undefin
if (errorContext.event) {
const { method, path } = getEventRequestInfo(errorContext.event);
ctx.method = method;
ctx.path = path;
// The h3 v1 path has the query string.
ctx.path = filterCollectedUrl(path);
}

if (Array.isArray(errorContext.tags)) {
Expand Down
48 changes: 41 additions & 7 deletions packages/nuxt/test/runtime/hooks/captureErrorHook.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,12 @@ import type { CapturedErrorContext } from 'nitropack/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { sentryCaptureErrorHook } from '../../../src/runtime/hooks/captureErrorHook';

const setTransactionName = vi.fn();

vi.mock('@sentry/core', async importOriginal => {
const mod = await importOriginal();
return {
...(mod as any),
captureException: vi.fn(),
getClient: vi.fn(),
getCurrentScope: vi.fn(() => ({ setTransactionName })),
};
});

Expand All @@ -41,12 +38,15 @@ const h3Majors = [
error.statusCode = statusCode;
return error;
},
event: { method: 'GET', path: '/test-path' },
event: { method: 'GET', path: '/users/42?include=profile' },
},
{
name: 'h3 v2 (Nitro v3)',
httpError: (message: string, statusCode: number): Error => new HTTPError({ message, status: statusCode }),
event: { req: new Request('http://localhost/test-path'), url: new URL('http://localhost/test-path') },
event: {
req: new Request('http://localhost/users/42?include=profile'),
url: new URL('http://localhost/users/42?include=profile'),
},
},
];

Expand All @@ -56,6 +56,16 @@ function withCause(error: Error, cause: unknown): Error {
return Object.defineProperty(error, 'cause', { value: cause, configurable: true });
}

/** The transaction name that the next captured event gets from the scope that is current during the capture. */
function recordTransactionNameOfNextCapture(): Array<string | undefined> {
const transactionNames: Array<string | undefined> = [];
vi.mocked(SentryCore.captureException).mockImplementationOnce(() => {
transactionNames.push(SentryCore.getCurrentScope().getScopeData().transactionName);
return '4c79f60c11214eb38604f4ae0781bfb2';
});
return transactionNames;
}

describe.each(h3Majors)('sentryCaptureErrorHook - $name', ({ httpError, event }) => {
const mockErrorContext = { event } as unknown as CapturedErrorContext;

Expand All @@ -80,10 +90,18 @@ describe.each(h3Majors)('sentryCaptureErrorHook - $name', ({ httpError, event })
);
});

it('sets the transaction name from the request method and path', async () => {
it('names the captured event after the request method and path, without the query string', async () => {
const transactionNames = recordTransactionNameOfNextCapture();

await sentryCaptureErrorHook(new Error('Test error'), mockErrorContext);

expect(transactionNames).toEqual(['GET /users/42']);
});

it('leaves the transaction name of the current scope unchanged', async () => {
await sentryCaptureErrorHook(new Error('Test error'), mockErrorContext);

expect(setTransactionName).toHaveBeenCalledWith('GET /test-path');
expect(SentryCore.getCurrentScope().getScopeData().transactionName).toBeUndefined();
});

it('should skip HTTP errors with 4xx status codes', async () => {
Expand Down Expand Up @@ -174,6 +192,22 @@ describe.each(h3Majors)('sentryCaptureErrorHook - $name', ({ httpError, event })
});
});

describe('sentryCaptureErrorHook - request without a pathname', () => {
beforeEach(() => {
vi.clearAllMocks();
(SentryCore.getClient as any).mockReturnValue({ getOptions: () => ({}) });
});

it('does not name the event when the h3 v1 path has only a query string', async () => {
const transactionNames = recordTransactionNameOfNextCapture();
const errorContext = { event: { method: 'GET', path: '?page=2' } } as unknown as CapturedErrorContext;

await sentryCaptureErrorHook(new Error('Test error'), errorContext);

expect(transactionNames).toEqual([undefined]);
});
});

describe('sentryCaptureErrorHook - errors that only look like h3 errors', () => {
beforeEach(() => {
vi.clearAllMocks();
Expand Down
12 changes: 12 additions & 0 deletions packages/nuxt/test/runtime/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { captureException, getClient } from '@sentry/core';
import type { CapturedErrorContext } from 'nitropack/types';
import { afterEach, beforeEach, describe, expect, it, type Mock, test, vi } from 'vitest';
import type { ComponentPublicInstance } from 'vue';
import { extractErrorContext, reportNuxtError } from '../../src/runtime/utils';
Expand Down Expand Up @@ -37,6 +38,17 @@ describe('extractErrorContext', () => {
expect(extractErrorContext(partialContext)).toEqual({ path: '/test' });
});

it('filters sensitive query params in the path of an h3 v1 (Nitro v2) event', () => {
const context = {
event: { method: 'GET', path: '/users/42?include=profile&token=abc123' },
} as unknown as CapturedErrorContext;

expect(extractErrorContext(context)).toEqual({
method: 'GET',
path: '/users/42?include=profile&token=[Filtered]',
});
});

it('reads method and path from an h3 v2 (Nitro v3) event, which has no `method`/`path` getters', () => {
const context = {
event: {
Expand Down
Loading