Skip to content
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

feat(core): Add support for argument decorators and centralize request validation #9734

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@
"xmllint-wasm": "3.0.1",
"yamljs": "0.3.0",
"zod": "3.22.4",
"zod-class": "0.0.13",
"zod-to-json-schema": "3.22.4"
}
}
9 changes: 1 addition & 8 deletions packages/cli/src/GenericHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,10 @@ import type { WorkflowEntity } from '@db/entities/WorkflowEntity';
import type { CredentialsEntity } from '@db/entities/CredentialsEntity';
import type { TagEntity } from '@db/entities/TagEntity';
import type { User } from '@db/entities/User';
import type { UserRoleChangePayload, UserUpdatePayload } from '@/requests';
import { BadRequestError } from './errors/response-errors/bad-request.error';

export async function validateEntity(
entity:
| WorkflowEntity
| CredentialsEntity
| TagEntity
| User
| UserUpdatePayload
| UserRoleChangePayload,
entity: WorkflowEntity | CredentialsEntity | TagEntity | User,
): Promise<void> {
const errors = await validate(entity);

Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/controllers/activeWorkflows.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Get, RestController } from '@/decorators';
import { Get, Req, RestController } from '@/decorators';
import { ActiveWorkflowRequest } from '@/requests';
import { ActiveWorkflowsService } from '@/services/activeWorkflows.service';

