Skip to content

Commit be14d05

Browse files
authored
fix(nest): keep guards and metadata on router-based @implement routes (#2497)
## Problem Router-based `@Implement` creates one Nest route method per contract entry. Those methods got their guards, interceptors and `@SetMetadata` by inheriting from the decorated function, and the link was made while `@Implement` ran. A decorator above `@Implement` that replaces the method, such as nestjs-otel `@Span()`, typeorm-transactional `@Transactional()` or nestjs-cls `@UseCls()`, moves every decorator above it onto the replacement. 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. The same stack on a procedure contract was enforced. A wrapper that returns a new descriptor, instead of mutating the one it receives, was also never called on router routes. This contradicts the docs, which say all decorators on the original method are reflected on the generated methods. ## Fix - Link each route method to the final method (`target[propertyKey]`) inside the existing microtask, after all decorators have run, and call the final method at request time. - Wrappers that don't copy metadata leave the decorators below them only on the original function. Linking to the wrapper alone would drop them, including `ImplementInterceptor`, and turn `@Wrap() @UseGuards(G) @implement(router)`, which is safe today, into a bypass. So metadata found only on the original is merged in. - Values are combined only for the keys Nest appends to (`__guards__`, `__interceptors__`, `__pipes__`, `__exceptionFilters__`, `__headers__`). For all other keys the outermost value wins, matching Nest without a wrapper. Merging every array would turn `@SetMetadata('roles', ['admin'])` above a wrapper and `['user']` below it into `['user', 'admin']`. ## 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. Its side effects, such as opening a transaction, start happening. ## Known limits - With two wrappers that don't copy metadata, decorators between them are still invisible, because only the original and final functions can be observed. - A guard applied on both sides of a wrapper that doesn't copy metadata runs once instead of twice. - The five key names are Nest internals written as strings. I didn't confirm an import path for them on Nest 11, which the peer range still allows. ## Tests New tests in `packages/nest/src/implement.test.ts` cover wrappers that mutate the descriptor, return a new descriptor, or don't copy metadata. They check guard order on both sides, `@SetMetadata` on both sides with the outer value winning, that the wrapper is called with correct responses, and procedure-based `@Implement`. Flat and nested router routes are both covered. They fail on the original code, on a version that merges every array, and on a version without the merge. - `pnpm format` and `pnpm check` pass. - `pnpm exec vitest run` passes except `openapi-inference` "names the nearest tsconfig when it does not include the file, and why", which also fails on `main` on macOS (`/var` vs `/private/var` temp paths). - `packages/bun` and the `packages/cloudflare` workerd suite were not run.
1 parent 33f0782 commit be14d05

2 files changed

Lines changed: 257 additions & 5 deletions

File tree

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

Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1603,6 +1603,218 @@ describe('compatibility', () => {
16031603
})
16041604
})
16051605

