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

[Reputation Oracle] NDA #3132

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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/apps/reputation-oracle/server/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,7 @@ SYNAPS_WEBHOOK_SECRET=
SYNAPS_BASE_URL=
SYNAPS_STEP_DOCUMENT_ID=


# NDA
NDA_URL=

2 changes: 1 addition & 1 deletion packages/apps/reputation-oracle/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"migration:show": "yarn build && typeorm-ts-node-commonjs migration:show -d typeorm.config.ts",
"docker:db:up": "docker compose up -d postgres && yarn migration:run",
"docker:db:down": "docker compose down postgres",
"setup:local": "ts-node ./test/setup.ts",
"setup:local": "ts-node ./scripts/setup-kv-store.ts",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
Expand Down
3 changes: 3 additions & 0 deletions packages/apps/reputation-oracle/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { WebhookIncomingModule } from './modules/webhook/webhook-incoming.module
import { WebhookOutgoingModule } from './modules/webhook/webhook-outgoing.module';
import { UserModule } from './modules/user/user.module';
import { EmailModule } from './modules/email/module';
import { NDAModule } from './modules/nda/nda.module';
import { StorageModule } from './modules/storage/storage.module';
import Environment from './utils/environment';

Expand Down Expand Up @@ -64,6 +65,8 @@ import Environment from './utils/environment';
AuthModule,
CronJobModule,
EmailModule,
UserModule,
NDAModule,
EscrowCompletionModule,
HealthModule,
KycModule,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export enum ReputationEntityType {
EXCHANGE_ORACLE = 'exchange_oracle',
RECORDING_ORACLE = 'recording_oracle',
REPUTATION_ORACLE = 'reputation_oracle',
CREDENTIAL_VALIDATOR = 'credential_validator',
}

