add argon encryption
This commit is contained in:
parent
9425bd1518
commit
918ceae7a4
|
@ -11,6 +11,11 @@ MESSAGE_BROKER_URI=amqp://v3-broker:5672
|
|||
MESSAGE_BROKER_EXCHANGE=mobicoop
|
||||
MESSAGE_BROKER_EXCHANGE_DURABILITY=true
|
||||
|
||||
# REDIS
|
||||
REDIS_HOST=v3-redis
|
||||
REDIS_PASSWORD=redis
|
||||
REDIS_PORT=6379
|
||||
|
||||
# OPA
|
||||
OPA_IMAGE=openpolicyagent/opa:0.57.0
|
||||
OPA_IMAGE=openpolicyagent/opa:0.58.0
|
||||
OPA_URL=http://v3-auth-opa:8181/v1/data/
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
ARG NODE_VERSION=20.9.0
|
||||
|
||||
###################
|
||||
# BUILD FOR LOCAL DEVELOPMENT
|
||||
###################
|
||||
|
||||
FROM node:18-alpine3.16 As development
|
||||
FROM node:${NODE_VERSION} As development
|
||||
|
||||
# Create app directory
|
||||
WORKDIR /usr/src/app
|
||||
|
@ -29,7 +31,7 @@ USER node
|
|||
# BUILD FOR PRODUCTION
|
||||
###################
|
||||
|
||||
FROM node:18-alpine3.16 As build
|
||||
FROM node:${NODE_VERSION} As build
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
|
@ -66,7 +68,7 @@ USER node
|
|||
# PRODUCTION
|
||||
###################
|
||||
|
||||
FROM node:18-alpine3.16 As production
|
||||
FROM node:${NODE_VERSION} As production
|
||||
|
||||
# Copy package.json to be able to execute migration command
|
||||
COPY --chown=node:node package*.json ./
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -33,6 +33,7 @@
|
|||
"@golevelup/nestjs-rabbitmq": "^4.0.0",
|
||||
"@grpc/grpc-js": "^1.9.9",
|
||||
"@grpc/proto-loader": "^0.7.10",
|
||||
"@mobicoop/configuration-module": "^7.2.1",
|
||||
"@mobicoop/ddd-library": "^2.1.1",
|
||||
"@mobicoop/health-module": "^2.3.1",
|
||||
"@mobicoop/message-broker-module": "^2.1.1",
|
||||
|
@ -46,6 +47,7 @@
|
|||
"@nestjs/platform-express": "^10.2.8",
|
||||
"@nestjs/terminus": "^10.1.1",
|
||||
"@prisma/client": "^5.5.2",
|
||||
"argon2": "^0.31.2",
|
||||
"axios": "^1.6.0",
|
||||
"bcrypt": "5.1.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
binaryTargets = ["linux-musl", "debian-openssl-3.0.x"]
|
||||
binaryTargets = ["linux-musl", "debian-openssl-3.0.x", "linux-musl-openssl-3.0.x"]
|
||||
}
|
||||
|
||||
datasource db {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AuthenticationModule } from '@modules/authentication/authentication.module';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
import {
|
||||
|
@ -21,6 +21,10 @@ import {
|
|||
HEALTH_USERNAME_REPOSITORY,
|
||||
SERVICE_NAME,
|
||||
} from './app.constants';
|
||||
import {
|
||||
ConfigurationModule,
|
||||
ConfigurationModuleOptions,
|
||||
} from '@mobicoop/configuration-module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
|
@ -53,6 +57,19 @@ import {
|
|||
messagePublisher,
|
||||
}),
|
||||
}),
|
||||
ConfigurationModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: async (
|
||||
configService: ConfigService,
|
||||
): Promise<ConfigurationModuleOptions> => {
|
||||
return {
|
||||
host: configService.get<string>('REDIS_HOST') as string,
|
||||
port: configService.get<number>('REDIS_PORT') as number,
|
||||
password: configService.get<string>('REDIS_PASSWORD'),
|
||||
};
|
||||
},
|
||||
}),
|
||||
AuthenticationModule,
|
||||
AuthorizationModule,
|
||||
MessagerModule,
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
import {
|
||||
ConfigurationDomainGet,
|
||||
ConfigurationType,
|
||||
} from '@mobicoop/configuration-module';
|
||||
import { IsStrongPasswordOptions } from 'class-validator';
|
||||
|
||||
export const STRONG_PASSWORD_OPTIONS: IsStrongPasswordOptions = {
|
||||
|
@ -7,3 +11,11 @@ export const STRONG_PASSWORD_OPTIONS: IsStrongPasswordOptions = {
|
|||
minSymbols: 1,
|
||||
minUppercase: 1,
|
||||
};
|
||||
|
||||
export const AUTH_CONFIG_ENCRYPTION_ALGORITHM = 'encryptionAlgorithm';
|
||||
export const AuthConfig: ConfigurationDomainGet[] = [
|
||||
{
|
||||
key: AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
type: ConfigurationType.STRING,
|
||||
},
|
||||
];
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
export const AUTH_MESSAGE_PUBLISHER = Symbol('AUTH_MESSAGE_PUBLISHER');
|
||||
export const AUTHENTICATION_REPOSITORY = Symbol('AUTHENTICATION_REPOSITORY');
|
||||
export const USERNAME_REPOSITORY = Symbol('USERNAME_REPOSITORY');
|
||||
export const AUTHENTICATION_CONFIGURATION_REPOSITORY = Symbol(
|
||||
'AUTHENTICATION_CONFIGURATION_REPOSITORY',
|
||||
);
|
||||
export const PASSWORD_VERIFIER = Symbol('PASSWORD_VERIFIER');
|
||||
|
|
|
@ -4,7 +4,9 @@ import { CreateAuthenticationService } from './core/application/commands/create-
|
|||
import { AuthenticationMapper } from './authentication.mapper';
|
||||
import {
|
||||
AUTH_MESSAGE_PUBLISHER,
|
||||
AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
PASSWORD_VERIFIER,
|
||||
USERNAME_REPOSITORY,
|
||||
} from './authentication.di-tokens';
|
||||
import { AuthenticationRepository } from './infrastructure/authentication.repository';
|
||||
|
@ -27,6 +29,8 @@ import { ValidateAuthenticationGrpcController } from './interface/grpc-controlle
|
|||
import { ValidateAuthenticationQueryHandler } from './core/application/queries/validate-authentication/validate-authentication.query-handler';
|
||||
import { UserUpdatedMessageHandler } from './interface/message-handlers/user-updated.message-handler';
|
||||
import { UserDeletedMessageHandler } from './interface/message-handlers/user-deleted.message-handler';
|
||||
import { ConfigurationRepository } from '@mobicoop/configuration-module';
|
||||
import { PasswordVerifier } from './infrastructure/password-verifier';
|
||||
|
||||
const grpcControllers = [
|
||||
CreateAuthenticationGrpcController,
|
||||
|
@ -62,6 +66,10 @@ const repositories: Provider[] = [
|
|||
provide: USERNAME_REPOSITORY,
|
||||
useClass: UsernameRepository,
|
||||
},
|
||||
{
|
||||
provide: AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
useClass: ConfigurationRepository,
|
||||
},
|
||||
];
|
||||
|
||||
const messagePublishers: Provider[] = [
|
||||
|
@ -71,7 +79,13 @@ const messagePublishers: Provider[] = [
|
|||
},
|
||||
];
|
||||
|
||||
const orms: Provider[] = [PrismaService];
|
||||
const orms: Provider[] = [
|
||||
PrismaService,
|
||||
{
|
||||
provide: PASSWORD_VERIFIER,
|
||||
useClass: PasswordVerifier,
|
||||
},
|
||||
];
|
||||
|
||||
@Module({
|
||||
imports: [CqrsModule],
|
||||
|
|
|
@ -6,26 +6,53 @@ import {
|
|||
UniqueConstraintException,
|
||||
} from '@mobicoop/ddd-library';
|
||||
import { CreateAuthenticationCommand } from './create-authentication.command';
|
||||
import { AUTHENTICATION_REPOSITORY } from '@modules/authentication/authentication.di-tokens';
|
||||
import {
|
||||
AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
} from '@modules/authentication/authentication.di-tokens';
|
||||
import { AuthenticationRepositoryPort } from '../../ports/authentication.repository.port';
|
||||
import { AuthenticationEntity } from '@modules/authentication/core/domain/authentication.entity';
|
||||
import {
|
||||
AuthenticationAlreadyExistsException,
|
||||
UsernameAlreadyExistsException,
|
||||
} from '@modules/authentication/core/domain/authentication.errors';
|
||||
import {
|
||||
ConfigurationDomain,
|
||||
Configurator,
|
||||
GetConfigurationRepositoryPort,
|
||||
} from '@mobicoop/configuration-module';
|
||||
import {
|
||||
AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
AuthConfig,
|
||||
} from '@modules/authentication/authentication.constants';
|
||||
import { EncryptionAlgorithm } from '@modules/authentication/core/domain/username.types';
|
||||
import { PasswordEncrypter } from '@modules/authentication/infrastructure/password-encrypter';
|
||||
import { PasswordEncrypterPort } from '../../ports/password-encrypter.port';
|
||||
|
||||
@CommandHandler(CreateAuthenticationCommand)
|
||||
export class CreateAuthenticationService implements ICommandHandler {
|
||||
constructor(
|
||||
@Inject(AUTHENTICATION_REPOSITORY)
|
||||
private readonly authenticationRepository: AuthenticationRepositoryPort,
|
||||
@Inject(AUTHENTICATION_CONFIGURATION_REPOSITORY)
|
||||
private readonly configurationRepository: GetConfigurationRepositoryPort,
|
||||
) {}
|
||||
|
||||
async execute(command: CreateAuthenticationCommand): Promise<AggregateID> {
|
||||
const authConfigurator: Configurator =
|
||||
await this.configurationRepository.mget(
|
||||
ConfigurationDomain.AUTH,
|
||||
AuthConfig,
|
||||
);
|
||||
const passwordEncrypter: PasswordEncrypterPort = new PasswordEncrypter(
|
||||
authConfigurator.get<EncryptionAlgorithm>(
|
||||
AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
),
|
||||
);
|
||||
const authentication: AuthenticationEntity =
|
||||
await AuthenticationEntity.create({
|
||||
userId: command.userId,
|
||||
password: command.password,
|
||||
password: await passwordEncrypter.encrypt(command.password),
|
||||
usernames: command.usernames,
|
||||
});
|
||||
try {
|
||||
|
|
|
@ -1,22 +1,54 @@
|
|||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { Inject } from '@nestjs/common';
|
||||
import { AggregateID } from '@mobicoop/ddd-library';
|
||||
import { AUTHENTICATION_REPOSITORY } from '@modules/authentication/authentication.di-tokens';
|
||||
import {
|
||||
AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
} from '@modules/authentication/authentication.di-tokens';
|
||||
import { UpdatePasswordCommand } from './update-password.command';
|
||||
import { AuthenticationRepositoryPort } from '../../ports/authentication.repository.port';
|
||||
import { AuthenticationEntity } from '@modules/authentication/core/domain/authentication.entity';
|
||||
import {
|
||||
ConfigurationDomain,
|
||||
Configurator,
|
||||
GetConfigurationRepositoryPort,
|
||||
} from '@mobicoop/configuration-module';
|
||||
import {
|
||||
AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
AuthConfig,
|
||||
} from '@modules/authentication/authentication.constants';
|
||||
import { EncryptionAlgorithm } from '@modules/authentication/core/domain/username.types';
|
||||
import { PasswordEncrypterPort } from '../../ports/password-encrypter.port';
|
||||
import { PasswordEncrypter } from '@modules/authentication/infrastructure/password-encrypter';
|
||||
|
||||
@CommandHandler(UpdatePasswordCommand)
|
||||
export class UpdatePasswordService implements ICommandHandler {
|
||||
constructor(
|
||||
@Inject(AUTHENTICATION_REPOSITORY)
|
||||
private readonly authenticationRepository: AuthenticationRepositoryPort,
|
||||
@Inject(AUTHENTICATION_CONFIGURATION_REPOSITORY)
|
||||
private readonly configurationRepository: GetConfigurationRepositoryPort,
|
||||
) {}
|
||||
|
||||
async execute(command: UpdatePasswordCommand): Promise<AggregateID> {
|
||||
const authConfigurator: Configurator =
|
||||
await this.configurationRepository.mget(
|
||||
ConfigurationDomain.AUTH,
|
||||
AuthConfig,
|
||||
);
|
||||
const encryptionAlgorithm: EncryptionAlgorithm =
|
||||
authConfigurator.get<EncryptionAlgorithm>(
|
||||
AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
);
|
||||
const passwordEncrypter: PasswordEncrypterPort = new PasswordEncrypter(
|
||||
encryptionAlgorithm,
|
||||
);
|
||||
const authentication: AuthenticationEntity =
|
||||
await this.authenticationRepository.findOneById(command.userId);
|
||||
await authentication.updatePassword(command.password);
|
||||
const encryptedPassword: string = await passwordEncrypter.encrypt(
|
||||
command.password,
|
||||
);
|
||||
await authentication.updatePassword(encryptedPassword);
|
||||
await this.authenticationRepository.update(command.userId, authentication);
|
||||
return authentication.id;
|
||||
}
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
import { EncryptionAlgorithm } from '../../domain/username.types';
|
||||
|
||||
export abstract class PasswordEncrypterPort {
|
||||
constructor(protected readonly encryptionAlgorithm: EncryptionAlgorithm) {}
|
||||
abstract encrypt(plainPassword: string): Promise<string>;
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
export interface PasswordVerifierPort {
|
||||
verify(passwordToVerify: string, encryptedPassword: string): Promise<boolean>;
|
||||
}
|
|
@ -3,6 +3,7 @@ import { Inject, UnauthorizedException } from '@nestjs/common';
|
|||
import { ValidateAuthenticationQuery } from './validate-authentication.query';
|
||||
import {
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
PASSWORD_VERIFIER,
|
||||
USERNAME_REPOSITORY,
|
||||
} from '@modules/authentication/authentication.di-tokens';
|
||||
import { AuthenticationRepositoryPort } from '../../ports/authentication.repository.port';
|
||||
|
@ -10,6 +11,7 @@ import { UsernameRepositoryPort } from '../../ports/username.repository.port';
|
|||
import { AuthenticationEntity } from '@modules/authentication/core/domain/authentication.entity';
|
||||
import { UsernameEntity } from '@modules/authentication/core/domain/username.entity';
|
||||
import { AggregateID, NotFoundException } from '@mobicoop/ddd-library';
|
||||
import { PasswordVerifierPort } from '../../ports/password-verifier.port';
|
||||
|
||||
@QueryHandler(ValidateAuthenticationQuery)
|
||||
export class ValidateAuthenticationQueryHandler implements IQueryHandler {
|
||||
|
@ -18,6 +20,8 @@ export class ValidateAuthenticationQueryHandler implements IQueryHandler {
|
|||
private readonly authenticationRepository: AuthenticationRepositoryPort,
|
||||
@Inject(USERNAME_REPOSITORY)
|
||||
private readonly usernameRepository: UsernameRepositoryPort,
|
||||
@Inject(PASSWORD_VERIFIER)
|
||||
private readonly passwordVerifier: PasswordVerifierPort,
|
||||
) {}
|
||||
|
||||
execute = async (
|
||||
|
@ -40,6 +44,7 @@ export class ValidateAuthenticationQueryHandler implements IQueryHandler {
|
|||
try {
|
||||
const isAuthenticated = await authenticationEntity.authenticate(
|
||||
query.password,
|
||||
this.passwordVerifier,
|
||||
);
|
||||
if (isAuthenticated) return authenticationEntity.id;
|
||||
throw new UnauthorizedException();
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { AggregateRoot, AggregateID } from '@mobicoop/ddd-library';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import {
|
||||
AuthenticationProps,
|
||||
CreateAuthenticationProps,
|
||||
|
@ -7,6 +6,7 @@ import {
|
|||
import { AuthenticationCreatedDomainEvent } from './events/authentication-created.domain-event';
|
||||
import { AuthenticationDeletedDomainEvent } from './events/authentication-deleted.domain-event';
|
||||
import { PasswordUpdatedDomainEvent } from './events/password-updated.domain-event';
|
||||
import { PasswordVerifierPort } from '../application/ports/password-verifier.port';
|
||||
|
||||
export class AuthenticationEntity extends AggregateRoot<AuthenticationProps> {
|
||||
protected readonly _id: AggregateID;
|
||||
|
@ -15,12 +15,11 @@ export class AuthenticationEntity extends AggregateRoot<AuthenticationProps> {
|
|||
create: CreateAuthenticationProps,
|
||||
): Promise<AuthenticationEntity> => {
|
||||
const props: AuthenticationProps = { ...create };
|
||||
const hash = await AuthenticationEntity.encryptPassword(props.password);
|
||||
const authentication = new AuthenticationEntity({
|
||||
id: props.userId,
|
||||
props: {
|
||||
userId: props.userId,
|
||||
password: hash,
|
||||
password: props.password,
|
||||
usernames: props.usernames,
|
||||
},
|
||||
});
|
||||
|
@ -31,7 +30,7 @@ export class AuthenticationEntity extends AggregateRoot<AuthenticationProps> {
|
|||
};
|
||||
|
||||
updatePassword = async (password: string): Promise<void> => {
|
||||
this.props.password = await AuthenticationEntity.encryptPassword(password);
|
||||
this.props.password = password;
|
||||
this.addEvent(
|
||||
new PasswordUpdatedDomainEvent({
|
||||
aggregateId: this.id,
|
||||
|
@ -47,13 +46,13 @@ export class AuthenticationEntity extends AggregateRoot<AuthenticationProps> {
|
|||
);
|
||||
}
|
||||
|
||||
authenticate = async (password: string): Promise<boolean> =>
|
||||
await bcrypt.compare(password, this.props.password);
|
||||
authenticate = async (
|
||||
password: string,
|
||||
passwordVerifier: PasswordVerifierPort,
|
||||
): Promise<boolean> =>
|
||||
await passwordVerifier.verify(password, this.props.password);
|
||||
|
||||
validate(): void {
|
||||
// entity business rules validation to protect it's invariant before saving entity to a database
|
||||
}
|
||||
|
||||
private static encryptPassword = async (password: string): Promise<string> =>
|
||||
await bcrypt.hash(password, 10);
|
||||
}
|
||||
|
|
|
@ -19,3 +19,10 @@ export enum Type {
|
|||
EMAIL = 'EMAIL',
|
||||
PHONE = 'PHONE',
|
||||
}
|
||||
|
||||
export enum EncryptionAlgorithm {
|
||||
BCRYPT = 'BCRYPT',
|
||||
ARGON2I = 'ARGON2I',
|
||||
ARGON2D = 'ARGON2D',
|
||||
ARGON2ID = 'ARGON2ID',
|
||||
}
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { EncryptionAlgorithm } from '../core/domain/username.types';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import * as argon2 from 'argon2';
|
||||
import { PasswordEncrypterPort } from '../core/application/ports/password-encrypter.port';
|
||||
|
||||
@Injectable()
|
||||
export class PasswordEncrypter extends PasswordEncrypterPort {
|
||||
encrypt = async (plainPassword: string): Promise<string> => {
|
||||
switch (this.encryptionAlgorithm) {
|
||||
case EncryptionAlgorithm.BCRYPT:
|
||||
return await bcrypt.hash(plainPassword, 10);
|
||||
case EncryptionAlgorithm.ARGON2D:
|
||||
case EncryptionAlgorithm.ARGON2I:
|
||||
case EncryptionAlgorithm.ARGON2ID:
|
||||
return await argon2.hash(plainPassword, {
|
||||
type: this.argonType(),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
private argonType = ():
|
||||
| typeof argon2.argon2d
|
||||
| typeof argon2.argon2i
|
||||
| typeof argon2.argon2id => {
|
||||
switch (this.encryptionAlgorithm) {
|
||||
case EncryptionAlgorithm.ARGON2D:
|
||||
return argon2.argon2d;
|
||||
case EncryptionAlgorithm.ARGON2I:
|
||||
return argon2.argon2i;
|
||||
default:
|
||||
return argon2.argon2id;
|
||||
}
|
||||
};
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { EncryptionAlgorithm } from '../core/domain/username.types';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import * as argon2 from 'argon2';
|
||||
import { PasswordVerifierPort } from '../core/application/ports/password-verifier.port';
|
||||
|
||||
@Injectable()
|
||||
export class PasswordVerifier implements PasswordVerifierPort {
|
||||
verify = async (
|
||||
passwordToVerify: string,
|
||||
encryptedPassword: string,
|
||||
): Promise<boolean> => {
|
||||
const encryptionAlgorithm: EncryptionAlgorithm =
|
||||
this.guessEncryptionAlgorithm(encryptedPassword);
|
||||
switch (encryptionAlgorithm) {
|
||||
case EncryptionAlgorithm.BCRYPT:
|
||||
return await bcrypt.compare(passwordToVerify, encryptedPassword);
|
||||
case EncryptionAlgorithm.ARGON2D:
|
||||
case EncryptionAlgorithm.ARGON2I:
|
||||
case EncryptionAlgorithm.ARGON2ID:
|
||||
return await argon2.verify(encryptedPassword, passwordToVerify, {
|
||||
type: this.argonType(encryptionAlgorithm),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
private guessEncryptionAlgorithm = (
|
||||
password: string,
|
||||
): EncryptionAlgorithm => {
|
||||
if (password.substring(1, 9) === 'argon2id')
|
||||
return EncryptionAlgorithm.ARGON2ID;
|
||||
if (password.substring(1, 8) === 'argon2i')
|
||||
return EncryptionAlgorithm.ARGON2I;
|
||||
if (password.substring(1, 8) === 'argon2d')
|
||||
return EncryptionAlgorithm.ARGON2D;
|
||||
return EncryptionAlgorithm.BCRYPT;
|
||||
};
|
||||
|
||||
private argonType = (
|
||||
encryptionAlgorithm: EncryptionAlgorithm,
|
||||
): typeof argon2.argon2d | typeof argon2.argon2i | typeof argon2.argon2id => {
|
||||
switch (encryptionAlgorithm) {
|
||||
case EncryptionAlgorithm.ARGON2D:
|
||||
return argon2.argon2d;
|
||||
case EncryptionAlgorithm.ARGON2I:
|
||||
return argon2.argon2i;
|
||||
default:
|
||||
return argon2.argon2id;
|
||||
}
|
||||
};
|
||||
}
|
|
@ -1,3 +1,4 @@
|
|||
import { PasswordVerifierPort } from '@modules/authentication/core/application/ports/password-verifier.port';
|
||||
import { AuthenticationEntity } from '@modules/authentication/core/domain/authentication.entity';
|
||||
import { CreateAuthenticationProps } from '@modules/authentication/core/domain/authentication.types';
|
||||
import { AuthenticationDeletedDomainEvent } from '@modules/authentication/core/domain/events/authentication-deleted.domain-event';
|
||||
|
@ -30,6 +31,10 @@ const createAuthenticationPropsWith2Usernames: CreateAuthenticationProps = {
|
|||
],
|
||||
};
|
||||
|
||||
const mockPasswordVerifier: PasswordVerifierPort = {
|
||||
verify: jest.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false),
|
||||
};
|
||||
|
||||
describe('Authentication entity create', () => {
|
||||
it('should create a new authentication entity', async () => {
|
||||
const authenticationEntity: AuthenticationEntity =
|
||||
|
@ -37,7 +42,6 @@ describe('Authentication entity create', () => {
|
|||
expect(authenticationEntity.id).toBe(
|
||||
'165192d4-398a-4469-a16b-98c02cc6f531',
|
||||
);
|
||||
expect(authenticationEntity.getProps().password.length).toBe(60);
|
||||
expect(authenticationEntity.domainEvents.length).toBe(1);
|
||||
});
|
||||
it('should create a new authentication entity with 2 usernames', async () => {
|
||||
|
@ -80,15 +84,19 @@ describe('Authentication password validation', () => {
|
|||
it('should validate a valid password', async () => {
|
||||
const authenticationEntity: AuthenticationEntity =
|
||||
await AuthenticationEntity.create(createAuthenticationProps);
|
||||
const result: boolean =
|
||||
await authenticationEntity.authenticate('somePassword');
|
||||
const result: boolean = await authenticationEntity.authenticate(
|
||||
'somePassword',
|
||||
mockPasswordVerifier,
|
||||
);
|
||||
expect(result).toBeTruthy();
|
||||
});
|
||||
it('should not validate an invalid password', async () => {
|
||||
const authenticationEntity: AuthenticationEntity =
|
||||
await AuthenticationEntity.create(createAuthenticationProps);
|
||||
const result: boolean =
|
||||
await authenticationEntity.authenticate('someWrongPassword');
|
||||
const result: boolean = await authenticationEntity.authenticate(
|
||||
'someWrongPassword',
|
||||
mockPasswordVerifier,
|
||||
);
|
||||
expect(result).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,9 +1,19 @@
|
|||
import {
|
||||
ConfigurationDomain,
|
||||
ConfigurationDomainGet,
|
||||
Configurator,
|
||||
GetConfigurationRepositoryPort,
|
||||
} from '@mobicoop/configuration-module';
|
||||
import {
|
||||
AggregateID,
|
||||
ConflictException,
|
||||
UniqueConstraintException,
|
||||
} from '@mobicoop/ddd-library';
|
||||
import { AUTHENTICATION_REPOSITORY } from '@modules/authentication/authentication.di-tokens';
|
||||
import { AUTH_CONFIG_ENCRYPTION_ALGORITHM } from '@modules/authentication/authentication.constants';
|
||||
import {
|
||||
AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
} from '@modules/authentication/authentication.di-tokens';
|
||||
import { CreateAuthenticationCommand } from '@modules/authentication/core/application/commands/create-authentication/create-authentication.command';
|
||||
import { CreateAuthenticationService } from '@modules/authentication/core/application/commands/create-authentication/create-authentication.service';
|
||||
import { AuthenticationEntity } from '@modules/authentication/core/domain/authentication.entity';
|
||||
|
@ -44,6 +54,25 @@ const mockAuthenticationRepository = {
|
|||
}),
|
||||
};
|
||||
|
||||
const mockConfigurationRepository: GetConfigurationRepositoryPort = {
|
||||
get: jest.fn(),
|
||||
mget: jest.fn().mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
(domain: ConfigurationDomain, configs: ConfigurationDomainGet[]) => {
|
||||
switch (domain) {
|
||||
case ConfigurationDomain.AUTH:
|
||||
return new Configurator(ConfigurationDomain.AUTH, [
|
||||
{
|
||||
domain: ConfigurationDomain.AUTH,
|
||||
key: AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
value: 'BCRYPT',
|
||||
},
|
||||
]);
|
||||
}
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
describe('Create Authentication Service', () => {
|
||||
let createAuthenticationService: CreateAuthenticationService;
|
||||
|
||||
|
@ -54,6 +83,10 @@ describe('Create Authentication Service', () => {
|
|||
provide: AUTHENTICATION_REPOSITORY,
|
||||
useValue: mockAuthenticationRepository,
|
||||
},
|
||||
{
|
||||
provide: AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
CreateAuthenticationService,
|
||||
],
|
||||
}).compile();
|
||||
|
|
|
@ -1,10 +1,20 @@
|
|||
import { AggregateID } from '@mobicoop/ddd-library';
|
||||
import { AUTHENTICATION_REPOSITORY } from '@modules/authentication/authentication.di-tokens';
|
||||
import {
|
||||
AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
} from '@modules/authentication/authentication.di-tokens';
|
||||
import { UpdatePasswordService } from '@modules/authentication/core/application/commands/update-password/update-password.service';
|
||||
import { Type } from '@modules/authentication/core/domain/username.types';
|
||||
import { UpdatePasswordRequestDto } from '@modules/authentication/interface/grpc-controllers/dtos/update-password.request.dto';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UpdatePasswordCommand } from '@modules/authentication/core/application/commands/update-password/update-password.command';
|
||||
import {
|
||||
ConfigurationDomain,
|
||||
ConfigurationDomainGet,
|
||||
Configurator,
|
||||
GetConfigurationRepositoryPort,
|
||||
} from '@mobicoop/configuration-module';
|
||||
import { AUTH_CONFIG_ENCRYPTION_ALGORITHM } from '@modules/authentication/authentication.constants';
|
||||
|
||||
const updatePasswordRequest: UpdatePasswordRequestDto = {
|
||||
userId: '165192d4-398a-4469-a16b-98c02cc6f531',
|
||||
|
@ -24,6 +34,25 @@ const mockAuthenticationRepository = {
|
|||
update: jest.fn().mockImplementation(),
|
||||
};
|
||||
|
||||
const mockConfigurationRepository: GetConfigurationRepositoryPort = {
|
||||
get: jest.fn(),
|
||||
mget: jest.fn().mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
(domain: ConfigurationDomain, configs: ConfigurationDomainGet[]) => {
|
||||
switch (domain) {
|
||||
case ConfigurationDomain.AUTH:
|
||||
return new Configurator(ConfigurationDomain.AUTH, [
|
||||
{
|
||||
domain: ConfigurationDomain.AUTH,
|
||||
key: AUTH_CONFIG_ENCRYPTION_ALGORITHM,
|
||||
value: 'BCRYPT',
|
||||
},
|
||||
]);
|
||||
}
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
describe('Update Password Service', () => {
|
||||
let updatePasswordService: UpdatePasswordService;
|
||||
|
||||
|
@ -34,6 +63,10 @@ describe('Update Password Service', () => {
|
|||
provide: AUTHENTICATION_REPOSITORY,
|
||||
useValue: mockAuthenticationRepository,
|
||||
},
|
||||
{
|
||||
provide: AUTHENTICATION_CONFIGURATION_REPOSITORY,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
UpdatePasswordService,
|
||||
],
|
||||
}).compile();
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
import { AggregateID, NotFoundException } from '@mobicoop/ddd-library';
|
||||
import {
|
||||
AUTHENTICATION_REPOSITORY,
|
||||
PASSWORD_VERIFIER,
|
||||
USERNAME_REPOSITORY,
|
||||
} from '@modules/authentication/authentication.di-tokens';
|
||||
import { PasswordVerifierPort } from '@modules/authentication/core/application/ports/password-verifier.port';
|
||||
import { ValidateAuthenticationQuery } from '@modules/authentication/core/application/queries/validate-authentication/validate-authentication.query';
|
||||
import { ValidateAuthenticationQueryHandler } from '@modules/authentication/core/application/queries/validate-authentication/validate-authentication.query-handler';
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
|
@ -50,6 +52,10 @@ const mockAuthenticationRepository = {
|
|||
}),
|
||||
};
|
||||
|
||||
const mockPasswordVerifier: PasswordVerifierPort = {
|
||||
verify: jest.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false),
|
||||
};
|
||||
|
||||
describe('Validate Authentication Query Handler', () => {
|
||||
let validateAuthenticationQueryHandler: ValidateAuthenticationQueryHandler;
|
||||
|
||||
|
@ -64,6 +70,10 @@ describe('Validate Authentication Query Handler', () => {
|
|||
provide: USERNAME_REPOSITORY,
|
||||
useValue: mockUsernameRepository,
|
||||
},
|
||||
{
|
||||
provide: PASSWORD_VERIFIER,
|
||||
useValue: mockPasswordVerifier,
|
||||
},
|
||||
ValidateAuthenticationQueryHandler,
|
||||
],
|
||||
}).compile();
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
import { PasswordEncrypterPort } from '@modules/authentication/core/application/ports/password-encrypter.port';
|
||||
import { EncryptionAlgorithm } from '@modules/authentication/core/domain/username.types';
|
||||
import { PasswordEncrypter } from '@modules/authentication/infrastructure/password-encrypter';
|
||||
|
||||
describe('Password encrypter', () => {
|
||||
it('should encrypt a password in bcrypt', async () => {
|
||||
const passwordEncrypter: PasswordEncrypterPort = new PasswordEncrypter(
|
||||
EncryptionAlgorithm.BCRYPT,
|
||||
);
|
||||
const encryptedPassword: string =
|
||||
await passwordEncrypter.encrypt('somePassword');
|
||||
expect(encryptedPassword.substring(0, 2)).toBe('$2');
|
||||
});
|
||||
|
||||
it('should encrypt a password in argon2i', async () => {
|
||||
const passwordEncrypter: PasswordEncrypterPort = new PasswordEncrypter(
|
||||
EncryptionAlgorithm.ARGON2I,
|
||||
);
|
||||
const encryptedPassword: string =
|
||||
await passwordEncrypter.encrypt('somePassword');
|
||||
expect(encryptedPassword.substring(0, 9)).toBe('$argon2i$');
|
||||
});
|
||||
|
||||
it('should encrypt a password in argon2d', async () => {
|
||||
const passwordEncrypter: PasswordEncrypterPort = new PasswordEncrypter(
|
||||
EncryptionAlgorithm.ARGON2D,
|
||||
);
|
||||
const encryptedPassword: string =
|
||||
await passwordEncrypter.encrypt('somePassword');
|
||||
expect(encryptedPassword.substring(0, 9)).toBe('$argon2d$');
|
||||
});
|
||||
|
||||
it('should encrypt a password in argon2id', async () => {
|
||||
const passwordEncrypter: PasswordEncrypterPort = new PasswordEncrypter(
|
||||
EncryptionAlgorithm.ARGON2ID,
|
||||
);
|
||||
const encryptedPassword: string =
|
||||
await passwordEncrypter.encrypt('somePassword');
|
||||
expect(encryptedPassword.substring(0, 10)).toBe('$argon2id$');
|
||||
});
|
||||
});
|
|
@ -0,0 +1,46 @@
|
|||
import { PasswordVerifierPort } from '@modules/authentication/core/application/ports/password-verifier.port';
|
||||
import { PasswordVerifier } from '@modules/authentication/infrastructure/password-verifier';
|
||||
|
||||
describe('Password verifier', () => {
|
||||
const passwordVerifier: PasswordVerifierPort = new PasswordVerifier();
|
||||
|
||||
it('should verify a bcrypt password', async () => {
|
||||
const bcryptEncryptedPassword: string =
|
||||
'$2b$10$IGMj7/tH66kzO8rqwdogK.tgY2nFOdtMC.dzMAYUVfbSTPwWk7sk.';
|
||||
const verified: boolean = await passwordVerifier.verify(
|
||||
'somePassword',
|
||||
bcryptEncryptedPassword,
|
||||
);
|
||||
expect(verified).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should verify an argon2i password', async () => {
|
||||
const argon2iEncryptedPassword: string =
|
||||
'$argon2i$v=19$m=16,t=2,p=1$c2lERkU0UmpMYkhSa1h3eQ$hSyr7TZZDzvq9XJgA+D/pw';
|
||||
const verified: boolean = await passwordVerifier.verify(
|
||||
'somePassword',
|
||||
argon2iEncryptedPassword,
|
||||
);
|
||||
expect(verified).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should verify an argon2d password', async () => {
|
||||
const argon2dEncryptedPassword: string =
|
||||
'$argon2d$v=19$m=16,t=2,p=1$c2lERkU0UmpMYkhSa1h3eQ$YBopyKamOUl7ZPhu+KPASw';
|
||||
const verified: boolean = await passwordVerifier.verify(
|
||||
'somePassword',
|
||||
argon2dEncryptedPassword,
|
||||
);
|
||||
expect(verified).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should verify an argon2id password', async () => {
|
||||
const argon2idEncryptedPassword: string =
|
||||
'$argon2id$v=19$m=16,t=2,p=1$c2lERkU0UmpMYkhSa1h3eQ$Heokt0Lk6mtBmRE07q94lw';
|
||||
const verified: boolean = await passwordVerifier.verify(
|
||||
'somePassword',
|
||||
argon2idEncryptedPassword,
|
||||
);
|
||||
expect(verified).toBeTruthy();
|
||||
});
|
||||
});
|
Loading…
Reference in New Issue