Skip to content
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

fix(nestjs): Check arguments before instrumenting with @Injectable #13544

Merged
merged 6 commits into from
Sep 2, 2024
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 @@ -96,4 +96,24 @@ export class AppController {
async exampleExceptionLocalFilter() {
throw new ExampleExceptionLocalFilter();
}

@Get('test-service-use')
testServiceWithUseMethod() {
return this.appService.use();
}

@Get('test-service-transform')
testServiceWithTransform() {
return this.appService.transform();
}

@Get('test-service-intercept')
testServiceWithIntercept() {
return this.appService.intercept();
}

@Get('test-service-canActivate')
testServiceWithCanActivate() {
return this.appService.canActivate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,20 @@ export class AppService {
async killTestCron() {
this.schedulerRegistry.deleteCronJob('test-cron-job');
}

use() {
console.log('Test use!');
}

transform() {
console.log('Test transform!');
}

intercept() {
console.log('Test intercept!');
}

canActivate() {
console.log('Test canActivate!');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -707,3 +707,23 @@ test('API route transaction includes exactly one nest async interceptor span aft
// 'Interceptor - After Route' is NOT the parent of 'test-controller-span'
expect(testControllerSpan.parent_span_id).not.toBe(exampleInterceptorSpanAfterRouteId);
});

test('Calling use method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-use`);
expect(response.status).toBe(200);
});

test('Calling transform method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-transform`);
expect(response.status).toBe(200);
});

test('Calling intercept method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-intercept`);
expect(response.status).toBe(200);
});

test('Calling canActivate method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-canActivate`);
expect(response.status).toBe(200);
});
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,24 @@ export class AppController {
async flush() {
await flush();
}

@Get('test-service-use')
testServiceWithUseMethod() {
return this.appService.use();
}

@Get('test-service-transform')
testServiceWithTransform() {
return this.appService.transform();
}

@Get('test-service-intercept')
testServiceWithIntercept() {
return this.appService.intercept();
}

@Get('test-service-canActivate')
testServiceWithCanActivate() {
return this.appService.canActivate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,20 @@ export class AppService {
async killTestCron() {
this.schedulerRegistry.deleteCronJob('test-cron-job');
}

use() {
console.log('Test use!');
}

transform() {
console.log('Test transform!');
}

intercept() {
console.log('Test intercept!');
}

canActivate() {
console.log('Test canActivate!');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -705,3 +705,23 @@ test('API route transaction includes exactly one nest async interceptor span aft
// 'Interceptor - After Route' is NOT the parent of 'test-controller-span'
expect(testControllerSpan.parent_span_id).not.toBe(exampleInterceptorSpanAfterRouteId);
});

test('Calling use method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-use`);
expect(response.status).toBe(200);
});

test('Calling transform method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-transform`);
expect(response.status).toBe(200);
});

test('Calling intercept method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-intercept`);
expect(response.status).toBe(200);
});

test('Calling canActivate method on service with Injectable decorator returns 200', async ({ baseURL }) => {
const response = await fetch(`${baseURL}/test-service-canActivate`);
expect(response.status).toBe(200);
});
21 changes: 20 additions & 1 deletion packages/node/src/integrations/tracing/nest/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, withActiveSpan } from '@sentry/core';
import type { Span } from '@sentry/types';
import { addNonEnumerableProperty } from '@sentry/utils';
import type { CatchTarget, InjectableTarget, Observable, Subscription } from './types';
import type { CatchTarget, InjectableTarget, NextFunction, Observable, Subscription } from './types';

const sentryPatched = 'sentryPatched';

Expand Down Expand Up @@ -53,3 +53,22 @@ export function instrumentObservable(observable: Observable<unknown>, activeSpan
});
}
}