export enum ReputationLevel {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,11 @@ export class AuthConfigService {
get humanAppEmail(): string {
return this.configService.getOrThrow<string>('HUMAN_APP_EMAIL');
}

/**
* Latest NDA Url.
*/
get latestNdaUrl(): string {
return this.configService.getOrThrow<string>('NDA_URL');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddNDA1740657822938 implements MigrationInterface {
name = 'AddNDA1740657822938';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "hmt"."users" ADD "nda_signed" character varying`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "hmt"."users" DROP COLUMN "nda_signed"`,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ describe('AuthService', () => {
wallet_address: userEntity.evmAddress,
kyc_status: userEntity.kyc?.status,
reputation_network: MOCK_ADDRESS,
nda_signed: false,
qualifications: [],
role: userEntity.role,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ export class AuthService {
wallet_address: userEntity.evmAddress,
role: userEntity.role,
kyc_status: userEntity.kyc?.status,
nda_signed: userEntity.ndaSigned === this.authConfigService.latestNdaUrl,
reputation_network: operatorAddress,
qualifications: userEntity.userQualifications
? userEntity.userQualifications.map(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {
Controller,
Get,
Post,
Body,
Req,
UseFilters,
UseGuards,
} from '@nestjs/common';
import { NDAService } from './nda.service';
import {
ApiBearerAuth,
ApiBody,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { JwtAuthGuard } from 'src/common/guards';
import { RequestWithUser } from 'src/common/interfaces/request';
import { NDAErrorFilter } from './nda.error.filter';
import { AuthConfigService } from 'src/config/auth-config.service';
import { NDASignatureDto } from './nda.dto';

@ApiTags('NDA')
@UseFilters(NDAErrorFilter)
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('nda')
export class NDAController {
constructor(
private readonly ndaService: NDAService,
private readonly authConfigService: AuthConfigService,
) {}

@ApiOperation({
summary: 'Retrieves latest NDA URL',
description:
'Retrieves the latest NDA URL that users must sign to join the oracle',
})
@ApiResponse({
status: 200,
description: 'URL retrieved successfully',
type: String,
})
@ApiResponse({
status: 401,
description: 'Unauthorized. Missing or invalid credentials.',
})
@Get('latest')
getLatestNDA() {
return this.authConfigService.latestNdaUrl;
}

@ApiOperation({
summary: 'Sign NDA',
description:
'Signs the NDA with the provided URL. The URL must match the latest NDA URL.',
})
@ApiBody({ type: NDASignatureDto })
@ApiResponse({
status: 200,
description: 'NDA signed successfully',
type: String,
})
@ApiResponse({
status: 401,
description: 'Unauthorized. Missing or invalid credentials.',
})
@ApiResponse({
status: 400,
description: 'Bad Request. User has already signed the NDA.',
})
@Post('sign')
async signNDA(@Req() request: RequestWithUser, @Body() nda: NDASignatureDto) {
await this.ndaService.signNDA(request.user, nda);
return { message: 'NDA signed successfully' };
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsUrl } from 'class-validator';

export class NDASignatureDto {
@ApiProperty({ name: 'url' })
@IsString()
@IsUrl()
public url: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';

import { NDAError } from './nda.error';
import logger from '../../logger';

@Catch(NDAError)
export class NDAErrorFilter implements ExceptionFilter {
private readonly logger = logger.child({ context: NDAErrorFilter.name });

catch(exception: NDAError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = HttpStatus.BAD_REQUEST;

this.logger.error('NDA error', exception);

return response.status(status).json({
message: exception.message,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { BaseError } from '../../common/errors/base';

export enum NDAErrorMessage {
INVALID_NDA = 'Invalid NDA URL',
NDA_EXISTS = 'User has already signed the NDA',
}

export class NDAError extends BaseError {
userId: number;
constructor(message: NDAErrorMessage, userId: number) {
super(message);
this.userId = userId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { NDAController } from './nda.controller';
import { NDAService } from './nda.service';
import { UserModule } from '../user/user.module';
import { UserRepository } from '../user/user.repository';

@Module({
imports: [UserModule],
controllers: [NDAController],
providers: [NDAService, UserRepository],
})
export class NDAModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Test, TestingModule } from '@nestjs/testing';
import { NDAService } from './nda.service';
import { UserRepository } from '../user/user.repository';
import { AuthConfigService } from '../../config/auth-config.service';
import { NDASignatureDto } from './nda.dto';
import { NDAError, NDAErrorMessage } from './nda.error';
import { faker } from '@faker-js/faker/.';

const mockUserRepository = {
updateOne: jest.fn(),
};
const validNdaUrl = faker.internet.url();
const mockAuthConfigService = {
latestNdaUrl: validNdaUrl,
};

describe('NDAService', () => {
let service: NDAService;

beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
NDAService,
{ provide: UserRepository, useValue: mockUserRepository },
{ provide: AuthConfigService, useValue: mockAuthConfigService },
],
}).compile();

service = module.get<NDAService>(NDAService);
});

afterEach(() => {
jest.resetAllMocks();
});

describe('signNDA', () => {
const user: any = {
id: 1,
email: faker.internet.email(),
password: 'password',
ndaSigned: undefined,
};

const nda: NDASignatureDto = {
url: validNdaUrl,
};

it('should sign the NDA if the URL is valid and the user has not signed it yet', async () => {
await service.signNDA(user, nda);

expect(user.ndaSigned).toBe(validNdaUrl);
expect(mockUserRepository.updateOne).toHaveBeenCalledWith(user);
});

it('should throw an error if the NDA URL is invalid', async () => {
const invalidNda: NDASignatureDto = {
url: faker.internet.url(),
};

await expect(service.signNDA(user, invalidNda)).rejects.toThrow(
new NDAError(NDAErrorMessage.INVALID_NDA, user.id),
);
});

it('should throw an error if the user has already signed the NDA', async () => {
user.ndaSigned = mockAuthConfigService.latestNdaUrl;

await expect(service.signNDA(user, nda)).rejects.toThrow(
new NDAError(NDAErrorMessage.NDA_EXISTS, user.id),
);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Injectable } from '@nestjs/common';
import { AuthConfigService } from '../../config/auth-config.service';
import { UserEntity } from '../user/user.entity';
import { UserRepository } from '../user/user.repository';
import { NDASignatureDto } from './nda.dto';
import { NDAError, NDAErrorMessage } from './nda.error';

@Injectable()
export class NDAService {
constructor(
private readonly userRepository: UserRepository,
private readonly authConfigService: AuthConfigService,
) {}

async signNDA(user: UserEntity, nda: NDASignatureDto) {
const ndaUrl = this.authConfigService.latestNdaUrl;
if (nda.url !== ndaUrl) {
throw new NDAError(NDAErrorMessage.INVALID_NDA, user.id);
}
if (user.ndaSigned === ndaUrl) {
throw new NDAError(NDAErrorMessage.NDA_EXISTS, user.id);
}

user.ndaSigned = nda.url;

await this.userRepository.updateOne(user);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,7 @@ export class UserEntity extends BaseEntity implements IUser {
(userQualification) => userQualification.user,
)
public userQualifications: UserQualificationEntity[];

@Column({ type: 'varchar', nullable: true })
public ndaSigned?: string;
}
2 changes: 2 additions & 0 deletions packages/apps/reputation-oracle/server/test/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export const MOCK_WEB3_RPC_URL = 'http://localhost:8545';
export const MOCK_QUALIFICATION_MIN_VALIDITY = 100;
export const MOCK_FE_URL = 'http://localhost:3001';
export const MOCK_KYC_API_PRIVATE_KEY = 'api-private-key';
export const MOCK_NDA_URL = 'https://staging.humanprotocol.org/nda';

export const mockConfig: any = {
S3_ACCESS_KEY: MOCK_S3_ACCESS_KEY,
Expand Down Expand Up @@ -126,6 +127,7 @@ export const mockConfig: any = {
HCAPTCHA_LABELING_URL: MOCK_HCAPTCHA_LABELING_URL,
HCAPTCHA_DEFAULT_LABELER_LANG: MOCK_HCAPTCHA_DEFAULT_LABELER_LANG,
KYC_API_PRIVATE_KEY: MOCK_KYC_API_PRIVATE_KEY,
NDA_URL: MOCK_NDA_URL,
};

export const MOCK_BACKOFF_INTERVAL_SECONDS = 120;