1606+
describe('@Implement keeps decorators around a method-replacing decorator', () => {
1607+
const contract = {
1608+
ping: oc.meta(openapi({ path: '/wrapped/ping' })),
1609+
nested: {
1610+
pong: oc.meta(openapi({ path: '/wrapped/pong' })),
1611+
},
1612+
}
1613+
1614+
const router = () => ({
1615+
ping: implement(contract.ping).handler(() => 'ping'),
1616+
nested: {
1617+
pong: implement(contract.nested.pong).handler(() => 'pong'),
1618+
},
1619+
})
1620+
1621+
const paths = ['/wrapped/ping', '/wrapped/pong']
1622+
1623+
const wrapperCalled = vi.fn()
1624+
1625+
const wrapMethod = (original: any, copyMetadata: boolean): any => {
1626+
const wrapped = function (this: unknown, ...args: unknown[]) {
1627+
wrapperCalled()
1628+
return original.apply(this, args)
1629+
}
1630+
1631+
if (copyMetadata) {
1632+
for (const key of Reflect.getOwnMetadataKeys(original)) {
1633+
Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, original), wrapped)
1634+
}
1635+
}
1636+
1637+
return wrapped
1638+
}
1639+
1640+
const InPlaceWrap = (): MethodDecorator => (_target, _key, descriptor) => {
1641+
descriptor.value = wrapMethod(descriptor.value, true)
1642+
}
1643+
1644+
const NewDescriptorWrap = (): MethodDecorator => (_target, _key, descriptor) => {
1645+
return { ...descriptor, value: wrapMethod(descriptor.value, true) }
1646+
}
1647+
1648+
const NonCopyingWrap = (): MethodDecorator => (_target, _key, descriptor) => {
1649+
descriptor.value = wrapMethod(descriptor.value, false)
1650+
}
1651+
1652+
const guardCalls = vi.fn()
1653+
1654+
const recordingGuard = (name: string): CanActivate => ({
1655+
canActivate() {
1656+
guardCalls(name)
1657+
return true
1658+
},
1659+
})
1660+
1661+
class DenyGuard implements CanActivate {
1662+
canActivate() {
1663+
return false
1664+
}
1665+
}
1666+
1667+
const handlerMeta = vi.fn()
1668+
1669+
class MetaGuard implements CanActivate {
1670+
canActivate(ctx: ExecutionContext) {
1671+
const reflector = new Reflector()
1672+
handlerMeta(
1673+
reflector.get('above', ctx.getHandler()),
1674+
reflector.get('below', ctx.getHandler()),
1675+
reflector.get('roles', ctx.getHandler()),
1676+
reflector.get('cleared', ctx.getHandler()),
1677+
)
1678+
return true
1679+
}
1680+
}
1681+
1682+
const createServer = async (controller: new () => unknown) => {
1683+
const moduleRef = await Test.createTestingModule({
1684+
controllers: [controller],
1685+
}).compile()
1686+
1687+
const app = moduleRef.createNestApplication()
1688+
await app.init()
1689+
1690+
return app.getHttpServer()
1691+
}
1692+
1693+
describe.each([
1694+
['a wrapper mutating the descriptor', InPlaceWrap],
1695+
['a wrapper returning a new descriptor', NewDescriptorWrap],
1696+
['a wrapper that does not copy metadata', NonCopyingWrap],
1697+
] as const)('with %s', (_, Wrap) => {
1698+
it('runs guards from both sides of the wrapper in decorator order', async () => {
1699+
@Controller()
1700+
class ImplController {
1701+
@UseGuards(recordingGuard('above'))
1702+
@Wrap()
1703+
@UseGuards(recordingGuard('below'))
1704+
@Implement(contract)
1705+
router() {
1706+
return router()
1707+
}
1708+
}
1709+
1710+
const server = await createServer(ImplController)
1711+
1712+
for (const path of paths) {
1713+
guardCalls.mockClear()
1714+
1715+
expect((await supertest(server).post(path)).status).toBe(200)
1716+
expect(guardCalls.mock.calls).toEqual([['below'], ['above']])
1717+
}
1718+
})
1719+
1720+
it('exposes @SetMetadata from both sides of the wrapper and lets the outermost value win', async () => {
1721+
@Controller()
1722+
@UseGuards(MetaGuard)
1723+
class ImplController {
1724+
@SetMetadata('above', 'above-value')
1725+
@SetMetadata('roles', ['admin'])
1726+
@SetMetadata('cleared', undefined)
1727+
@Wrap()
1728+
@SetMetadata('cleared', 'below-value')
1729+
@SetMetadata('roles', ['user'])
1730+
@SetMetadata('below', 'below-value')
1731+
@Implement(contract)
1732+
router() {
1733+
return router()
1734+
}
1735+
}
1736+
1737+
const server = await createServer(ImplController)
1738+
1739+
for (const path of paths) {
1740+
handlerMeta.mockClear()
1741+
1742+
expect((await supertest(server).post(path)).status).toBe(200)
1743+
expect(handlerMeta).toHaveBeenCalledExactlyOnceWith(
1744+
'above-value',
1745+
'below-value',
1746+
['admin'],
1747+
undefined,
1748+
)
1749+
}
1750+
})
1751+
1752+
it('keeps guards when their metadata key is set to undefined on the other side of the wrapper', async () => {
1753+
@Controller()
1754+
class ImplController {
1755+
@SetMetadata('__guards__', undefined)
1756+
@Wrap()
1757+
@UseGuards(recordingGuard('below'))
1758+
@Implement(contract)
1759+
router() {
1760+
return router()
1761+
}
1762+
}
1763+
1764+
const server = await createServer(ImplController)
1765+
1766+
for (const path of paths) {
1767+
guardCalls.mockClear()
1768+
1769+
expect((await supertest(server).post(path)).status).toBe(200)
1770+
expect(guardCalls.mock.calls).toEqual([['below']])
1771+
}
1772+
})
1773+
1774+
it('calls the wrapper and returns the procedure output on every route', async () => {
1775+
@Controller()
1776+
class ImplController {
1777+
@Wrap()
1778+
@Implement(contract)
1779+
router() {
1780+
return router()
1781+
}
1782+
}
1783+
1784+
const server = await createServer(ImplController)
1785+
1786+
const pingRes = await supertest(server).post('/wrapped/ping')
1787+
expect(pingRes.status).toBe(200)
1788+
expect(pingRes.body).toEqual('ping')
1789+
expect(wrapperCalled).toHaveBeenCalledTimes(1)
1790+
1791+
const pongRes = await supertest(server).post('/wrapped/pong')
1792+
expect(pongRes.status).toBe(200)
1793+
expect(pongRes.body).toEqual('pong')
1794+
expect(wrapperCalled).toHaveBeenCalledTimes(2)
1795+
})
1796+
})
1797+
1798+
it.each([
1799+
['a wrapper mutating the descriptor', InPlaceWrap],
1800+
['a wrapper returning a new descriptor', NewDescriptorWrap],
1801+
] as const)('procedure-based implementation applies a guard above %s', async (_, Wrap) => {
1802+
@Controller()
1803+
class ImplController {
1804+
@UseGuards(DenyGuard)
1805+
@Wrap()
1806+
@Implement(contract.ping)
1807+
ping() {
1808+
return router().ping
1809+
}
1810+
}
1811+
1812+
const server = await createServer(ImplController)
1813+
1814+
expect((await supertest(server).post('/wrapped/ping')).status).toBe(403)
1815+
})
1816+
})
1817+
16061818
describe('router-based implementation applies method-level interceptors to synthesized methods', () => {
16071819
const contract = {
16081820
ping: oc.meta(openapi({ path: '/intercepted/ping' })),

‎packages/nest/src/implement.ts‎

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ import type {
3333
StandardHandlerCodecResolvedProcedure,
3434
} from '@orpc/server/standard'
3535
import { StandardHandler } from '@orpc/server/standard'
36-
import type { Promisable } from '@orpc/shared'
36+
import type { AnyFunction, Promisable } from '@orpc/shared'
3737
import {
3838
isAsyncIteratorObject,
3939
listenAbort,
@@ -76,6 +76,15 @@ const MethodDecoratorMap = {
7676
OPTIONS: Options,
7777
}
7878

79+
// Nest appends to these keys across decorators, while any other metadata is replaced
80+
const ACCUMULATED_METADATA_KEYS = new Set([
81+
'__guards__',
82+
'__interceptors__',
83+
'__pipes__',
84+
'__exceptionFilters__',
85+
'__headers__',
86+
])
87+
7988
/**
8089
* Decorator that implements an oRPC contract (procedure or router contract)
8190
* on a NestJS controller method. It registers the corresponding NestJS routes
@@ -150,6 +159,8 @@ function implementRouterContract(
150159
propertyKey: string,
151160
descriptor: TypedPropertyDescriptor<(...args: any[]) => any>,
152161
): void {
162+
const originalMethod = descriptor.value!
163+
153164
for (const [key, childContract] of Object.entries(contract)) {
154165
let methodName = `${propertyKey}_${key}`
155166

@@ -159,13 +170,15 @@ function implementRouterContract(
159170
}
160171

161172
target[methodName] = async function (...args: any[]) {
162-
const router = await descriptor.value!.apply(this, args)
173+
const router = await target[propertyKey].apply(this, args)
163174
return getRouter(router, [key])
164175
}
165176

166-
Object.setPrototypeOf(target[methodName], descriptor.value!)
177+
const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName)!
167178

168179
queueMicrotask(() => {
180+
inheritFunctionMetadata(childDescriptor.value, originalMethod, target[propertyKey])
181+
169182
for (const p of Reflect.getOwnMetadataKeys(target, propertyKey)) {
170183
Reflect.defineMetadata(
171184
p,
@@ -185,8 +198,6 @@ function implementRouterContract(
185198
}
186199
})
187200

188-
const childDescriptor = Object.getOwnPropertyDescriptor(target, methodName)!
189-
190201
if (childContract instanceof ProcedureContract) {
191202
const routeDecorator = toNestRouteDecorator(childContract)
192203

@@ -200,6 +211,35 @@ function implementRouterContract(
200211
}
201212
}
202213

214+
function inheritFunctionMetadata(
215+
method: AnyFunction,
216+
originalMethod: AnyFunction,
217+
finalMethod: AnyFunction,
218+
): void {
219+
Object.setPrototypeOf(method, finalMethod)
220+
221+
if (finalMethod === originalMethod) {
222+
return
223+
}
224+
225+
// a replacement that does not copy metadata leaves it only on the original function
226+
for (const key of Reflect.getMetadataKeys(originalMethod)) {
227+
const originalValue = Reflect.getMetadata(key, originalMethod)
228+
229+
if (!Reflect.hasMetadata(key, finalMethod)) {
230+
Reflect.defineMetadata(key, originalValue, method)
231+
} else if (ACCUMULATED_METADATA_KEYS.has(key)) {
232+
const originalItems: unknown[] = toArray(originalValue)
233+
const finalItems: unknown[] = toArray(Reflect.getMetadata(key, finalMethod))
234+
Reflect.defineMetadata(
235+
key,
236+
[...originalItems.filter((item) => !finalItems.includes(item)), ...finalItems],
237+
method,
238+
)
239+
}
240+
}
241+
}
242+
203243
@Injectable()
204244
export class ImplementInterceptor implements NestInterceptor {
205245
private readonly config: ORPCModuleConfig

0 commit comments

Comments
 (0)