/**
* Proxies the next() call in a nestjs middleware to end the span when it is called.
*/
export function getNextProxy(next: NextFunction, span: Span, prevSpan: undefined | Span): NextFunction {
return new Proxy(next, {
apply: (originalNext, thisArgNext, argsNext) => {
span.end();

if (prevSpan) {
return withActiveSpan(prevSpan, () => {
return Reflect.apply(originalNext, thisArgNext, argsNext);
});
} else {
return Reflect.apply(originalNext, thisArgNext, argsNext);
}
},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import { getActiveSpan, startInactiveSpan, startSpan, startSpanManual, withActiveSpan } from '@sentry/core';
import type { Span } from '@sentry/types';
import { SDK_VERSION, addNonEnumerableProperty, isThenable } from '@sentry/utils';
import { getMiddlewareSpanOptions, instrumentObservable, isPatched } from './helpers';
import { getMiddlewareSpanOptions, getNextProxy, instrumentObservable, isPatched } from './helpers';
import type { CallHandler, CatchTarget, InjectableTarget, MinimalNestJsExecutionContext, Observable } from './types';

const supportedVersions = ['>=8.0.0 <11'];
Expand Down Expand Up @@ -101,23 +101,19 @@ export class SentryNestInstrumentation extends InstrumentationBase {
target.prototype.use = new Proxy(target.prototype.use, {
apply: (originalUse, thisArgUse, argsUse) => {
const [req, res, next, ...args] = argsUse;
const prevSpan = getActiveSpan();

return startSpanManual(getMiddlewareSpanOptions(target), (span: Span) => {
const nextProxy = new Proxy(next, {
apply: (originalNext, thisArgNext, argsNext) => {
span.end();
// Check that we can reasonably assume that the target is a middleware.
// Without these guards, instrumentation will fail if a function named 'use' on a service, which is
// decorated with @Injectable, is called.
if (!req || !res || !next || typeof next !== 'function') {
return originalUse.apply(thisArgUse, argsUse);
}

if (prevSpan) {
return withActiveSpan(prevSpan, () => {
return Reflect.apply(originalNext, thisArgNext, argsNext);
});
} else {
return Reflect.apply(originalNext, thisArgNext, argsNext);
}
},
});
const prevSpan = getActiveSpan();

return startSpanManual(getMiddlewareSpanOptions(target), (span: Span) => {
// proxy next to end span on call
const nextProxy = getNextProxy(next, span, prevSpan);
return originalUse.apply(thisArgUse, [req, res, nextProxy, args]);
});
},
Expand All @@ -133,6 +129,12 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.canActivate = new Proxy(target.prototype.canActivate, {
apply: (originalCanActivate, thisArgCanActivate, argsCanActivate) => {
const context: MinimalNestJsExecutionContext = argsCanActivate[0];

if (!context) {
return originalCanActivate.apply(thisArgCanActivate, argsCanActivate);
}

return startSpan(getMiddlewareSpanOptions(target), () => {
return originalCanActivate.apply(thisArgCanActivate, argsCanActivate);
});
Expand All @@ -148,6 +150,13 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.transform = new Proxy(target.prototype.transform, {
apply: (originalTransform, thisArgTransform, argsTransform) => {
const value = argsTransform[0];
const metadata = argsTransform[1];

if (!value || !metadata) {
return originalTransform.apply(thisArgTransform, argsTransform);
}

return startSpan(getMiddlewareSpanOptions(target), () => {
return originalTransform.apply(thisArgTransform, argsTransform);
});
Expand All @@ -169,6 +178,11 @@ export class SentryNestInstrumentation extends InstrumentationBase {
const parentSpan = getActiveSpan();
let afterSpan: Span;

// Check that we can reasonably assume that the target is an interceptor.
if (!context || !next || typeof next.handle !== 'function') {
return originalIntercept.apply(thisArgIntercept, argsIntercept);
}

return startSpanManual(getMiddlewareSpanOptions(target), (beforeSpan: Span) => {
// eslint-disable-next-line @typescript-eslint/unbound-method
next.handle = new Proxy(next.handle, {
Expand Down Expand Up @@ -263,6 +277,13 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.catch = new Proxy(target.prototype.catch, {
apply: (originalCatch, thisArgCatch, argsCatch) => {
const exception = argsCatch[0];
const host = argsCatch[1];

if (!exception || !host) {
return originalCatch.apply(thisArgCatch, argsCatch);
}

return startSpan(getMiddlewareSpanOptions(target), () => {
return originalCatch.apply(thisArgCatch, argsCatch);
});
Expand Down
5 changes: 5 additions & 0 deletions packages/node/src/integrations/tracing/nest/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,8 @@ export interface CatchTarget {
catch?: (...args: any[]) => any;
};
}

/**
* Represents an express NextFunction.
*/
export type NextFunction = (err?: any) => void;
Loading