Skip to content

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

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

Merged
merged 6 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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,8 +8,15 @@ 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 type { CallHandler, CatchTarget, InjectableTarget, MinimalNestJsExecutionContext, Observable } from './types';
import { getMiddlewareSpanOptions, getNextProxy, instrumentObservable, isPatched } from './helpers';
import type {
CallHandler,
CatchTarget,
InjectableTarget,
MinimalNestJsExecutionContext,
NextFunction,
Observable,
} from './types';

const supportedVersions = ['>=8.0.0 <11'];

Expand Down Expand Up @@ -103,21 +110,16 @@ export class SentryNestInstrumentation extends InstrumentationBase {
const [req, res, next, ...args] = argsUse;
const prevSpan = getActiveSpan();
Copy link
Contributor

Choose a reason for hiding this comment

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

We should probably also move this line below all the guarding.


return startSpanManual(getMiddlewareSpanOptions(target), (span: Span) => {
const nextProxy = 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);
}
},
});
// Check that we can reasonably assume that the target is a middleware.
// Without this guard, instrumentation will fail if a function named 'use' on a service, which is
// decorated with @Injectable, is called.
if (!(next satisfies NextFunction)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Just fyi, satisfies is a type annotation and has no effect during runtime. What was your intention with this if statement?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

To early-return before we try to proxy next. Thanks for the hint, interesting that it does seem to work nevertheless.

I added tests first to verify the behavior, then introduced this check and that fixed it

Copy link
Contributor

Choose a reason for hiding this comment

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

let's check for truthyness of next and also that typeof next === 'function', and I would also check for the existence of the req, and res args.

return originalUse.apply(thisArgUse, argsUse);
}

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 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