Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

centralized handlebar client + new helpers

Matheus Nogueiraa00c8b07c7a2
diff --git a/backend/src/ee/services/dynamic-secret/providers/aws-elasticache.ts b/backend/src/ee/services/dynamic-secret/providers/aws-elasticache.ts
index 6cf5c9c9fd..ed11e1a393 100644
--- a/backend/src/ee/services/dynamic-secret/providers/aws-elasticache.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/aws-elasticache.ts
@@ -8,11 +8,11 @@ import {
ModifyReplicationGroupCommand,
ModifyUserGroupCommand
} from "@aws-sdk/client-elasticache";
-import handlebars from "handlebars";
import { customAlphabet } from "nanoid";
import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { CustomAWSHasher } from "@app/lib/aws/hashing";
import { crypto } from "@app/lib/crypto";
import { BadRequestError } from "@app/lib/errors";
@@ -211,7 +211,7 @@ export const AwsElastiCacheDatabaseProvider = (): TDynamicProviderFns => {
const leasePassword = generatePassword();
const leaseExpiration = new Date(expireAt).toISOString();
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username: leaseUsername,
password: leasePassword,
expiration: leaseExpiration
@@ -255,7 +255,7 @@ export const AwsElastiCacheDatabaseProvider = (): TDynamicProviderFns => {
const revoke = async (inputs: unknown, entityId: string) => {
const providerInputs = await validateProviderInputs(inputs);
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username: entityId
});
const parsedStatement = DeleteElasticCacheUserSchema.parse(JSON.parse(revokeStatement));
diff --git a/backend/src/ee/services/dynamic-secret/providers/aws-memorydb.ts b/backend/src/ee/services/dynamic-secret/providers/aws-memorydb.ts
index 93c8b4ccaf..626b421a64 100644
--- a/backend/src/ee/services/dynamic-secret/providers/aws-memorydb.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/aws-memorydb.ts
@@ -5,11 +5,11 @@ import {
MemoryDB,
UpdateACLCommand
} from "@aws-sdk/client-memorydb";
-import handlebars from "handlebars";
import { customAlphabet } from "nanoid";
import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { CustomAWSHasher } from "@app/lib/aws/hashing";
import { crypto } from "@app/lib/crypto";
import { BadRequestError } from "@app/lib/errors";
@@ -188,7 +188,7 @@ export const AwsMemoryDbDatabaseProvider = (): TDynamicProviderFns => {
const leasePassword = generatePassword();
const leaseExpiration = new Date(expireAt).toISOString();
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username: leaseUsername,
password: leasePassword,
expiration: leaseExpiration
@@ -230,7 +230,7 @@ export const AwsMemoryDbDatabaseProvider = (): TDynamicProviderFns => {
const providerInputs = await validateProviderInputs(inputs);
const credentials = $getAwsCredentials(providerInputs);
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username: entityId
});
const parsedStatement = DeleteMemoryDbUserSchema.parse(JSON.parse(revokeStatement));
diff --git a/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts
index 4a50ebe13c..806de90eae 100644
--- a/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts
@@ -1,8 +1,9 @@
-import handlebars from "handlebars";
import knex from "knex";
import RE2 from "re2";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
@@ -302,7 +303,7 @@ export const AzureSqlDatabaseProvider = ({
);
try {
- const masterCreationStatement = handlebars.compile(providerInputs.masterCreationStatement, { noEscape: true })({
+ const masterCreationStatement = createHandlebarsClient().compile(providerInputs.masterCreationStatement, { noEscape: true })({
username,
password,
expiration,
@@ -336,7 +337,7 @@ export const AzureSqlDatabaseProvider = ({
});
try {
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration,
@@ -377,7 +378,7 @@ export const AzureSqlDatabaseProvider = ({
const { database, masterDatabase } = providerInputs;
const gatewayCallback = async (host = providerInputs.host, port = providerInputs.port) => {
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username,
database
});
@@ -500,7 +501,7 @@ export const AzureSqlDatabaseProvider = ({
const expiration = new Date(expireAt).toISOString();
const { database } = providerInputs;
- const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({
username: entityId,
expiration,
database
diff --git a/backend/src/ee/services/dynamic-secret/providers/cassandra.ts b/backend/src/ee/services/dynamic-secret/providers/cassandra.ts
index 79160924b7..32de19afda 100644
--- a/backend/src/ee/services/dynamic-secret/providers/cassandra.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/cassandra.ts
@@ -1,8 +1,9 @@
import cassandra from "cassandra-driver";
-import handlebars from "handlebars";
import { customAlphabet } from "nanoid";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
@@ -109,7 +110,7 @@ export const CassandraProvider = (): TDynamicProviderFns => {
try {
const expiration = new Date(expireAt).toISOString();
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration,
@@ -148,7 +149,7 @@ export const CassandraProvider = (): TDynamicProviderFns => {
const { keyspace } = providerInputs;
try {
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username,
keyspace
});
@@ -185,7 +186,7 @@ export const CassandraProvider = (): TDynamicProviderFns => {
try {
const expiration = new Date(expireAt).toISOString();
- const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({
username: entityId,
keyspace,
expiration
diff --git a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts b/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts
index 42e38690d0..2829044562 100644
--- a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts
@@ -1,8 +1,8 @@
import { createClient } from "@clickhouse/client";
-import handlebars from "handlebars";
import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
@@ -278,7 +278,7 @@ export const ClickhouseProvider = ({
try {
const expiration = new Date(expireAt).toISOString();
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration,
@@ -323,7 +323,7 @@ export const ClickhouseProvider = ({
});
try {
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username,
database
});
@@ -368,7 +368,7 @@ export const ClickhouseProvider = ({
const { database } = providerInputs;
try {
- const renewStatement = handlebars.compile(providerInputs.renewStatement as string, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement as string, { noEscape: true })({
username: entityId,
expiration,
database
diff --git a/backend/src/ee/services/dynamic-secret/providers/ldap.ts b/backend/src/ee/services/dynamic-secret/providers/ldap.ts
index 7f2312c8d3..9c7c82d46e 100644
--- a/backend/src/ee/services/dynamic-secret/providers/ldap.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/ldap.ts
@@ -1,8 +1,9 @@
import ldapjs from "@infisical/ldapjs";
-import handlebars from "handlebars";
import ldif from "ldif";
import { customAlphabet } from "nanoid";
import RE2 from "re2";
+
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
@@ -42,7 +43,7 @@ const generateLDIF = ({
EncodedPassword: encodePassword(password)
};
- const renderTemplate = handlebars.compile(ldifTemplate);
+ const renderTemplate = createHandlebarsClient().compile(ldifTemplate);
const renderedLdif = renderTemplate(data);
return renderedLdif;
diff --git a/backend/src/ee/services/dynamic-secret/providers/redis.ts b/backend/src/ee/services/dynamic-secret/providers/redis.ts
index 9860363346..9bfe5f7a17 100644
--- a/backend/src/ee/services/dynamic-secret/providers/redis.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/redis.ts
@@ -1,8 +1,9 @@
-import handlebars from "handlebars";
import { Redis } from "ioredis";
import { customAlphabet } from "nanoid";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
@@ -147,7 +148,7 @@ export const RedisDatabaseProvider = (): TDynamicProviderFns => {
const password = generatePassword();
const expiration = new Date(expireAt).toISOString();
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration
@@ -177,7 +178,7 @@ export const RedisDatabaseProvider = (): TDynamicProviderFns => {
const username = entityId;
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({ username });
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({ username });
const queries = revokeStatement.toString().split(";").filter(Boolean);
try {
@@ -205,7 +206,7 @@ export const RedisDatabaseProvider = (): TDynamicProviderFns => {
const username = entityId;
const expiration = new Date(expireAt).toISOString();
- const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({
username,
expiration
});
diff --git a/backend/src/ee/services/dynamic-secret/providers/sap-ase.ts b/backend/src/ee/services/dynamic-secret/providers/sap-ase.ts
index c5da910b74..413b67fdbc 100644
--- a/backend/src/ee/services/dynamic-secret/providers/sap-ase.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/sap-ase.ts
@@ -1,8 +1,9 @@
-import handlebars from "handlebars";
import { customAlphabet } from "nanoid";
import odbc from "odbc";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
@@ -116,7 +117,7 @@ export const SapAseProvider = (): TDynamicProviderFns => {
const client = await $getClient(providerInputs);
const masterClient = await $getClient(providerInputs, true);
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password
});
@@ -148,7 +149,7 @@ export const SapAseProvider = (): TDynamicProviderFns => {
const revoke = async (inputs: unknown, username: string) => {
const providerInputs = await validateProviderInputs(inputs);
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username
});
diff --git a/backend/src/ee/services/dynamic-secret/providers/sap-hana.ts b/backend/src/ee/services/dynamic-secret/providers/sap-hana.ts
index ffb25d53bc..bfd6b72304 100644
--- a/backend/src/ee/services/dynamic-secret/providers/sap-hana.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/sap-hana.ts
@@ -4,11 +4,12 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
-import handlebars from "handlebars";
import hdb from "hdb";
import { customAlphabet } from "nanoid";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
@@ -117,7 +118,7 @@ export const SapHanaProvider = (): TDynamicProviderFns => {
const expiration = new Date(expireAt).toISOString();
const client = await $getClient(providerInputs);
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration
@@ -149,7 +150,7 @@ export const SapHanaProvider = (): TDynamicProviderFns => {
const revoke = async (inputs: unknown, username: string) => {
const providerInputs = await validateProviderInputs(inputs);
const client = await $getClient(providerInputs);
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({ username });
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({ username });
const queries = revokeStatement.toString().split(";").filter(Boolean);
try {
for await (const query of queries) {
@@ -183,7 +184,7 @@ export const SapHanaProvider = (): TDynamicProviderFns => {
try {
const expiration = new Date(expireAt).toISOString();
- const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({
username: entityId,
expiration
});
diff --git a/backend/src/ee/services/dynamic-secret/providers/snowflake.ts b/backend/src/ee/services/dynamic-secret/providers/snowflake.ts
index d8ed94921b..ba9270e0d6 100644
--- a/backend/src/ee/services/dynamic-secret/providers/snowflake.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/snowflake.ts
@@ -1,8 +1,9 @@
-import handlebars from "handlebars";
import { customAlphabet } from "nanoid";
import snowflake from "snowflake-sdk";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
@@ -109,7 +110,7 @@ export const SnowflakeProvider = (): TDynamicProviderFns => {
try {
const expiration = getDaysToExpiry(new Date(expireAt));
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration
@@ -146,7 +147,7 @@ export const SnowflakeProvider = (): TDynamicProviderFns => {
const client = await $getClient(providerInputs);
try {
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({ username });
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({ username });
await new Promise((resolve, reject) => {
client.execute({
@@ -181,7 +182,7 @@ export const SnowflakeProvider = (): TDynamicProviderFns => {
try {
const expiration = getDaysToExpiry(new Date(expireAt));
- const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({
username: entityId,
expiration
});
diff --git a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts
index 717a9b5d53..496c1e6582 100644
--- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts
@@ -1,8 +1,9 @@
-import handlebars from "handlebars";
import knex from "knex";
import RE2 from "re2";
import { z } from "zod";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+
import { TDynamicSecrets } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
@@ -321,7 +322,7 @@ export const SqlDatabaseProvider = ({
try {
const expiration = new Date(expireAt).toISOString();
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password,
expiration,
@@ -367,7 +368,7 @@ export const SqlDatabaseProvider = ({
originalHost: providerInputs.host
});
try {
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username,
database
});
@@ -412,7 +413,7 @@ export const SqlDatabaseProvider = ({
const expiration = new Date(expireAt).toISOString();
const { database } = providerInputs;
- const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({
+ const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({
username: entityId,
expiration,
database
diff --git a/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts b/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts
index fbd891e842..f54dad7d89 100644
--- a/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts
@@ -1,60 +1,14 @@
/* eslint-disable func-names */
-import handlebars from "handlebars";
import { customAlphabet } from "nanoid";
-import RE2 from "re2";
import { TDynamicSecrets } from "@app/db/schemas/dynamic-secrets";
import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";
import { DynamicSecretProviders, DynamicSecretSqlDBSchema, SqlProviders } from "./models";
-const hbsReplace = (text: string, searchValue: string, replaceValue: string) => {
- // Convert to string if it's not already
- const textStr = String(text || "");
- if (!textStr) {
- return textStr;
- }
-
- try {
- const re2Pattern = new RE2(searchValue, "g");
- // Replace all occurrences
- return re2Pattern.replace(textStr, replaceValue);
- } catch (error) {
- logger.error(error, "RE2 pattern failed, using original template");
- return textStr;
- }
-};
-
-const hbsRandom = (length: number) => {
- if (typeof length !== "number" || length <= 0 || length > 100) {
- return "";
- }
- return alphaNumericNanoId(length);
-};
-
-const hbsTruncate = (text: string, length: number) => {
- const textStr = String(text || "");
- if (!textStr) {
- return textStr;
- }
-
- if (typeof length !== "number" || length <= 0) return textStr;
- return textStr.substring(0, length);
-};
-
-const hbsUppercase = (text: string) => {
- const textStr = String(text || "");
- return textStr.toUpperCase();
-};
-
-const hbsLowercase = (text: string) => {
- const textStr = String(text || "");
- return textStr.toLowerCase();
-};
-
const compileUsernameTemplate = ({
usernameTemplate,
randomUsername,
@@ -72,22 +26,8 @@ const compileUsernameTemplate = ({
toUpperCase?: boolean;
};
}): string => {
- // Create isolated handlebars instance
- const hbs = handlebars.create();
-
- // Register random helper on local instance
- hbs.registerHelper("random", hbsRandom);
- // Register replace helper on local instance
- hbs.registerHelper("replace", hbsReplace);
- // Register truncate helper on local instance
- hbs.registerHelper("truncate", hbsTruncate);
-
- // Register uppercase helper on local instance
- hbs.registerHelper("uppercase", hbsUppercase);
- // Register lowercase helper on local instance
- hbs.registerHelper("lowercase", hbsLowercase);
-
- // Compile template with context using local instance
+ const hbs = createHandlebarsClient();
+
const context = {
randomUsername,
unixTimestamp,
diff --git a/backend/src/ee/services/dynamic-secret/providers/vertica.ts b/backend/src/ee/services/dynamic-secret/providers/vertica.ts
index 759417285c..583aa047dd 100644
--- a/backend/src/ee/services/dynamic-secret/providers/vertica.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/vertica.ts
@@ -1,8 +1,8 @@
-import handlebars from "handlebars";
import knex, { Knex } from "knex";
import { z } from "zod";
import { crypto } from "@app/lib/crypto/cryptography";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { BadRequestError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
@@ -127,7 +127,7 @@ const generateUsername = (usernameTemplate?: string | null) => {
const randomUsername = `inf_${alphaNumericNanoId(25)}`; // Username must start with an ascii letter, so we prepend the username with "inf-"
if (!usernameTemplate) return randomUsername;
- return handlebars.compile(usernameTemplate)({
+ return createHandlebarsClient().compile(usernameTemplate)({
randomUsername,
unixTimestamp: Math.floor(Date.now() / 100)
});
@@ -286,7 +286,7 @@ export const VerticaProvider = ({
try {
client = await $getClient({ ...providerInputs, hostIp: host, port });
- const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({
+ const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({
username,
password
});
@@ -332,7 +332,7 @@ export const VerticaProvider = ({
try {
client = await $getClient({ ...providerInputs, hostIp: host, port });
- const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({
+ const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({
username
});
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index ec03fd9121..6eac4b166b 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -1,7 +1,6 @@
import { createMongoAbility, ForbiddenError, MongoAbility, RawRuleOf, subject } from "@casl/ability";
import { PackRule, packRules, unpackRules } from "@casl/ability/extra";
import { requestContext } from "@fastify/request-context";
-import handlebars from "handlebars";
import {
AccessScope,
@@ -77,6 +76,8 @@ import {
ProjectPermissionSet,
ProjectPermissionSub
} from "./project-permission";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
+import { logger } from "@app/lib/logger";
// Returns the delegated OAuth scopes for the current request, or undefined when this is not an
// OAuth-delegated request. The distinction matters: a returned array (even empty) means scope
@@ -621,7 +622,7 @@ export const permissionServiceFactory = ({
}
const rules = buildProjectPermissionRules(permissionFromRoles);
- const templatedRules = handlebars.compile(JSON.stringify(rules), { data: false });
+ const templatedRules = createHandlebarsClient().compile(JSON.stringify(rules), { data: false });
const unescapedMetadata = objectify(
permissionData?.[0]?.metadata,
(i) => i.key,
@@ -823,7 +824,7 @@ export const permissionServiceFactory = ({
})) || [];
const rules = buildProjectPermissionRules(rolePermissions.concat(additionalPrivileges));
- const templatedRules = handlebars.compile(JSON.stringify(rules), { data: false });
+ const templatedRules = createHandlebarsClient().compile(JSON.stringify(rules), { data: false });
const metadataKeyValuePair = escapeHandlebarsMissingDict(
objectify(
userProjectPermission.metadata,
@@ -869,7 +870,7 @@ export const permissionServiceFactory = ({
})) || [];
const rules = buildProjectPermissionRules(rolePermissions.concat(additionalPrivileges));
- const templatedRules = handlebars.compile(JSON.stringify(rules), { data: false });
+ const templatedRules = createHandlebarsClient().compile(JSON.stringify(rules), { data: false });
const metadataKeyValuePair = escapeHandlebarsMissingDict(
objectify(
identityProjectPermission.metadata,
diff --git a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts
index 457bf0c105..1a0ded60d4 100644
--- a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts
@@ -1,4 +1,3 @@
-import handlebars from "handlebars";
import { Knex } from "knex";
import {
@@ -10,6 +9,7 @@ import {
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
import { BadRequestError } from "@app/lib/errors";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import {
executeWithPotentialGateway,
@@ -129,7 +129,7 @@ export const sqlCredentialsRotationFactory: TRotationFactory<
const $executeQuery = async (tx: Knex, username: string, password: string) => {
if (userProvidedRotationStatement) {
- const revokeStatement = handlebars.compile(userProvidedRotationStatement)({
+ const revokeStatement = createHandlebarsClient().compile(userProvidedRotationStatement)({
username,
password,
database: connection.credentials.database
diff --git a/backend/src/lib/template/handlebars-client.ts b/backend/src/lib/template/handlebars-client.ts
new file mode 100644
index 0000000000..6ec72dd010
--- /dev/null
+++ b/backend/src/lib/template/handlebars-client.ts
@@ -0,0 +1,73 @@
+import handlebars from "handlebars";
+import RE2 from "re2";
+
+import { logger } from "@app/lib/logger";
+import { alphaNumericNanoId } from "@app/lib/nanoid";
+
+export function createHandlebarsClient() {
+ const hbs = handlebars.create();
+
+ hbs.registerHelper("random", hbsRandom);
+ hbs.registerHelper("replace", hbsReplace);
+ hbs.registerHelper("truncate", hbsTruncate);
+ hbs.registerHelper("uppercase", hbsUppercase);
+ hbs.registerHelper("lowercase", hbsLowercase);
+ hbs.registerHelper('substr', hbsSubstr);
+ hbs.registerHelper("stripPrefix", hbsStripPrefix);
+
+ return hbs;
+}
+
+const hbsReplace = (text: string, searchValue: string, replaceValue: string) => {
+ // Convert to string if it's not already
+ const textStr = String(text || "");
+ if (!textStr) {
+ return textStr;
+ }
+
+ try {
+ const re2Pattern = new RE2(searchValue, "g");
+ // Replace all occurrences
+ return re2Pattern.replace(textStr, replaceValue);
+ } catch (error) {
+ logger.error(error, "RE2 pattern failed, using original template");
+ return textStr;
+ }
+};
+
+const hbsRandom = (length: number) => {
+ if (typeof length !== "number" || length <= 0 || length > 100) {
+ return "";
+ }
+ return alphaNumericNanoId(length);
+};
+
+const hbsTruncate = (text: string, length: number) => {
+ const textStr = String(text || "");
+ if (!textStr) {
+ return textStr;
+ }
+
+ if (typeof length !== "number" || length <= 0) return textStr;
+ return textStr.substring(0, length);
+};
+
+const hbsUppercase = (text: string) => {
+ const textStr = String(text || "");
+ return textStr.toUpperCase();
+};
+
+const hbsLowercase = (text: string) => {
+ const textStr = String(text || "");
+ return textStr.toLowerCase();
+};
+
+const hbsSubstr = (text: string, start: number, end?: number) => {
+ const endIndex = end && typeof end === 'number' ? end : undefined;
+ return text.substring(start, endIndex);
+}
+
+const hbsStripPrefix = (text: string, prefix: string) => {
+ logger.info({prefix: prefix ?? 'no-prefix', text}, "stripPrefix");
+ return text.startsWith(prefix) ? text.substring(prefix.length) : text;
+}
\ No newline at end of file
diff --git a/backend/src/lib/template/validate-handlebars.ts b/backend/src/lib/template/validate-handlebars.ts
index 133027be3b..dfcec21ff6 100644
--- a/backend/src/lib/template/validate-handlebars.ts
+++ b/backend/src/lib/template/validate-handlebars.ts
@@ -1,7 +1,6 @@
-import handlebars from "handlebars";
-
import { BadRequestError } from "../errors";
import { logger } from "../logger";
+import { createHandlebarsClient } from "./handlebars-client";
type SanitizationArg = {
allowedExpressions?: (arg: string) => boolean;
@@ -9,7 +8,7 @@ type SanitizationArg = {
const isValidExpression = (expression: string, dto: SanitizationArg): boolean => {
// Allow helper functions (replace, truncate)
- const allowedHelpers = ["replace", "truncate", "random", "uppercase", "lowercase"];
+ const allowedHelpers = ["replace", "truncate", "random", "uppercase", "lowercase", "substr", "stripPrefix"];
if (allowedHelpers.includes(expression)) {
return true;
}
@@ -19,7 +18,7 @@ const isValidExpression = (expression: string, dto: SanitizationArg): boolean =>
};
export const validateHandlebarTemplate = (templateName: string, template: string, dto: SanitizationArg) => {
- const parsedAst = handlebars.parse(template);
+ const parsedAst = createHandlebarsClient().parse(template);
parsedAst.body.forEach((el) => {
if (el.type === "ContentStatement") return;
if (el.type === "MustacheStatement" && "path" in el) {
@@ -32,7 +31,7 @@ export const validateHandlebarTemplate = (templateName: string, template: string
};
export const isValidHandleBarTemplate = (template: string, dto: SanitizationArg) => {
- const parsedAst = handlebars.parse(template);
+ const parsedAst = createHandlebarsClient().parse(template);
return parsedAst.body.every((el) => {
if (el.type === "ContentStatement") return true;
if (el.type === "MustacheStatement" && "path" in el) {
diff --git a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts
index 46b86c4b87..6025935f51 100644
--- a/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/f5-big-ip/f5-big-ip-pki-sync-fns.ts
@@ -1,10 +1,10 @@
/* eslint-disable no-await-in-loop */
import { AxiosError, AxiosRequestConfig } from "axios";
-import handlebars from "handlebars";
import RE2 from "re2";
import { TCertificateSyncs } from "@app/db/schemas";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { logger } from "@app/lib/logger";
import {
@@ -836,7 +836,7 @@ export const f5BigIpPkiSyncFactory = ({
} else if (certificate?.renewedFromCertificateId && !preserveItemOnRenewal) {
const certIdClean = certificateId.replace(new RE2("-", "g"), "");
if (certificateNameSchema) {
- targetName = handlebars.compile(certificateNameSchema)({
+ targetName = createHandlebarsClient().compile(certificateNameSchema)({
certificateId: certIdClean,
environment: "global"
});
diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts
index 937585926a..874811dea1 100644
--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts
@@ -1,10 +1,10 @@
/* eslint-disable no-await-in-loop */
import { AxiosError, AxiosRequestConfig } from "axios";
-import handlebars from "handlebars";
import RE2 from "re2";
import { TCertificateSyncs } from "@app/db/schemas";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { logger } from "@app/lib/logger";
import { executeNetScalerOperationWithGateway } from "@app/services/app-connection/netscaler/netscaler-connection-fns";
@@ -450,7 +450,7 @@ export const netScalerPkiSyncFactory = ({
} else if (certificate?.renewedFromCertificateId && !preserveItemOnRenewal) {
const certIdClean = certificateId.replace(new RE2("-", "g"), "");
if (certificateNameSchema) {
- targetCertKeyName = handlebars.compile(certificateNameSchema)({
+ targetCertKeyName = createHandlebarsClient().compile(certificateNameSchema)({
certificateId: certIdClean,
environment: "global"
});
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index 2895865108..f7d5f3c712 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -1,7 +1,7 @@
-import handlebars from "handlebars";
import { z, ZodSchema } from "zod";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { BadRequestError } from "@app/lib/errors";
@@ -99,7 +99,7 @@ export const applyCertificateNameSchema = (
const processedCertificateMap: TCertificateMap = {};
for (const [certificateId, value] of Object.entries(certificateMap)) {
- const newName = handlebars.compile(schema)({
+ const newName = createHandlebarsClient().compile(schema)({
certificateId,
environment
});
@@ -117,7 +117,7 @@ export const stripCertificateNameSchema = (
): TCertificateMap => {
if (!schema) return certificateMap;
- const compiledSchemaPattern = handlebars.compile(schema)({
+ const compiledSchemaPattern = createHandlebarsClient().compile(schema)({
certificateId: "{{certificateId}}",
environment
});
@@ -144,7 +144,7 @@ export const stripCertificateNameSchema = (
export const matchesCertificateNameSchema = (name: string, environment: string, schema?: string): boolean => {
if (!schema) return true;
- const compiledSchemaPattern = handlebars.compile(schema)({
+ const compiledSchemaPattern = createHandlebarsClient().compile(schema)({
certificateId: "{{certificateId}}",
environment
});
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index 6314cdc25d..c1e1283037 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -4,9 +4,9 @@ import * as x509 from "@peculiar/x509";
import { AxiosError } from "axios";
import { Job } from "bullmq";
import { randomUUID } from "crypto";
-import handlebars from "handlebars";
import { TCertificates } from "@app/db/schemas";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -297,7 +297,7 @@ export const pkiSyncQueueFactory = ({
friendlyName: cert.friendlyName || "",
environment
};
- certificateName = handlebars.compile(certificateNameSchema)(templateData);
+ certificateName = createHandlebarsClient().compile(certificateNameSchema)(templateData);
} else {
const stableId = cert.profileId
? `${cert.profileId.replace(/-/g, "")}-${(cert.commonName || "").replace(/[^a-zA-Z0-9]/g, "")}`
diff --git a/backend/src/services/secret-sync/aws-parameter-store/aws-parameter-store-sync-fns.ts b/backend/src/services/secret-sync/aws-parameter-store/aws-parameter-store-sync-fns.ts
index 695640f52b..6bc4d2f336 100644
--- a/backend/src/services/secret-sync/aws-parameter-store/aws-parameter-store-sync-fns.ts
+++ b/backend/src/services/secret-sync/aws-parameter-store/aws-parameter-store-sync-fns.ts
@@ -19,9 +19,9 @@ import {
SSMClient,
type Tag
} from "@aws-sdk/client-ssm";
-import handlebars from "handlebars";
import { isAwsError } from "@app/lib/aws/error";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
@@ -59,7 +59,7 @@ const getFullPath = ({ path, keySchema, environment }: { path: string; keySchema
throw new SecretSyncError({ message: `Key schema cannot contain leading '/'`, shouldRetry: false });
}
- const keySchemaSegments = handlebars
+ const keySchemaSegments = createHandlebarsClient()
.compile(keySchema)({
environment,
secretKey: "{{secretKey}}"
diff --git a/backend/src/services/secret-sync/secret-sync-fns.ts b/backend/src/services/secret-sync/secret-sync-fns.ts
index f860ef20a9..38f57ab132 100644
--- a/backend/src/services/secret-sync/secret-sync-fns.ts
+++ b/backend/src/services/secret-sync/secret-sync-fns.ts
@@ -1,7 +1,7 @@
import { AxiosError } from "axios";
-import handlebars from "handlebars";
import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
+import { createHandlebarsClient } from "@app/lib/template/handlebars-client";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
@@ -184,7 +184,7 @@ export const getKeyWithSchema = ({
}) => {
if (!schema) return key;
- return handlebars.compile(schema)({
+ return createHandlebarsClient().compile(schema)({
secretKey: key,
environment
});
@@ -197,7 +197,7 @@ const addSchema = (unprocessedSecretMap: TSecretMap, environment: string, schema
const processedSecretMap: TSecretMap = {};
for (const [key, value] of Object.entries(unprocessedSecretMap)) {
- const newKey = handlebars.compile(schema)({
+ const newKey = createHandlebarsClient().compile(schema)({
secretKey: key,
environment
});
@@ -212,7 +212,7 @@ const addSchema = (unprocessedSecretMap: TSecretMap, environment: string, schema
const stripSchema = (unprocessedSecretMap: TSecretMap, environment: string, schema?: string): TSecretMap => {
if (!schema) return unprocessedSecretMap;
- const compiledSchemaPattern = handlebars.compile(schema)({
+ const compiledSchemaPattern = createHandlebarsClient().compile(schema)({
secretKey: "{{secretKey}}", // Keep secretKey
environment
});
@@ -240,7 +240,7 @@ const stripSchema = (unprocessedSecretMap: TSecretMap, environment: string, sche
export const matchesSchema = (key: string, environment: string, schema?: string): boolean => {
if (!schema) return true;
- const compiledSchemaPattern = handlebars.compile(schema)({
+ const compiledSchemaPattern = createHandlebarsClient().compile(schema)({
secretKey: "{{secretKey}}", // Keep secretKey
environment
});