Expand All @@ -7,12 +7,12 @@ export class ActiveWorkflowsController {
constructor(private readonly activeWorkflowsService: ActiveWorkflowsService) {}

@Get('/')
async getActiveWorkflows(req: ActiveWorkflowRequest.GetAllActive) {
async getActiveWorkflows(@Req req: ActiveWorkflowRequest.GetAllActive) {
return await this.activeWorkflowsService.getAllActiveIdsFor(req.user);
}

@Get('/error/:id')
async getActivationError(req: ActiveWorkflowRequest.GetActivationError) {
async getActivationError(@Req req: ActiveWorkflowRequest.GetActivationError) {
const {
user,
params: { id: workflowId },
Expand Down
6 changes: 4 additions & 2 deletions packages/cli/src/controllers/ai.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Post, RestController } from '@/decorators';
import { Post, Req, RestController } from '@/decorators';
import { AIRequest } from '@/requests';
import { AIService } from '@/services/ai.service';
import { FailedDependencyError } from '@/errors/response-errors/failed-dependency.error';
Expand All @@ -11,7 +11,9 @@ export class AIController {
* Generate CURL request and additional HTTP Node metadata for given service and request
*/
@Post('/generate-curl')
async generateCurl(req: AIRequest.GenerateCurl): Promise<{ curl: string; metadata?: object }> {
async generateCurl(
@Req req: AIRequest.GenerateCurl,
): Promise<{ curl: string; metadata?: object }> {
const { service, request } = req.body;

try {
Expand Down
12 changes: 6 additions & 6 deletions packages/cli/src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import validator from 'validator';

import { AuthService } from '@/auth/auth.service';
import { Get, Post, RestController } from '@/decorators';
import { Get, Post, Req, Res, RestController } from '@/decorators';
import { RESPONSE_ERROR_MESSAGES } from '@/constants';
import { Request, Response } from 'express';
import { Response } from 'express';
import type { User } from '@db/entities/User';
import { AuthenticatedRequest, LoginRequest, UserRequest } from '@/requests';
import type { PublicUser } from '@/Interfaces';
Expand Down Expand Up @@ -42,7 +42,7 @@ export class AuthController {

/** Log in a user */
@Post('/login', { skipAuth: true, rateLimit: true })
async login(req: LoginRequest, res: Response): Promise<PublicUser | undefined> {
async login(@Req req: LoginRequest, @Res res: Response): Promise<PublicUser | undefined> {
const { email, password, mfaToken, mfaRecoveryCode } = req.body;
if (!email) throw new ApplicationError('Email is required to log in');
if (!password) throw new ApplicationError('Password is required to log in');
Expand Down Expand Up @@ -110,7 +110,7 @@ export class AuthController {

/** Check if the user is already logged in */
@Get('/login')
async currentUser(req: AuthenticatedRequest): Promise<PublicUser> {
async currentUser(@Req req: AuthenticatedRequest): Promise<PublicUser> {
return await this.userService.toPublic(req.user, {
posthog: this.postHog,
withScopes: true,
Expand All @@ -119,7 +119,7 @@ export class AuthController {

/** Validate invite token to enable invitee to set up their account */
@Get('/resolve-signup-token', { skipAuth: true })
async resolveSignupToken(req: UserRequest.ResolveSignUp) {
async resolveSignupToken(@Req req: UserRequest.ResolveSignUp) {
const { inviterId, inviteeId } = req.query;
const isWithinUsersLimit = this.license.isWithinUsersLimit();

Expand Down Expand Up @@ -188,7 +188,7 @@ export class AuthController {

/** Log out a user */
@Post('/logout')
logout(_: Request, res: Response) {
logout(@Res res: Response) {
this.authService.clearCookie(res);
return { loggedOut: true };
}
Expand Down
44 changes: 13 additions & 31 deletions packages/cli/src/controllers/binaryData.controller.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,32 @@
import express from 'express';
import { BinaryDataService, FileNotFoundError, isValidNonDefaultMode } from 'n8n-core';
import { Get, RestController } from '@/decorators';
import { BinaryDataRequest } from '@/requests';
import { Response } from 'express';
import { BinaryDataService, FileNotFoundError } from 'n8n-core';
import { Get, Query, Res, RestController } from '@/decorators';
import { GetBinaryData } from '@/dtos/binaryData';

@RestController('/binary-data')
export class BinaryDataController {
constructor(private readonly binaryDataService: BinaryDataService) {}

@Get('/')
async get(req: BinaryDataRequest, res: express.Response) {
const { id: binaryDataId, action } = req.query;

if (!binaryDataId) {
return res.status(400).end('Missing binary data ID');
}

if (!binaryDataId.includes(':')) {
return res.status(400).end('Missing binary data mode');
}

const [mode] = binaryDataId.split(':');

if (!isValidNonDefaultMode(mode)) {
return res.status(400).end('Invalid binary data mode');
}

let { fileName, mimeType } = req.query;

async get(@Query query: GetBinaryData, @Res res: Response) {
try {
if (!fileName || !mimeType) {
if (!query.fileName || !query.mimeType) {
try {
const metadata = await this.binaryDataService.getMetadata(binaryDataId);
fileName = metadata.fileName;
mimeType = metadata.mimeType;
const metadata = await this.binaryDataService.getMetadata(query.id);
query.fileName = metadata.fileName;
query.mimeType = metadata.mimeType;
res.setHeader('Content-Length', metadata.fileSize);
} catch {}
}

if (mimeType) res.setHeader('Content-Type', mimeType);
if (query.mimeType) res.setHeader('Content-Type', query.mimeType);

if (action === 'download' && fileName) {
const encodedFilename = encodeURIComponent(fileName);
if (query.action === 'download' && query.fileName) {
const encodedFilename = encodeURIComponent(query.fileName);
res.setHeader('Content-Disposition', `attachment; filename="${encodedFilename}"`);
}

return await this.binaryDataService.getAsStream(binaryDataId);
return await this.binaryDataService.getAsStream(query.id);
} catch (error) {
if (error instanceof FileNotFoundError) return res.writeHead(404).end();
else throw error;
Expand Down
60 changes: 20 additions & 40 deletions packages/cli/src/controllers/me.controller.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import validator from 'validator';
import { plainToInstance } from 'class-transformer';
import { type RequestHandler, Response } from 'express';
import { randomBytes } from 'crypto';

import { AuthService } from '@/auth/auth.service';
import { Delete, Get, Patch, Post, RestController } from '@/decorators';
import { Body, Delete, Get, Patch, Post, Req, Res, RestController } from '@/decorators';
import { UserUpdateDTO } from '@/dtos/user/user.update';
import { PasswordUtility } from '@/services/password.utility';
import { validateEntity } from '@/GenericHelpers';
import type { User } from '@db/entities/User';
import {
AuthenticatedRequest,
MeRequest,
UserSettingsUpdatePayload,
UserUpdatePayload,
} from '@/requests';
import { AuthenticatedRequest, MeRequest } from '@/requests';
import type { PublicUser } from '@/Interfaces';
import { isSamlLicensedAndEnabled } from '@/sso/saml/samlHelpers';
import { UserService } from '@/services/user.service';
Expand All @@ -24,6 +17,8 @@ import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { UserRepository } from '@/databases/repositories/user.repository';
import { isApiEnabled } from '@/PublicApi';
import { EventRelay } from '@/eventbus/event-relay.service';
import { PasswordUpdateDTO } from '@/dtos/user/password.update';
import { SettingsUpdateDTO } from '@/dtos/user/settings.update';

export const isApiEnabledMiddleware: RequestHandler = (_, res, next) => {
if (isApiEnabled()) {
Expand All @@ -50,28 +45,13 @@ export class MeController {
* Update the logged-in user's properties, except password.
*/
@Patch('/')
async updateCurrentUser(req: MeRequest.UserUpdate, res: Response): Promise<PublicUser> {
async updateCurrentUser(
@Req req: AuthenticatedRequest,
@Body payload: UserUpdateDTO,
@Res res: Response,
): Promise<PublicUser> {
const { id: userId, email: currentEmail } = req.user;
const payload = plainToInstance(UserUpdatePayload, req.body, { excludeExtraneousValues: true });

const { email } = payload;
if (!email) {
this.logger.debug('Request to update user email failed because of missing email in payload', {
userId,
payload,
});
throw new BadRequestError('Email is mandatory');
}

if (!validator.isEmail(email)) {
this.logger.debug('Request to update user email failed because of invalid email in payload', {
userId,
invalidEmail: email,
});
throw new BadRequestError('Invalid email address');
}

await validateEntity(payload);

// If SAML is enabled, we don't allow the user to change their email address
if (isSamlLicensedAndEnabled()) {
Expand Down Expand Up @@ -113,9 +93,13 @@ export class MeController {
* Update the logged-in user's password.
*/
@Patch('/password')
async updatePassword(req: MeRequest.Password, res: Response) {
async updatePassword(
@Req req: AuthenticatedRequest,
@Body payload: PasswordUpdateDTO,
@Res res: Response,
) {
const { user } = req;
const { currentPassword, newPassword } = req.body;
const { currentPassword, newPassword } = payload;

// If SAML is enabled, we don't allow the user to change their email address
if (isSamlLicensedAndEnabled()) {
Expand All @@ -127,10 +111,6 @@ export class MeController {
);
}

if (typeof currentPassword !== 'string' || typeof newPassword !== 'string') {
throw new BadRequestError('Invalid payload.');
}

if (!user.password) {
throw new BadRequestError('Requesting user not set up.');
}
Expand Down Expand Up @@ -229,10 +209,10 @@ export class MeController {
* Update the logged-in user's settings.
*/
@Patch('/settings')
async updateCurrentUserSettings(req: MeRequest.UserSettingsUpdate): Promise<User['settings']> {
const payload = plainToInstance(UserSettingsUpdatePayload, req.body, {
excludeExtraneousValues: true,
});
async updateCurrentUserSettings(
@Req req: AuthenticatedRequest,
@Body payload: SettingsUpdateDTO,
): Promise<User['settings']> {
const { id } = req.user;

await this.userService.updateSettings(id, payload);
Expand Down
45 changes: 20 additions & 25 deletions packages/cli/src/controllers/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { plainToInstance } from 'class-transformer';

import { AuthService } from '@/auth/auth.service';
import { User } from '@db/entities/User';
import { GlobalScope, Delete, Get, RestController, Patch, Licensed } from '@/decorators';
import {
ListQuery,
UserRequest,
UserRoleChangePayload,
UserSettingsUpdatePayload,
} from '@/requests';
GlobalScope,
Delete,
Get,
RestController,
Patch,
Licensed,
Body,
Param,
Req,
} from '@/decorators';
import { AuthenticatedRequest, ListQuery, UserRequest } from '@/requests';
import type { PublicUser, ITelemetryUserDeletionData } from '@/Interfaces';
import { AuthIdentity } from '@db/entities/AuthIdentity';
import { SharedCredentialsRepository } from '@db/repositories/sharedCredentials.repository';
Expand All @@ -22,13 +25,14 @@ import { NotFoundError } from '@/errors/response-errors/not-found.error';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { ExternalHooks } from '@/ExternalHooks';
import { InternalHooks } from '@/InternalHooks';
import { validateEntity } from '@/GenericHelpers';
import { ProjectRepository } from '@/databases/repositories/project.repository';
import { Project } from '@/databases/entities/Project';
import { WorkflowService } from '@/workflows/workflow.service';
import { CredentialsService } from '@/credentials/credentials.service';
import { ProjectService } from '@/services/project.service';
import { EventRelay } from '@/eventbus/event-relay.service';
import { SettingsUpdateDTO } from '@/dtos/user/settings.update';
import { RoleChangeDTO } from '@/dtos/user/role.change';

@RestController('/users')
export class UsersController {
Expand Down Expand Up @@ -126,13 +130,7 @@ export class UsersController {

@Patch('/:id/settings')
@GlobalScope('user:update')
async updateUserSettings(req: UserRequest.UserSettingsUpdate) {
const payload = plainToInstance(UserSettingsUpdatePayload, req.body, {
excludeExtraneousValues: true,
});

const id = req.params.id;

async updateUserSettings(@Body payload: SettingsUpdateDTO, @Param('id') id: string) {
await this.userService.updateSettings(id, payload);

const user = await this.userRepository.findOneOrFail({
Expand Down Expand Up @@ -268,18 +266,15 @@ export class UsersController {
@Patch('/:id/role')
@GlobalScope('user:changeRole')
@Licensed('feat:advancedPermissions')
async changeGlobalRole(req: UserRequest.ChangeRole) {
async changeGlobalRole(
@Req req: AuthenticatedRequest,
@Body payload: RoleChangeDTO,
@Param('id') id: string,
) {
const { NO_ADMIN_ON_OWNER, NO_USER, NO_OWNER_ON_OWNER } =
UsersController.ERROR_MESSAGES.CHANGE_ROLE;

const payload = plainToInstance(UserRoleChangePayload, req.body, {
excludeExtraneousValues: true,
});
await validateEntity(payload);

const targetUser = await this.userRepository.findOne({
where: { id: req.params.id },
});
const targetUser = await this.userRepository.findOneBy({ id });
if (targetUser === null) {
throw new NotFoundError(NO_USER);
}
Expand Down
25 changes: 25 additions & 0 deletions packages/cli/src/decorators/Args.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { getRouteMetadata } from './controller.registry';
import type { Arg, Controller } from './types';

const ArgDecorator =
(arg: Arg): ParameterDecorator =>
(target, handlerName, parameterIndex) => {
const routeMetadata = getRouteMetadata(target.constructor as Controller, String(handlerName));
if (!routeMetadata.args) routeMetadata.args = [];
routeMetadata.args[parameterIndex] = arg;
};

/** Injects the request object into the handler */
export const Req = ArgDecorator({ type: 'req' });

/** Injects the response object into the handler */
export const Res = ArgDecorator({ type: 'res' });

/** Injects the request body into the handler */
export const Body = ArgDecorator({ type: 'body' });

/** Injects the request query into the handler */
export const Query = ArgDecorator({ type: 'query' });

/** Injects a request parameter into the handler */
export const Param = (key: string) => ArgDecorator({ type: 'param', key });
Loading
Loading