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

fix(core): Use JWT as reset password token #6714

Merged
merged 18 commits into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from 15 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
4 changes: 4 additions & 0 deletions packages/cli/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ import { SourceControlService } from '@/environments/sourceControl/sourceControl
import { SourceControlController } from '@/environments/sourceControl/sourceControl.controller.ee';
import { ExecutionRepository } from '@db/repositories';
import type { ExecutionEntity } from '@db/entities/ExecutionEntity';
import { JwtService } from './services/jwt.service';

const exec = promisify(callbackExec);

Expand Down Expand Up @@ -463,6 +464,7 @@ export class Server extends AbstractServer {
const internalHooks = Container.get(InternalHooks);
const mailer = Container.get(UserManagementMailer);
const postHog = this.postHog;
const jwtService = Container.get(JwtService);

const controllers: object[] = [
new EventBusController(),
Expand All @@ -477,6 +479,7 @@ export class Server extends AbstractServer {
mailer,
repositories,
logger,
jwtService,
}),
new TagsController({ config, repositories, externalHooks }),
new TranslationController(config, this.credentialTypes),
Expand All @@ -489,6 +492,7 @@ export class Server extends AbstractServer {
activeWorkflowRunner,
logger,
postHog,
jwtService,
}),
Container.get(SamlController),
Container.get(SourceControlController),
Expand Down
10 changes: 1 addition & 9 deletions packages/cli/src/UserManagement/UserManagementHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,7 @@ export function validatePassword(password?: string): string {
* Remove sensitive properties from the user to return to the client.
*/
export function sanitizeUser(user: User, withoutKeys?: string[]): PublicUser {
const {
password,
resetPasswordToken,
resetPasswordTokenExpiration,
updatedAt,
apiKey,
authIdentities,
...rest
} = user;
const { password, updatedAt, apiKey, authIdentities, ...rest } = user;
if (withoutKeys) {
withoutKeys.forEach((key) => {
// @ts-ignore
Expand Down
1 change: 0 additions & 1 deletion packages/cli/src/auth/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export function issueJWT(user: User): JwtToken {

const signedToken = jwt.sign(payload, config.getEnv('userManagement.jwtSecret'), {
expiresIn: expiresIn / 1000 /* in seconds */,
algorithm: 'HS256',
netroy marked this conversation as resolved.
Show resolved Hide resolved
});

return {
Expand Down
85 changes: 55 additions & 30 deletions packages/cli/src/controllers/passwordReset.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IsNull, MoreThanOrEqual, Not } from 'typeorm';
import { IsNull, Not } from 'typeorm';
import validator from 'validator';
import { Get, Post, RestController } from '@/decorators';
import {
Expand Down Expand Up @@ -28,6 +28,8 @@ import { UserService } from '@/user/user.service';
import { License } from '@/License';
import { Container } from 'typedi';
import { RESPONSE_ERROR_MESSAGES } from '@/constants';
import { TokenExpiredError } from 'jsonwebtoken';
import type { JwtService, JwtPayload } from '@/services/jwt.service';

@RestController()
export class PasswordResetController {
Expand All @@ -43,27 +45,32 @@ export class PasswordResetController {

private readonly userRepository: UserRepository;

private readonly jwtService: JwtService;

constructor({
config,
logger,
externalHooks,
internalHooks,
mailer,
repositories,
jwtService,
}: {
config: Config;
logger: ILogger;
externalHooks: IExternalHooksClass;
internalHooks: IInternalHooksClass;
mailer: UserManagementMailer;
repositories: Pick<IDatabaseCollections, 'User'>;
jwtService: JwtService;
}) {
this.config = config;
this.logger = logger;
this.externalHooks = externalHooks;
this.internalHooks = internalHooks;
this.mailer = mailer;
this.userRepository = repositories.User;
this.jwtService = jwtService;
}

/**
Expand Down Expand Up @@ -139,7 +146,15 @@ export class PasswordResetController {

const baseUrl = getInstanceBaseUrl();
const { id, firstName, lastName } = user;
const url = await UserService.generatePasswordResetUrl(user);

const resetPasswordToken = this.jwtService.signData(
{ sub: id },
{
expiresIn: '1d',
},
);

const url = await UserService.generatePasswordResetUrl(baseUrl, resetPasswordToken);

try {
await this.mailer.passwordReset({
Expand Down Expand Up @@ -175,59 +190,58 @@ export class PasswordResetController {
*/
@Get('/resolve-password-token')
async resolvePasswordToken(req: PasswordResetRequest.Credentials) {
const { token: resetPasswordToken, userId: id } = req.query;
const { token: resetPasswordToken } = req.query;

if (!resetPasswordToken || !id) {
if (!resetPasswordToken) {
this.logger.debug(
'Request to resolve password token failed because of missing password reset token or user ID in query string',
'Request to resolve password token failed because of missing password reset token',
{
queryString: req.query,
},
);
throw new BadRequestError('');
}

// Timestamp is saved in seconds
const currentTimestamp = Math.floor(Date.now() / 1000);
const decodedToken = this.verifyResetPasswordToken(resetPasswordToken);

const user = await this.userRepository.findOne({
where: {
id,
resetPasswordToken,
resetPasswordTokenExpiration: MoreThanOrEqual(currentTimestamp),
id: decodedToken.sub,
},
relations: ['globalRole'],
});

if (!user?.isOwner && !Container.get(License).isWithinUsersLimit()) {
this.logger.debug(
'Request to resolve password token failed because the user limit was reached',
{ userId: id },
{ userId: decodedToken.sub },
);
throw new UnauthorizedError(RESPONSE_ERROR_MESSAGES.USERS_QUOTA_REACHED);
}

if (!user) {
this.logger.debug(
'Request to resolve password token failed because no user was found for the provided user ID and reset password token',
'Request to resolve password token failed because no user was found for the provided user ID',
{
userId: id,
userId: decodedToken.sub,
resetPasswordToken,
},
);
throw new NotFoundError('');
}

this.logger.info('Reset-password token resolved successfully', { userId: id });
this.logger.info('Reset-password token resolved successfully', { userId: user.id });
void this.internalHooks.onUserPasswordResetEmailClick({ user });
}

/**
* Verify password reset token and user ID and update password.
* Verify password reset token and update password.
*/
@Post('/change-password')
async changePassword(req: PasswordResetRequest.NewPassword, res: Response) {
const { token: resetPasswordToken, userId, password } = req.body;
const { token: resetPasswordToken, password } = req.body;

if (!resetPasswordToken || !userId || !password) {
if (!resetPasswordToken || !password) {
this.logger.debug(
'Request to change password failed because of missing user ID or password or reset password token in payload',
{
Expand All @@ -239,23 +253,17 @@ export class PasswordResetController {

const validPassword = validatePassword(password);

// Timestamp is saved in seconds
const currentTimestamp = Math.floor(Date.now() / 1000);
const decodedToken = this.verifyResetPasswordToken(resetPasswordToken);

const user = await this.userRepository.findOne({
where: {
id: userId,
resetPasswordToken,
resetPasswordTokenExpiration: MoreThanOrEqual(currentTimestamp),
},
where: { id: decodedToken.sub },
relations: ['authIdentities'],
});

if (!user) {
this.logger.debug(
'Request to resolve password token failed because no user was found for the provided user ID and reset password token',
'Request to resolve password token failed because no user was found for the provided user ID',
{
userId,
resetPasswordToken,
},
);
Expand All @@ -264,13 +272,11 @@ export class PasswordResetController {

const passwordHash = await hashPassword(validPassword);

await this.userRepository.update(userId, {
await this.userRepository.update(user.id, {
password: passwordHash,
resetPasswordToken: null,
resetPasswordTokenExpiration: null,
});

this.logger.info('User password updated successfully', { userId });
this.logger.info('User password updated successfully', { userId: user.id });

await issueCookie(res, user);

Expand All @@ -290,4 +296,23 @@ export class PasswordResetController {

await this.externalHooks.run('user.password.update', [user.email, passwordHash]);
}

private verifyResetPasswordToken(resetPasswordToken: string) {
let decodedToken: JwtPayload;
try {
decodedToken = this.jwtService.verifyToken(resetPasswordToken);
return decodedToken;
} catch (e) {
if (e instanceof TokenExpiredError) {
this.logger.debug('Reset password token expired', {
resetPasswordToken,
});
throw new NotFoundError('');
}
this.logger.debug('Error verifying token', {
resetPasswordToken,
});
throw new BadRequestError('');
}
}
}
18 changes: 17 additions & 1 deletion packages/cli/src/controllers/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { plainToInstance } from 'class-transformer';
import { License } from '@/License';
import { Container } from 'typedi';
import { RESPONSE_ERROR_MESSAGES } from '@/constants';
import type { JwtService } from '@/services/jwt.service';

@Authorized(['global', 'owner'])
@RestController('/users')
Expand All @@ -73,6 +74,8 @@ export class UsersController {

private mailer: UserManagementMailer;

private jwtService: JwtService;

private postHog?: PostHogClient;

constructor({
Expand All @@ -83,6 +86,7 @@ export class UsersController {
repositories,
activeWorkflowRunner,
mailer,
jwtService,
postHog,
}: {
config: Config;
Expand All @@ -95,6 +99,7 @@ export class UsersController {
>;
activeWorkflowRunner: ActiveWorkflowRunner;
mailer: UserManagementMailer;
jwtService: JwtService;
postHog?: PostHogClient;
}) {
this.config = config;
Expand All @@ -107,6 +112,7 @@ export class UsersController {
this.sharedWorkflowRepository = repositories.SharedWorkflow;
this.activeWorkflowRunner = activeWorkflowRunner;
this.mailer = mailer;
this.jwtService = jwtService;
this.postHog = postHog;
}

Expand Down Expand Up @@ -382,7 +388,17 @@ export class UsersController {
if (!user) {
throw new NotFoundError('User not found');
}
const link = await UserService.generatePasswordResetUrl(user);

const resetPasswordToken = this.jwtService.signData(
{ sub: user.id },
{
expiresIn: '1d',
},
);

const baseUrl = getInstanceBaseUrl();

const link = await UserService.generatePasswordResetUrl(baseUrl, resetPasswordToken);
return {
link,
};
Expand Down
7 changes: 0 additions & 7 deletions packages/cli/src/databases/entities/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,6 @@ export class User extends AbstractEntity implements IUser {
@IsString({ message: 'Password must be of type string.' })
password: string;

@Column({ type: String, nullable: true })
resetPasswordToken?: string | null;

// Expiration timestamp saved in seconds
@Column({ type: Number, nullable: true })
resetPasswordTokenExpiration?: number | null;

@Column({
type: jsonColumnType,
nullable: true,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { MigrationContext, ReversibleMigration } from '@db/types';
import { TableColumn } from 'typeorm';

export class RemoveResetPasswordColumns1690000000030 implements ReversibleMigration {
async up({ queryRunner, tablePrefix }: MigrationContext) {
await queryRunner.dropColumn(`${tablePrefix}user`, 'resetPasswordToken');
await queryRunner.dropColumn(`${tablePrefix}user`, 'resetPasswordTokenExpiration');
}

async down({ queryRunner, tablePrefix }: MigrationContext) {
await queryRunner.addColumn(
`${tablePrefix}user`,
new TableColumn({
name: 'resetPasswordToken',
type: 'varchar',
isNullable: true,
}),
);

await queryRunner.addColumn(
`${tablePrefix}user`,
new TableColumn({
name: 'resetPasswordTokenExpiration',
type: 'int',
isNullable: true,
}),
);
}
}
2 changes: 2 additions & 0 deletions packages/cli/src/databases/migrations/mysqldb/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { MigrateIntegerKeysToString1690000000001 } from './1690000000001-Migrate
import { SeparateExecutionData1690000000030 } from './1690000000030-SeparateExecutionData';
import { FixExecutionDataType1690000000031 } from './1690000000031-FixExecutionDataType';
import { RemoveSkipOwnerSetup1681134145997 } from './1681134145997-RemoveSkipOwnerSetup';
import { RemoveResetPasswordColumns1690000000030 } from '../common/1690000000030-RemoveResetPasswordColumns';

export const mysqlMigrations: Migration[] = [
InitialMigration1588157391238,
Expand Down Expand Up @@ -87,4 +88,5 @@ export const mysqlMigrations: Migration[] = [
SeparateExecutionData1690000000030,
FixExecutionDataType1690000000031,
RemoveSkipOwnerSetup1681134145997,
RemoveResetPasswordColumns1690000000030,
];
2 changes: 2 additions & 0 deletions packages/cli/src/databases/migrations/postgresdb/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { AddUserActivatedProperty1681134145996 } from './1681134145996-AddUserAc
import { MigrateIntegerKeysToString1690000000000 } from './1690000000000-MigrateIntegerKeysToString';
import { SeparateExecutionData1690000000020 } from './1690000000020-SeparateExecutionData';
import { RemoveSkipOwnerSetup1681134145997 } from './1681134145997-RemoveSkipOwnerSetup';
import { RemoveResetPasswordColumns1690000000030 } from '../common/1690000000030-RemoveResetPasswordColumns';

export const postgresMigrations: Migration[] = [
InitialMigration1587669153312,
Expand Down Expand Up @@ -81,4 +82,5 @@ export const postgresMigrations: Migration[] = [
MigrateIntegerKeysToString1690000000000,
SeparateExecutionData1690000000020,
RemoveSkipOwnerSetup1681134145997,
RemoveResetPasswordColumns1690000000030,
];
Loading