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 4 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 @@ -100,24 +100,24 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.use = new Proxy(target.prototype.use, {
apply: (originalUse, thisArgUse, argsUse) => {
// Middlewares have a request, response and next argument.
if (argsUse.length < 3) {
return originalUse.apply(thisArgUse, argsUse);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

This check is technically redundant with the assertions we have below.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is it? What if the function has 0 arguments?

Copy link
Contributor

Choose a reason for hiding this comment

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

Then an empty array will be passed to argsUse and all the arguments we check down below will be falsy (or rather undefined).


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 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')) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if (!req || !res || !next || !(typeof next === 'function')) {
if (!req || !res || !next || typeof next !== 'function') {

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 All @@ -133,6 +133,17 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.canActivate = new Proxy(target.prototype.canActivate, {
apply: (originalCanActivate, thisArgCanActivate, argsCanActivate) => {
// Guards have a context argument.
if (argsCanActivate.length == 0) {
return originalCanActivate.apply(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 +159,18 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.transform = new Proxy(target.prototype.transform, {
apply: (originalTransform, thisArgTransform, argsTransform) => {
// Pipes have a value and metadata argument.
if (argsTransform.length < 2) {
return originalTransform.apply(thisArgTransform, argsTransform);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

This check is technically redundant with the assertions we have below.


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 @@ -163,12 +186,22 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.intercept = new Proxy(target.prototype.intercept, {
apply: (originalIntercept, thisArgIntercept, argsIntercept) => {
// Interceptors have a context and next argument.
if (argsIntercept.length < 2) {
return originalIntercept.apply(thisArgIntercept, argsIntercept);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

This check is technically redundant with the assertions we have below.


const context: MinimalNestJsExecutionContext = argsIntercept[0];
const next: CallHandler = argsIntercept[1];

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')) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if (!context || !next || !(typeof next.handle === 'function')) {
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 +296,17 @@ export class SentryNestInstrumentation extends InstrumentationBase {

target.prototype.catch = new Proxy(target.prototype.catch, {
apply: (originalCatch, thisArgCatch, argsCatch) => {
if (argsCatch.length < 2) {
return originalCatch.apply(thisArgCatch, argsCatch);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

This check is technically redundant with the assertions we have below.


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