Skip to content

Commit 7b122d0

Browse files
authored
fix(nest): keep guards and metadata on router-based @implement routes (#2498)
Backport of #2497 to `1.x`. ## Problem Router-based `@Implement` creates one Nest route method per contract entry. Each route method inherited guards and `@SetMetadata` from the original function through a prototype link, and that link was made while `@Implement` ran. A decorator above `@Implement` that replaces the method moves every decorator above it onto the replacement. Examples are nestjs-otel `@Span()`, typeorm-transactional `@Transactional()` and nestjs-cls `@UseCls()`. The route methods never saw that metadata: ```ts @UseGuards(AuthGuard) // never ran on router routes @roles('admin') // invisible to a class-level RolesGuard @span() @implement(adminRouter) admin() { ... } ``` Requests returned 200 instead of 403, while the same stack on a procedure contract was enforced. A wrapper that returns a new descriptor was also never called on router routes. ## Fix Same approach as #2497: - A microtask runs after all decorators. It links each route method to the final method, `target[propertyKey]`. Route methods also call the final method at request time. - Metadata that exists only on the original function is merged in. Values are combined only for the keys Nest appends to: `__guards__`, `__interceptors__`, `__pipes__`, `__exceptionFilters__` and `__headers__`. For all other keys the outermost value wins, so `['admin']` above a wrapper beats `['user']` below it. ## Differences from #2497 On `1.x`, `@Implement` sets up each child route immediately, not in a microtask as on v2. It adds `UseInterceptors(ImplementInterceptor)` and the route decorators at that point. `extendArrayMetadata` copies the interceptor list it sees at that moment onto the route method. So: - The route method is still linked to the original function right away, then re-linked to the final method in the microtask. Without the early link, the copy would miss interceptors below `@Implement`. - The merge skips keys the route method already has itself. Its interceptor list already includes the original's interceptors. Overwriting it would drop `ImplementInterceptor`, and routes would stop responding through oRPC. - The metadata copy for `(target, propertyKey)` still runs immediately, as before on `1.x`. - The tests use `oc.route({ path })` because `oc.meta(openapi(...))` doesn't exist on `1.x`. They add one 1.x-only case: interceptors below `@Implement` still run, and the route still responds, for each wrapper type. Removing either of the first two changes fails that case. Nothing else covered them. ## Behavior changes - Guards and metadata above a method-replacing decorator now apply to router routes, so requests that were wrongly allowed now get 403. - A wrapper that returns a new descriptor now runs on router routes, so its side effects, such as opening a transaction, start happening. - The final link to the replacement method is made one microtask after the class is defined. ## Known limits - Same as #2497: with two wrappers that don't copy metadata, decorators between them stay invisible. A guard on both sides of a wrapper that doesn't copy metadata runs once. - Not changed here, and already true without a wrapper: on `1.x`, interceptors placed above `@Implement` are ignored on router routes. `@UseInterceptors(X) @implement(router)` never calls `X`. Fixing that means applying the child route decorators in a microtask, as v2 does. ## Tests - New tests in `packages/nest/src/implement.test.ts`. 7 of them fail on the original `1.x` code. - Nest tests pass (43). `pnpm lint` and the type checks pass, apart from two leftover untracked files in my local checkout. - `packages/bun` was not run.
1 parent 6c8f348 commit 7b122d0

2 files changed

Lines changed: 306 additions & 7 deletions

File tree

‎packages/nest/src/implement.test.ts‎

Lines changed: 248 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import type { CanActivate, ExecutionContext } from '@nestjs/common'
1+
import type { CallHandler, CanActivate, ExecutionContext, NestInterceptor } from '@nestjs/common'
22
import type { NodeHttpRequest } from '@orpc/standard-server-node'
33
import type { Request } from 'express'
44
import type { FastifyReply } from 'fastify'
55
import FastifyCookie from '@fastify/cookie'
66
import { HonoAdapter } from '@mnigos/platform-hono'
7-
import { Controller, Req, Res, UseGuards } from '@nestjs/common'
8-
import { REQUEST } from '@nestjs/core'
7+
import { Controller, Req, Res, SetMetadata, UseGuards, UseInterceptors } from '@nestjs/common'
8+
import { Reflector, REQUEST } from '@nestjs/core'
99
import { FastifyAdapter } from '@nestjs/platform-fastify'
1010
import { Test } from '@nestjs/testing'
1111
import { oc, ORPCError } from '@orpc/contract'
@@ -871,5 +871,250 @@ describe('@Implement', async () => {
871871
],
872872
}))
873873
})
874+
875+
describe('@Implement keeps decorators around a method-replacing decorator', () => {
876+
const contract = {
877+
ping: oc.route({ path: '/wrapped/ping' }),
878+
nested: {
879+
pong: oc.route({ path: '/wrapped/pong' }),
880+
},
881+
}
882+
883+
const router = () => ({
884+
ping: implement(contract.ping).handler(() => 'ping'),
885+
nested: {
886+
pong: implement(contract.nested.pong).handler(() => 'pong'),
887+
},
888+
})
889+
890+
const paths = ['/wrapped/ping', '/wrapped/pong']
891+
892+
const wrapperCalled = vi.fn()
893+
894+
const wrapMethod = (original: any, copyMetadata: boolean): any => {
895+
const wrapped = function (this: unknown, ...args: unknown[]) {
896+
wrapperCalled()
897+
return original.apply(this, args)
898+
}
899+
900+
if (copyMetadata) {
901+
for (const key of Reflect.getOwnMetadataKeys(original)) {
902+
Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, original), wrapped)
903+
}
904+
}
905+
906+
return wrapped
907+
}
908+
909+
const InPlaceWrap = (): MethodDecorator => (_target, _key, descriptor) => {
910+
descriptor.value = wrapMethod(descriptor.value, true)
911+
}
912+
913+
const NewDescriptorWrap = (): MethodDecorator => (_target, _key, descriptor) => {
914+
return { ...descriptor, value: wrapMethod(descriptor.value, true) }
915+
}
916+
917+
const NonCopyingWrap = (): MethodDecorator => (_target, _key, descriptor) => {
918+
descriptor.value = wrapMethod(descriptor.value, false)
919+
}
920+
921+
const guardCalls = vi.fn()
922+
923+
const recordingGuard = (name: string): CanActivate => ({
924+
canActivate() {
925+
guardCalls(name)
926+
return true
927+
},
928+
})
929+
930+
class DenyGuard implements CanActivate {
931+
canActivate() {
932+
return false
933+
}
934+
}
935+
936+
const interceptorCalls = vi.fn()
937+
938+
class RecordingInterceptor implements NestInterceptor {
939+
intercept(_ctx: ExecutionContext, next: CallHandler) {
940+
interceptorCalls()
941+
return next.handle()
942+
}
943+
}
944+
945+
const handlerMeta = vi.fn()
946+
947+
class MetaGuard implements CanActivate {
948+
canActivate(ctx: ExecutionContext) {
949+
const reflector = new Reflector()
950+
handlerMeta(
951+
reflector.get('above', ctx.getHandler()),
952+
reflector.get('below', ctx.getHandler()),
953+
reflector.get('roles', ctx.getHandler()),
954+
reflector.get('cleared', ctx.getHandler()),
955+
)
956+
return true
957+
}
958+
}
959+
960+
const createServer = async (controller: new () => unknown) => {
961+
const moduleRef = await Test.createTestingModule({
962+
controllers: [controller],
963+
}).compile()
964+
965+
const app = moduleRef.createNestApplication()
966+
await app.init()
967+
968+
return app.getHttpServer()
969+
}
970+
971+
describe.each([
972+
['a wrapper mutating the descriptor', InPlaceWrap],
973+
['a wrapper returning a new descriptor', NewDescriptorWrap],
974+
['a wrapper that does not copy metadata', NonCopyingWrap],
975+
] as const)('with %s', (_, Wrap) => {
976+
it('runs guards from both sides of the wrapper in decorator order', async () => {
977+
@Controller()
978+
class ImplController {
979+
@UseGuards(recordingGuard('above'))
980+
@Wrap()
981+
@UseGuards(recordingGuard('below'))
982+
@Implement(contract)
983+
router() {
984+
return router()
985+
}
986+
}
987+
988+
const server = await createServer(ImplController)
989+
990+
for (const path of paths) {
991+
guardCalls.mockClear()
992+
993+
expect((await supertest(server).post(path)).status).toBe(200)
994+
expect(guardCalls.mock.calls).toEqual([['below'], ['above']])
995+
}
996+
})
997+
998+
it('exposes @SetMetadata from both sides of the wrapper and lets the outermost value win', async () => {
999+
@Controller()
1000+
@UseGuards(MetaGuard)
1001+
class ImplController {
1002+
@SetMetadata('above', 'above-value')
1003+
@SetMetadata('roles', ['admin'])
1004+
@SetMetadata('cleared', undefined)
1005+
@Wrap()
1006+
@SetMetadata('cleared', 'below-value')
1007+
@SetMetadata('roles', ['user'])
1008+
@SetMetadata('below', 'below-value')
1009+
@Implement(contract)
1010+
router() {
1011+
return router()
1012+
}
1013+
}
1014+
1015+
const server = await createServer(ImplController)
1016+
1017+
for (const path of paths) {
1018+
handlerMeta.mockClear()
1019+
1020+
expect((await supertest(server).post(path)).status).toBe(200)
1021+
expect(handlerMeta).toHaveBeenCalledExactlyOnceWith(
1022+
'above-value',
1023+
'below-value',
1024+
['admin'],
1025+
undefined,
1026+
)
1027+
}
1028+
})
1029+
1030+
it('keeps guards when their metadata key is set to undefined on the other side of the wrapper', async () => {
1031+
@Controller()
1032+
class ImplController {
1033+
@SetMetadata('__guards__', undefined)
1034+
@Wrap()
1035+
@UseGuards(recordingGuard('below'))
1036+
@Implement(contract)
1037+
router() {
1038+
return router()
1039+
}
1040+
}
1041+
1042+
const server = await createServer(ImplController)
1043+
1044+
for (const path of paths) {
1045+
guardCalls.mockClear()
1046+
1047+
expect((await supertest(server).post(path)).status).toBe(200)
1048+
expect(guardCalls.mock.calls).toEqual([['below']])
1049+
}
1050+
})
1051+
1052+
it('calls the wrapper and returns the procedure output on every route', async () => {
1053+
@Controller()
1054+
class ImplController {
1055+
@Wrap()
1056+
@Implement(contract)
1057+
router() {
1058+
return router()
1059+
}
1060+
}
1061+
1062+
const server = await createServer(ImplController)
1063+
1064+
const pingRes = await supertest(server).post('/wrapped/ping')
1065+
expect(pingRes.status).toBe(200)
1066+
expect(pingRes.body).toEqual('ping')
1067+
expect(wrapperCalled).toHaveBeenCalledTimes(1)
1068+
1069+
const pongRes = await supertest(server).post('/wrapped/pong')
1070+
expect(pongRes.status).toBe(200)
1071+
expect(pongRes.body).toEqual('pong')
1072+
expect(wrapperCalled).toHaveBeenCalledTimes(2)
1073+
})
1074+
1075+
it('runs interceptors below @Implement and still responds through @Implement', async () => {
1076+
@Controller()
1077+
class ImplController {
1078+
@Wrap()
1079+
@Implement(contract)
1080+
@UseInterceptors(RecordingInterceptor)
1081+
router() {
1082+
return router()
1083+
}
1084+
}
1085+
1086+
const server = await createServer(ImplController)
1087+
1088+
const pingRes = await supertest(server).post('/wrapped/ping')
1089+
expect(pingRes.status).toBe(200)
1090+
expect(pingRes.body).toEqual('ping')
1091+
expect(interceptorCalls).toHaveBeenCalledTimes(1)
1092+
1093+
const pongRes = await supertest(server).post('/wrapped/pong')
1094+
expect(pongRes.status).toBe(200)
1095+
expect(pongRes.body).toEqual('pong')
1096+
expect(interceptorCalls).toHaveBeenCalledTimes(2)
1097+
})
1098+
})
1099+
1100+
it.each([
1101+
['a wrapper mutating the descriptor', InPlaceWrap],
1102+
['a wrapper returning a new descriptor', NewDescriptorWrap],
1103+
] as const)('procedure-based implementation applies a guard above %s', async (_, Wrap) => {
1104+
@Controller()
1105+
class ImplController {
1106+
@UseGuards(DenyGuard)
1107+
@Wrap()
1108+
@Implement(contract.ping)
1109+
ping() {
1110+
return router().ping
1111+
}
1112+
}
1113+
1114+
const server = await createServer(ImplController)
1115+
1116+
expect((await supertest(server).post('/wrapped/ping')).status).toBe(403)
1117+
})
1118+
})
8741119
})
8751120
})

