Skip to content
Merged
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
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ Unless you need to set a non-default value, it is recommended to only populate o
| `OPCODELOGGER_ENABLED` | "true" | Whether the `opcodeLogger` tracer is enabled for a call to `debug_traceTransaction`. This setting should match the value `hiero.mirror.web3.opcode.tracer.enabled` in the Mirror Node used. See [HIP-801](https://hips.hedera.com/hip/hip-801) for more information. |
| `PAYMASTER_ENABLED` | "false" | Flag to enable or disable the Paymaster functionally |
| `PAYMASTER_WHITELIST` | "[]" | List of "to" addresses that will have fully subsidized transactions if the gasPrice was set to 0 by the signer |
| `PAYMASTER_ACCOUNTS` | "[]" | List of potential paymaster accounts that can be used alongside or instead of the default operator. Allows multiple paymasters without deploying separate instances per contract or address. Each entry defines [[accountId, type ("HEX_ECDSA", "HEX_ED25519"), key, allowance], [account, type, key, allowance]], e.g. `PAYMASTER_ACCOUNTS=[["0.0.9303","HEX_ECDSA","0x0000000000000000000000000000000000000000000000000000000000000000","80"],["0.0.5644","HEX_ECDSA","0x0000000000000000000000000000000000000000000000000000000000000000","100"]]` |
| `PAYMASTER_ACCOUNTS` | "[]" | List of potential paymaster accounts that can be used alongside or instead of the default operator. Allows multiple paymasters without deploying separate instances per contract or address. Each entry defines [[accountId, type ("HEX_ECDSA", "HEX_ED25519"), key (both DER 48 bytes for ED25519 or 50 bytes for ECDSA, and 0x prefixed HEX are supported), allowanceInHBAR], [account, type, key, allowanceInHBAR]], e.g. `PAYMASTER_ACCOUNTS=[["0.0.9303","HEX_ECDSA","0x0000000000000000000000000000000000000000000000000000000000000000","80"],["0.0.5644","HEX_ECDSA","0x0000000000000000000000000000000000000000000000000000000000000000","350"]]` |
| `PAYMASTER_ACCOUNTS_WHITELISTS` | "[]" | Defines the address (smart contract or account) whitelists for each paymaster account. Each entry maps a paymaster account to an array of addresses it can pay for. Duplicates are overridden by the last configured paymaster. Each entry defines [[accountId, [addressA, addressB]], e.g. `PAYMASTER_ACCOUNTS_WHITELISTS=[["0.0.9303",["0x0000000000000000000000000000000000000062","0x0000000000000000000000000000000000000320"]],["0.0.5644",["0x0000000000000000000000000000000000000001"]]]` |
| `READ_ONLY` | "false" | Starts the JSON-RPC Relay in Read-Only mode. In Read-Only mode, write operations, _e.g._, `eth_sendRawTransaction` or query operations to the Consensus Node will trigger an `Unsupported operation` error. |
| `REDIS_ENABLED` | "true" | Enable usage of Redis as shared cache |
Expand Down
49 changes: 49 additions & 0 deletions packages/config-service/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ export class ConfigService {

this.validateReadOnlyMode();

this.validatePaymasterAccounts();

// note: temporary bandage solution
// should be replaced after https://github.com/hiero-ledger/hiero-json-rpc-relay/issues/4840 is implemented
if (this.get('MIRROR_NODE_TIMESTAMP_SLICING_MAX_LOGS_PER_SLICE') === 0) {
Expand Down Expand Up @@ -142,6 +144,53 @@ export class ConfigService {
}
}

private validatePaymasterAccounts() {
const paymasterAccounts = this.get('PAYMASTER_ACCOUNTS');
if (!paymasterAccounts.length) {
return;
}

// regex for realm.shard.num
const accountIdRegex: RegExp = /^\d+\.\d+\.\d+$/;
// regex for 32 bytes 0x prefixed private key
const hexKeyRegex: RegExp = /^0x[a-fA-F0-9]{64}$/;
// regex for DER encoded private keys handling both:
// - ECDSA (50 bytes) - curve OID + ec private key structure + optional public key
// - Ed25519 (48 bytes) - simpler ASN.1, no curve parameters
const derKeyRegex = /^(?:[a-fA-F0-9]{96}|[a-fA-F0-9]{100})$/;
paymasterAccounts.forEach((entry, i) => {
if (!Array.isArray(entry) || entry.length !== 4) {
throw new Error(`PAYMASTER_ACCOUNTS: Entry ${i} must be an array of 4 elements`);
}
const [accountId, keyType, privateKey, allowanceInHBAR] = entry;

// account id in format realm.shard.num
if (!accountIdRegex.test(accountId)) {
throw new Error(
`PAYMASTER_ACCOUNTS: Entry ${i}: invalid account id format, required format is realm.shard.num`,
);
}

// key type
if (!['HEX_ECDSA', 'HEX_ED25519'].includes(keyType)) {
throw new Error(`PAYMASTER_ACCOUNTS: Entry ${i}: key type must be HEX_ECDSA or HEX_ED25519`);
}

// 0x prefixed hex or der private key
if (!hexKeyRegex.test(privateKey) && !derKeyRegex.test(privateKey)) {
throw new Error(
`PAYMASTER_ACCOUNTS: Entry ${i}: invalid private key format, it must be 0x prefixed hex or der encoded (48 or 50 bytes)`,
);
}

// allowanceInHBAR as integer
const w = Number(allowanceInHBAR);
if (!Number.isInteger(w) || w < 1) {
throw new Error(`PAYMASTER_ACCOUNTS: Entry ${i}: allowanceInHBAR must be an integer >= 1`);
}
});
}

private get<K extends ConfigKey>(name: K): GetTypeOfConfigKey<K> {
const configEntry = GlobalConfig.ENTRIES[name];
let value = this.envs[name] == undefined ? configEntry?.defaultValue : this.envs[name];
Expand Down
51 changes: 41 additions & 10 deletions packages/config-service/src/services/loggerService.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,59 @@
// SPDX-License-Identifier: Apache-2.0

import { ConfigKey, GlobalConfig } from './globalConfig';
import { ConfigKey } from './globalConfig';

export class LoggerService {
public static readonly SENSITIVE_FIELDS: ConfigKey[] = ['OPERATOR_KEY_MAIN', 'GITHUB_TOKEN', 'GH_ACCESS_TOKEN'];
/**
* Unified map of sensitive fields.
*
* Key: configuration field name.
* Value:
* - `true` - entire value is sensitive
* - `number[]` - positions of sensitive fields in array values
*/
public static readonly SENSITIVE_FIELDS_MAP: Map<ConfigKey, number[] | true> = new Map([
// Fields where the whole value is sensitive
['OPERATOR_KEY_MAIN', true],
['GITHUB_TOKEN', true],
['GH_ACCESS_TOKEN', true],

// Fields where only certain positions in arrays are sensitive
['PAYMASTER_ACCOUNTS', [2]],
] as [ConfigKey, true | number[]][]);

/**
* RegExp to detect GitHub-style secrets in string values.
*/
public static readonly GITHUB_SECRET_PATTERN: RegExp =
/^(gh[pousr]_[a-zA-Z0-9]{36,251}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})$/;

/**
* Hide sensitive information
* Hide sensitive configuration values.
*
* @param envName
* @param envValue
* @param envName - the configuration key
* @param envValue - the value, either string or array of arrays of strings
* @returns masked string representation of the environment variable
*/
static maskUpEnv(envName: string, envValue: string | undefined): string {
const isSensitiveField: boolean = (this.SENSITIVE_FIELDS as string[]).indexOf(envName) > -1;
const isKnownSecret: boolean =
GlobalConfig.ENTRIES[envName].type === 'string' && !!this.GITHUB_SECRET_PATTERN.exec(envValue ?? '');
static maskUpEnv(envName: string, envValue: string | undefined | string[][]): string {
// explicitly listed as sensitive
const sensitiveInfo = this.SENSITIVE_FIELDS_MAP.get(envName as ConfigKey);
if (sensitiveInfo === true) {
return `${envName} = **********`;
}

// certain positions are sensitive in array values
if (Array.isArray(sensitiveInfo) && sensitiveInfo.length) {
return `${envName} = ${(envValue as string[][]).map(
(a) => `[${a.map((v, k) => (sensitiveInfo.includes(k) ? `**********` : v))}]`,
)}`;
}

if (isSensitiveField || isKnownSecret) {
// handle GitHub tokens
if (typeof envValue === 'string' && !!this.GITHUB_SECRET_PATTERN.exec(envValue ?? '')) {
return `${envName} = **********`;
}

// Not sensitive
return `${envName} = ${envValue}`;
}
}
120 changes: 116 additions & 4 deletions packages/config-service/tests/src/services/configService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,122 @@ describe('ConfigService tests', async function () {
const envs = ConfigService.getAllMasked();
expect(envs).to.not.be.empty;

for (const sensitiveField of LoggerService.SENSITIVE_FIELDS) {
if (envs[sensitiveField]) {
expect(envs[sensitiveField]).to.equal('**********');
LoggerService.SENSITIVE_FIELDS_MAP.forEach((value, key) => {
if (envs[key]) {
expect(envs[key]).to.contains(`**********`);
}
}
});
});

describe('validatePaymasterAccounts', () => {
let initialPaymasterAccounts;

before(() => {
initialPaymasterAccounts = ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'];
});

after(() => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = initialPaymasterAccounts;
});

it('should validate a correct config', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.0.8031491', 'HEX_ECDSA', '0x0000000000000000000000000000000000000000000000000000000000000000', '80'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.not.throw();
});

it('should throw on invalid account id format', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.8031491', 'HEX_ECDSA', '0x0000000000000000000000000000000000000000000000000000000000000000', '80'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.throw(
'PAYMASTER_ACCOUNTS: Entry 0: invalid account id format, required format is realm.shard.num',
);
});

it('should throw on invalid key type', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.0.8031491', 'RSA', '0x0000000000000000000000000000000000000000000000000000000000000000', '80'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.throw(
'PAYMASTER_ACCOUNTS: Entry 0: key type must be HEX_ECDSA or HEX_ED25519',
);
});

it('should throw on invalid hex private key', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.0.8031491', 'HEX_ECDSA', '0x1234', '80'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.throw(
'PAYMASTER_ACCOUNTS: Entry 0: invalid private key format, it must be 0x prefixed hex or der encoded (48 or 50 bytes)',
);
});

