-
Notifications
You must be signed in to change notification settings - Fork 23
fix(http): parse body before guards and return parsed body synchronously #208
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
Open
nicoske
wants to merge
2
commits into
FOSSFORGE:main
Choose a base branch
from
nicoske:fix-http-body-before-guards
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+218
−24
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| // @ts-nocheck - NestJS decorators in test files cause false positive TypeScript errors | ||
| import { NestFactory } from '@nestjs/core'; | ||
| import { | ||
| Controller, | ||
| Post, | ||
| Req, | ||
| Res, | ||
| Module, | ||
| INestApplication, | ||
| CanActivate, | ||
| ExecutionContext, | ||
| UseGuards, | ||
| UnauthorizedException, | ||
| } from '@nestjs/common'; | ||
| import { UwsPlatformAdapter } from '../../src/http/platform/uws-platform.adapter'; | ||
| import { UwsResponse } from '../../src/http/core/response'; | ||
| import * as http from 'http'; | ||
|
|
||
| // ============================================================================ | ||
| // Guard that reads request.body synchronously, like typical auth guards that | ||
| // bind a token to fields of the payload | ||
| // ============================================================================ | ||
|
|
||
| let bodySeenByGuard: unknown; | ||
|
|
||
| class BodyAuthGuard implements CanActivate { | ||
| canActivate(context: ExecutionContext): boolean { | ||
| const request = context.switchToHttp().getRequest(); | ||
| const body = request.body; | ||
| bodySeenByGuard = body; | ||
|
|
||
| if (!body || typeof body !== 'object' || typeof body.then === 'function') { | ||
| throw new UnauthorizedException('Missing payload'); | ||
| } | ||
|
|
||
| return body.role === 'admin'; | ||
| } | ||
| } | ||
|
|
||
| // ============================================================================ | ||
| // Controller | ||
| // ============================================================================ | ||
|
|
||
| @Controller('guarded') | ||
| class GuardedController { | ||
| @Post('action') | ||
| @UseGuards(BodyAuthGuard) | ||
| action(@Res() res: UwsResponse) { | ||
| res.status(200).json({ ok: true }); | ||
| } | ||
| } | ||
|
|
||
| @Controller('plain') | ||
| class PlainController { | ||
| @Post('echo') | ||
| echo(@Req() req, @Res() res: UwsResponse) { | ||
| // request.body is already parsed by the time the handler runs, so a | ||
| // synchronous read returns the value, not a Promise | ||
| res.status(200).json({ body: req.body, wasPromise: typeof req.body?.then === 'function' }); | ||
| } | ||
| } | ||
|
|
||
| @Module({ | ||
| controllers: [GuardedController, PlainController], | ||
| }) | ||
| class TestModule {} | ||
|
|
||
| // ============================================================================ | ||
| // E2E Tests | ||
| // ============================================================================ | ||
|
|
||
| describe('Guards and body access E2E', () => { | ||
| let app: INestApplication; | ||
| let baseUrl: string; | ||
| const port = 13391; | ||
|
|
||
| beforeAll(async () => { | ||
| const adapter = new UwsPlatformAdapter({ port }); | ||
| app = await NestFactory.create(TestModule, adapter, { logger: false }); | ||
| await app.init(); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| adapter.listen(port, (error) => { | ||
| if (error) reject(error); | ||
| else resolve(); | ||
| }); | ||
| }); | ||
|
|
||
| baseUrl = `http://localhost:${port}`; | ||
| }, 10000); | ||
|
|
||
| afterAll(async () => { | ||
| if (app) { | ||
| await app.close(); | ||
| } | ||
| await new Promise((resolve) => setTimeout(resolve, 500)); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| bodySeenByGuard = undefined; | ||
| }); | ||
|
|
||
| function request( | ||
| method: string, | ||
| path: string, | ||
| body?: string, | ||
| contentType: string | null = 'application/json' | ||
| ): Promise<{ status: number; body: Record<string, unknown> }> { | ||
| return new Promise((resolve, reject) => { | ||
| const headers: Record<string, string> = {}; | ||
| if (body !== undefined) { | ||
| // contentType === null sends a body WITHOUT a Content-Type header | ||
| if (contentType !== null) headers['Content-Type'] = contentType; | ||
| headers['Content-Length'] = Buffer.byteLength(body).toString(); | ||
| } | ||
|
|
||
| const req = http.request(`${baseUrl}${path}`, { method, agent: false, headers }, (res) => { | ||
| const chunks: Buffer[] = []; | ||
| res.on('data', (chunk) => chunks.push(chunk)); | ||
| res.on('end', () => { | ||
| const raw = Buffer.concat(chunks).toString(); | ||
| let parsed: Record<string, unknown>; | ||
| try { | ||
| parsed = JSON.parse(raw); | ||
| } catch { | ||
| parsed = { raw }; | ||
| } | ||
| resolve({ status: res.statusCode || 0, body: parsed }); | ||
| }); | ||
| }); | ||
| req.setTimeout(5000, () => { | ||
| req.destroy(new Error(`${method} ${path} timed out`)); | ||
| }); | ||
| req.on('error', reject); | ||
| if (body !== undefined) req.write(body); | ||
| req.end(); | ||
| }); | ||
| } | ||
|
|
||
| it('lets a guard read the parsed body synchronously', async () => { | ||
| const res = await request('POST', '/guarded/action', JSON.stringify({ role: 'admin' })); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| expect(res.body).toEqual({ ok: true }); | ||
| expect(bodySeenByGuard).toEqual({ role: 'admin' }); | ||
| }); | ||
|
|
||
| it('rejects based on body content read inside the guard', async () => { | ||
| const res = await request('POST', '/guarded/action', JSON.stringify({ role: 'viewer' })); | ||
|
|
||
| expect(res.status).toBe(403); | ||
| expect(bodySeenByGuard).toEqual({ role: 'viewer' }); | ||
| }); | ||
|
|
||
| it('exposes the parsed body synchronously to handlers', async () => { | ||
| const res = await request('POST', '/plain/echo', JSON.stringify({ hello: 'world' })); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| expect(res.body).toEqual({ body: { hello: 'world' }, wasPromise: false }); | ||
| }); | ||
|
|
||
| it('gives guards a concrete body, not a pending Promise, when the request has a body but no Content-Type header', async () => { | ||
| const res = await request('POST', '/guarded/action', JSON.stringify({ role: 'admin' }), null); | ||
|
|
||
| // A body without a Content-Type is buffered (not JSON-decoded), so the guard | ||
| // cannot read .role and returns false -> 403. The point is that it saw a | ||
| // resolved value: before parsing moved ahead of guards it saw the pending | ||
| // buffer() Promise and threw 401 "Missing payload". | ||
| expect(res.status).toBe(403); | ||
| expect(bodySeenByGuard).toBeDefined(); | ||
| expect(typeof (bodySeenByGuard as { then?: unknown })?.then).not.toBe('function'); | ||
| }); | ||
|
|
||
| it('still rejects malformed JSON before the handler runs', async () => { | ||
| const res = await request('POST', '/plain/echo', '{not json'); | ||
|
|
||
| // Same status invalid JSON produced before the parse/guard reorder | ||
| // (see body-parsing.e2e.spec.ts) | ||
| expect(res.status).toBe(500); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.