‎packages/nest/src/implement.ts‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/com
22
import type { ContractRouter } from '@orpc/contract'
33
import type { Router } from '@orpc/server'
44
import type { StandardParams } from '@orpc/server/standard'
5-
import type { Promisable } from '@orpc/shared'
5+
import type { AnyFunction, Promisable } from '@orpc/shared'
66
import type { Request, Response } from 'express'
77
import type { FastifyReply, FastifyRequest } from 'fastify'
88
import type { Observable } from 'rxjs'
@@ -38,6 +38,15 @@ const MethodDecoratorMap = {
3838
OPTIONS: Options,
3939
}
4040

41+
// Nest appends to these keys across decorators, while any other metadata is replaced
42+
const ACCUMULATED_METADATA_KEYS = new Set([
43+
'__guards__',
44+
'__interceptors__',
45+
'__pipes__',
46+
'__exceptionFilters__',
47+
'__headers__',
48+
])
49+
4150
/**
4251
* Decorator in controller handler to implement a oRPC contract.
4352
*
@@ -72,6 +81,8 @@ export function Implement<T extends ContractRouter<any>>(
7281
}
7382

7483
return (target, propertyKey, descriptor) => {
84+
const originalMethod = descriptor.value!
85+
7586
for (const key in contract) {
7687
let methodName = `${propertyKey}_${key}`
7788

@@ -81,11 +92,18 @@ export function Implement<T extends ContractRouter<any>>(
8192
}
8293

8394
target[methodName] = async function (...args: any[]) {
84-
const router = await descriptor.value!.apply(this, args)
95+
const router = await target[propertyKey].apply(this, args)
8596
return getRouter(router, [key])
8697
}
8798

88-
Object.setPrototypeOf(target[methodName], descriptor.value!)
99+
const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName)!
100+
101+
// the child is implemented synchronously below and snapshots interceptors through this link
102+
Object.setPrototypeOf(childDescriptor.value, originalMethod)
103+
104+
queueMicrotask(() => {
105+
inheritFunctionMetadata(childDescriptor.value, originalMethod, target[propertyKey])
106+
})
89107

90108
for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
91109
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target, propertyKey), target, methodName)
@@ -95,7 +113,43 @@ export function Implement<T extends ContractRouter<any>>(
95113
Reflect.defineMetadata(p, Reflect.getOwnMetadata(p, target.constructor, propertyKey), target.constructor, methodName)
96114
}
97115

98-
Implement(get(contract, [key]) as any)(target, methodName, Object.getOwnPropertyDescriptor(target, methodName)!)
116+
Implement(get(contract, [key]) as any)(target, methodName, childDescriptor)
117+
}
118+
}
119+
}
120+
121+
function inheritFunctionMetadata(
122+
method: AnyFunction,
123+
originalMethod: AnyFunction,
124+
finalMethod: AnyFunction,
125+
): void {
126+
Object.setPrototypeOf(method, finalMethod)
127+
128+
if (finalMethod === originalMethod) {
129+
return
130+
}
131+
132+
// a replacement that does not copy metadata leaves it only on the original function
133+
for (const key of Reflect.getMetadataKeys(originalMethod)) {
134+
// own keys are the child's route decorators plus `__interceptors__`, snapshotted through the
135+
// synchronous link: it holds the interceptors below @Implement, but not the ones above it
136+
if (Reflect.hasOwnMetadata(key, method)) {
137+
continue
138+
}
139+
140+
const originalValue = Reflect.getMetadata(key, originalMethod)
141+
142+
if (!Reflect.hasMetadata(key, finalMethod)) {
143+
Reflect.defineMetadata(key, originalValue, method)
144+
}
145+
else if (ACCUMULATED_METADATA_KEYS.has(key)) {
146+
const originalItems: unknown[] = toArray(originalValue)
147+
const finalItems: unknown[] = toArray(Reflect.getMetadata(key, finalMethod))
148+
Reflect.defineMetadata(
149+
key,
150+
[...originalItems.filter(item => !finalItems.includes(item)), ...finalItems],
151+
method,
152+
)
99153
}
100154
}
101155
}

0 commit comments

Comments
 (0)