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

refactor!: environment variables validation #216

Draft
wants to merge 2 commits into
base: develop
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
135 changes: 86 additions & 49 deletions src/common/config/env.validation.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,77 @@
import { plainToClass, Transform } from 'class-transformer';
import {
IsEnum,
IsString,
IsOptional,
validateSync,
Min,
IsArray,
ArrayMinSize,
IsInt,
IsArray,
IsBoolean,
ValidateIf,
IsEnum,
IsInt,
IsNotEmpty,
IsOptional,
IsPositive,
IsString,
IsUrl,
Max,
Min,
ValidateIf,
validateSync,
} from 'class-validator';
import { Environment, LogLevel, LogFormat } from './interfaces';
import { Environment, LogLevel, LogFormat, Chain } from './interfaces';
import { NonEmptyArray } from '@lido-nestjs/execution/dist/interfaces/non-empty-array';

const toNumber =
({ defaultValue }) =>
({ value }) => {
if (value === '' || value == null || value == undefined) return defaultValue;
if (value === '' || value == null) return defaultValue;
return Number(value);
};

export const toBoolean = (value: any): boolean => {
if (typeof value === 'boolean') {
return value;
}
const toBoolean = ({ defaultValue }) => {
return function({ value }) {
if (value == null || value === '') {
return defaultValue;
}

if (typeof value === 'number') {
return !!value;
}
if (typeof value === 'boolean') {
return value;
}

const str = value.toString().toLowerCase().trim();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if it is number?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the previous code gave users too much unnecessary freedom in setting boolean values. I think it's better to be more strict here and allow users to set only "true" or "false" strings as valid values of boolean variables and throw errors otherwise.

But I understand that it is a breaking change. If we know or can reasonably assume that some KAPI users should be able to set "1" or "yes" as valid values of boolean variables for a good reason, or some users already doing it this way, we should revert back to the previous behavior.

What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have a lot of users, so i dont know
i think in guides was true/false value, so they used it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on the results of today's internal discussion, it has been decided to revert back support of numerical values and special constants like "yes" and "no", but return an error if the undefined, null or empty string was provided. I'll update the PR.
@Amuhar please, let me know if you have any objections.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay, but i agree that just boolean values look better


switch (str) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I did a similar solution for Ejector we came across the fact that in some environments boolean variables can be capitalized, it would be good to take this into account.

https://github.com/lidofinance/lido-ts-nanolib/pull/5/files#diff-146bc8ef351e775395fe473346533483494222a0a9770be47547b8e6619a8188

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it has been taken into account. As you can see in the quoted code in line 38, I cast the input to lowercase before making comparisons. So, all strings in all registers should be accepted (uppercase, lowercase, capitalized).

case 'true':
case 'yes':
case '1':
return true;

if (!(typeof value === 'string')) {
return false;
case 'false':
case 'no':
case '0':
return false;

default:
return value;
}
}
}

switch (value.toLowerCase().trim()) {
case 'true':
case 'yes':
case '1':
return true;
case 'false':
case 'no':
case '0':
case null:
return false;
default:
return false;
const toArrayOfUrls = (url: string | null): string[] => {
if (url == null || url === '') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it extra check ? Because all urls required, or depends on another config

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check protects the app from the situation when a user sets an empty string as a value of the PROVIDERS_URLS for example. Like this: PROVIDERS_URLS=

Previously the @Transform() decorator had the following implementation:
@Transform(({ value }) => value.split(',').map((url) => url.replace(/\/$/, '')))

Assume a user sets this in the .env file: PROVIDERS_URLS=. The function in the @Transform decorator is executed first. It splits the empty string and converts it into an array. The result is the array that consists of only one element - an empty string: [""]. The next .map() function converts this array to the same result: [""]. Then validation decorators look at this value. It is an array with at least one element, everything is OK. The previous code accepted empty strings here and it was a bug. Now we have an extra @IsUrl() check that will protect the app from this case. But the check that you mentioned allows us to make sure that empty strings will never be accepted as URL values regardless of the @IsUrl() decorator. I prefer to leave this check in place.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good

return [];
}

return url.split(',').map((str) => str.trim().replace(/\/$/, ''));
};

export class EnvironmentVariables {
@IsOptional()
@IsEnum(Environment)
@Transform(({ value }) => value || Environment.development)
NODE_ENV: Environment = Environment.development;

@IsOptional()
@IsInt()
@Min(1)
@Min(1025)
@Max(65535)
@Transform(toNumber({ defaultValue: 3000 }))
PORT = 3000;

Expand All @@ -68,19 +81,19 @@ export class EnvironmentVariables {

@IsOptional()
@IsInt()
@Min(1)
@IsPositive()
Amuhar marked this conversation as resolved.
Show resolved Hide resolved
@Transform(toNumber({ defaultValue: 5 }))
GLOBAL_THROTTLE_TTL = 5;

@IsOptional()
@IsInt()
@Min(1)
@IsPositive()
@Transform(toNumber({ defaultValue: 100 }))
GLOBAL_THROTTLE_LIMIT = 100;

@IsOptional()
@IsInt()
@Min(1)
@IsPositive()
@Transform(toNumber({ defaultValue: 1 }))
GLOBAL_CACHE_TTL = 1;

Expand All @@ -98,78 +111,102 @@ export class EnvironmentVariables {
@Transform(({ value }) => value || LogFormat.json)
LOG_FORMAT: LogFormat = LogFormat.json;

@IsNotEmpty()
@IsArray()
@ArrayMinSize(1)
@Transform(({ value }) => value.split(',').map((url) => url.replace(/\/$/, '')))
@IsUrl({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this check run after Transform ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The short answer is yes. The @Transform() decorator is always executed first. Then all other validation decorators are executed.

It works this way.

  1. If the PROVIDERS_URLS is not presented in the .env file, the function in the @Transform() decorator is not called. As the default value is not assigned to the PROVIDERS_URLS variable, the @IsNotEmpty() and other decorators will return the appropriate error.

  2. If there is a value for the PROVIDERS_URLS in the .env. file (including the empty value PROVIDERS_URLS=), the function in the @Transform() decorator will be called first, and then all other validation decorators will be called.

require_protocol: true
}, {
each: true,
})
@Transform(({ value }) => toArrayOfUrls(value))
PROVIDERS_URLS!: NonEmptyArray<string>;

@IsInt()
@IsNotEmpty()
@IsEnum(Chain)
@Transform(({ value }) => parseInt(value, 10))
CHAIN_ID!: number;
CHAIN_ID!: Chain;

@IsNotEmpty()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you check how it behave now without @isnotempty() check ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we don't set IsNotEmpty() here it will work as follows.

  1. If the DB_HOST variable is not presented in the .env file, the validation will throw an error, because undefined is not a string.

  2. If a user sets an empty string in the .env file like this: DB_HOST=, the validation error will not be thrown, because the empty string is a string, everything is OK.

I don't think that we want to allow empty strings here.

@IsString()
DB_HOST!: string;

@IsNotEmpty()
@IsString()
DB_USER!: string;

@IsOptional()
@IsString()
@IsNotEmpty()
@IsString()
DB_PASSWORD!: string;

@ValidateIf((e) => !e.DB_PASSWORD)
@IsString()
@IsNotEmpty()
DB_PASSWORD_FILE!: string;

@IsNotEmpty()
@IsString()
DB_NAME!: string;

@IsNotEmpty()
@IsInt()
@Min(1025)
@Max(65535)
@Transform(({ value }) => parseInt(value, 10))
DB_PORT!: number;

@IsOptional()
@IsInt()
@Transform(({ value }) => parseInt(value, 10))
@IsPositive()
@Transform(toNumber({ defaultValue: 100 }))
PROVIDER_JSON_RPC_MAX_BATCH_SIZE = 100;

@IsOptional()
@IsInt()
@Transform(({ value }) => parseInt(value, 10))
@IsPositive()
@Transform(toNumber({ defaultValue: 5 }))
PROVIDER_CONCURRENT_REQUESTS = 5;

@IsOptional()
@IsInt()
@Transform(({ value }) => parseInt(value, 10))
@IsPositive()
@Transform(toNumber({ defaultValue: 10 }))
PROVIDER_BATCH_AGGREGATION_WAIT_MS = 10;

// Enable endpoints that use CL API for ejector
@IsOptional()
@IsBoolean()
@Transform(({ value }) => toBoolean(value))
@Transform(toBoolean({ defaultValue: true }))
VALIDATOR_REGISTRY_ENABLE = true;

@ValidateIf((e) => e.VALIDATOR_REGISTRY_ENABLE === true)
@ValidateIf((e) => e.VALIDATOR_REGISTRY_ENABLE)
@IsNotEmpty()
@IsArray()
@ArrayMinSize(1)
@Transform(({ value }) => value.split(',').map((url) => url.replace(/\/$/, '')))
@IsUrl({
require_protocol: true,
}, {
each: true,
})
@Transform(({ value }) => toArrayOfUrls(value))
CL_API_URLS: string[] = [];

@IsOptional()
@IsInt()
@Transform(({ value }) => parseInt(value, 10))
@IsPositive()
@Transform(toNumber({ defaultValue: 5000 }))
UPDATE_KEYS_INTERVAL_MS = 5000;

@IsOptional()
@IsInt()
@Transform(({ value }) => parseInt(value, 10))
@IsPositive()
@Transform(toNumber({ defaultValue: 10000 }))
UPDATE_VALIDATORS_INTERVAL_MS = 10000;

@IsOptional()
@IsInt()
@IsPositive()
@Transform(({ value }) => parseInt(value, 10))
@Transform(toNumber({ defaultValue: 1100 }))
KEYS_FETCH_BATCH_SIZE = 1100;
}

Expand Down
6 changes: 6 additions & 0 deletions src/common/config/interfaces/environment.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@ export enum LogFormat {
json = 'json',
simple = 'simple',
}

export enum Chain {
Mainnet = 1,
Goerli = 5,
Holesky = 17000,
}
Loading