it('should throw on invalid der private key', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.0.8031491', 'HEX_ECDSA', '30300201003', '80'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.throw(
'PAYMASTER_ACCOUNTS: Entry 0: invalid private key format, it must be 0x prefixed hex or der encoded (48 or 50 bytes)',
);
});

it('should pass on valid hex private key', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.0.8031491', 'HEX_ECDSA', '0x0000000000000000000000000000000000000000000000000000000000000000', '80'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.not.throw();
});

it('should pass on valid der ecdsa private key', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
[
'0.0.8031491',
'HEX_ECDSA',
'3030020100300706052b8104000a0000000000000caeb6079ce700000a695000000e438f8e51a40000000000000000000000',
'80',
],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.not.throw();
});

it('should pass on valid der ed25519 private key', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
[
'0.0.8031491',
'HEX_ECDSA',
'303002010030072b8104000a0000000000000caeb6079ce700000a695000000e438f8e51a40000000000000000000000',
'80',
],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.not.throw();
});

it('should throw on invalid allowanceInHBAR', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [
['0.0.8031491', 'HEX_ECDSA', '0x0000000000000000000000000000000000000000000000000000000000000000', '0'],
] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.throw(
'PAYMASTER_ACCOUNTS: Entry 0: allowanceInHBAR must be an integer >= 1',
);
});

it('should throw if payment account array length is incorrect', () => {
ConfigService['getInstance']()['envs']['PAYMASTER_ACCOUNTS'] = [['0.0.8031491', 'HEX_ECDSA']] as any;

expect(() => ConfigService['getInstance']()['validatePaymasterAccounts']()).to.throw(
'PAYMASTER_ACCOUNTS: Entry 0 must be an array of 4 element',
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ chai.use(chaiAsPromised);

describe('LoggerService tests', async function () {
it('should be able to mask sensitive information', async () => {
for (const sensitiveField of LoggerService.SENSITIVE_FIELDS) {
const hex = crypto.randomBytes(32).toString('hex');
const res = LoggerService.maskUpEnv(sensitiveField, hex);
expect(res).to.equal(`${sensitiveField} = **********`);
}
LoggerService.SENSITIVE_FIELDS_MAP.forEach((value, key) => {
if (value === true) {
const res = LoggerService.maskUpEnv(key, crypto.randomBytes(32).toString('hex'));
expect(res).to.equal(`${key} = **********`);
}
});
});

it('should be able to return plain information', async () => {
Expand All @@ -24,4 +25,30 @@ describe('LoggerService tests', async function () {

expect(LoggerService.maskUpEnv(envName, res)).to.equal(`${envName} = ${res}`);
});

it('should mask private keys in PAYMASTER_ACCOUNTS', async () => {
const paymaster0 = [
'0.0.801',
'HEX_ECDSA',
'0x1111111111111111111111111111111111111111111111111111111111111111',
'300',
];
const paymaster1 = [
'0.0.802',
'HEX_ECDSA',
'0x2222222222222222222222222222222222222222222222222222222222222222',
'200',
];
const res = LoggerService.maskUpEnv('PAYMASTER_ACCOUNTS', [paymaster0, paymaster1]);

expect(res).to.contain(paymaster0[0]);
expect(res).to.contain(paymaster1[0]);
expect(res).to.contain(paymaster0[3]);
expect(res).to.contain(paymaster1[3]);

expect(res.match(/\*{10}/g).length).to.equal(2);
expect(res.match(/HEX_ECDSA/g).length).to.equal(2);
expect(res).to.not.contain(paymaster0[2]);
expect(res).to.not.contain(paymaster1[2]);
});
});
2 changes: 1 addition & 1 deletion packages/relay/src/lib/clients/sdkClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export class SDKClient {
true,
originalCallerAddress,
undefined,
paymasterInfo ? this.paymasterClients.get(paymasterInfo.accountId!) : this.clientMain,
paymasterInfo?.accountId ? this.paymasterClients.get(paymasterInfo.accountId) : undefined,
),
};
}
Expand Down
Loading
Loading