Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
only allow substr and stripPrefix for permissions
Matheus Nogueiraf3169407c1f4
diff --git a/backend/src/ee/services/dynamic-secret/providers/aws-elasticache.ts b/backend/src/ee/services/dynamic-secret/providers/aws-elasticache.tsindex ed11e1a393..6cf5c9c9fd 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 = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.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 = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.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.tsindex 626b421a64..93c8b4ccaf 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 = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.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 = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.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.tsindex 806de90eae..4a50ebe13c 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,9 +1,8 @@+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";@@ -303,7 +302,7 @@ export const AzureSqlDatabaseProvider = ({);try {- const masterCreationStatement = createHandlebarsClient().compile(providerInputs.masterCreationStatement, { noEscape: true })({+ const masterCreationStatement = handlebars.compile(providerInputs.masterCreationStatement, { noEscape: true })({username,password,expiration,@@ -337,7 +336,7 @@ export const AzureSqlDatabaseProvider = ({});try {- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration,@@ -378,7 +377,7 @@ export const AzureSqlDatabaseProvider = ({const { database, masterDatabase } = providerInputs;const gatewayCallback = async (host = providerInputs.host, port = providerInputs.port) => {- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({username,database});@@ -501,7 +500,7 @@ export const AzureSqlDatabaseProvider = ({const expiration = new Date(expireAt).toISOString();const { database } = providerInputs;- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({+ const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({username: entityId,expiration,databasediff --git a/backend/src/ee/services/dynamic-secret/providers/cassandra.ts b/backend/src/ee/services/dynamic-secret/providers/cassandra.tsindex 32de19afda..79160924b7 100644--- a/backend/src/ee/services/dynamic-secret/providers/cassandra.ts+++ b/backend/src/ee/services/dynamic-secret/providers/cassandra.ts@@ -1,9 +1,8 @@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";@@ -110,7 +109,7 @@ export const CassandraProvider = (): TDynamicProviderFns => {try {const expiration = new Date(expireAt).toISOString();- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration,@@ -149,7 +148,7 @@ export const CassandraProvider = (): TDynamicProviderFns => {const { keyspace } = providerInputs;try {- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({username,keyspace});@@ -186,7 +185,7 @@ export const CassandraProvider = (): TDynamicProviderFns => {try {const expiration = new Date(expireAt).toISOString();- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({+ const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({username: entityId,keyspace,expirationdiff --git a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts b/backend/src/ee/services/dynamic-secret/providers/clickhouse.tsindex 2829044562..42e38690d0 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 = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration,@@ -323,7 +323,7 @@ export const ClickhouseProvider = ({});try {- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({username,database});@@ -368,7 +368,7 @@ export const ClickhouseProvider = ({const { database } = providerInputs;try {- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement as string, { noEscape: true })({+ const renewStatement = handlebars.compile(providerInputs.renewStatement as string, { noEscape: true })({username: entityId,expiration,databasediff --git a/backend/src/ee/services/dynamic-secret/providers/ldap.ts b/backend/src/ee/services/dynamic-secret/providers/ldap.tsindex 9c7c82d46e..7f2312c8d3 100644--- a/backend/src/ee/services/dynamic-secret/providers/ldap.ts+++ b/backend/src/ee/services/dynamic-secret/providers/ldap.ts@@ -1,9 +1,8 @@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";@@ -43,7 +42,7 @@ const generateLDIF = ({EncodedPassword: encodePassword(password)};- const renderTemplate = createHandlebarsClient().compile(ldifTemplate);+ const renderTemplate = handlebars.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.tsindex 9bfe5f7a17..9860363346 100644--- a/backend/src/ee/services/dynamic-secret/providers/redis.ts+++ b/backend/src/ee/services/dynamic-secret/providers/redis.ts@@ -1,9 +1,8 @@+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";@@ -148,7 +147,7 @@ export const RedisDatabaseProvider = (): TDynamicProviderFns => {const password = generatePassword();const expiration = new Date(expireAt).toISOString();- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration@@ -178,7 +177,7 @@ export const RedisDatabaseProvider = (): TDynamicProviderFns => {const username = entityId;- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({ username });+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({ username });const queries = revokeStatement.toString().split(";").filter(Boolean);try {@@ -206,7 +205,7 @@ export const RedisDatabaseProvider = (): TDynamicProviderFns => {const username = entityId;const expiration = new Date(expireAt).toISOString();- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({+ const renewStatement = handlebars.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.tsindex 413b67fdbc..c5da910b74 100644--- a/backend/src/ee/services/dynamic-secret/providers/sap-ase.ts+++ b/backend/src/ee/services/dynamic-secret/providers/sap-ase.ts@@ -1,9 +1,8 @@+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";@@ -117,7 +116,7 @@ export const SapAseProvider = (): TDynamicProviderFns => {const client = await $getClient(providerInputs);const masterClient = await $getClient(providerInputs, true);- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password});@@ -149,7 +148,7 @@ export const SapAseProvider = (): TDynamicProviderFns => {const revoke = async (inputs: unknown, username: string) => {const providerInputs = await validateProviderInputs(inputs);- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.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.tsindex bfd6b72304..ffb25d53bc 100644--- a/backend/src/ee/services/dynamic-secret/providers/sap-hana.ts+++ b/backend/src/ee/services/dynamic-secret/providers/sap-hana.ts@@ -4,12 +4,11 @@/* 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";@@ -118,7 +117,7 @@ export const SapHanaProvider = (): TDynamicProviderFns => {const expiration = new Date(expireAt).toISOString();const client = await $getClient(providerInputs);- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration@@ -150,7 +149,7 @@ export const SapHanaProvider = (): TDynamicProviderFns => {const revoke = async (inputs: unknown, username: string) => {const providerInputs = await validateProviderInputs(inputs);const client = await $getClient(providerInputs);- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({ username });+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({ username });const queries = revokeStatement.toString().split(";").filter(Boolean);try {for await (const query of queries) {@@ -184,7 +183,7 @@ export const SapHanaProvider = (): TDynamicProviderFns => {try {const expiration = new Date(expireAt).toISOString();- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({+ const renewStatement = handlebars.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.tsindex ba9270e0d6..d8ed94921b 100644--- a/backend/src/ee/services/dynamic-secret/providers/snowflake.ts+++ b/backend/src/ee/services/dynamic-secret/providers/snowflake.ts@@ -1,9 +1,8 @@+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";@@ -110,7 +109,7 @@ export const SnowflakeProvider = (): TDynamicProviderFns => {try {const expiration = getDaysToExpiry(new Date(expireAt));- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration@@ -147,7 +146,7 @@ export const SnowflakeProvider = (): TDynamicProviderFns => {const client = await $getClient(providerInputs);try {- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({ username });+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({ username });await new Promise((resolve, reject) => {client.execute({@@ -182,7 +181,7 @@ export const SnowflakeProvider = (): TDynamicProviderFns => {try {const expiration = getDaysToExpiry(new Date(expireAt));- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({+ const renewStatement = handlebars.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.tsindex 496c1e6582..717a9b5d53 100644--- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts+++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts@@ -1,9 +1,8 @@+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";@@ -322,7 +321,7 @@ export const SqlDatabaseProvider = ({try {const expiration = new Date(expireAt).toISOString();- const creationStatement = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password,expiration,@@ -368,7 +367,7 @@ export const SqlDatabaseProvider = ({originalHost: providerInputs.host});try {- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({username,database});@@ -413,7 +412,7 @@ export const SqlDatabaseProvider = ({const expiration = new Date(expireAt).toISOString();const { database } = providerInputs;- const renewStatement = createHandlebarsClient().compile(providerInputs.renewStatement, { noEscape: true })({+ const renewStatement = handlebars.compile(providerInputs.renewStatement, { noEscape: true })({username: entityId,expiration,databasediff --git a/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts b/backend/src/ee/services/dynamic-secret/providers/templateUtils.tsindex f54dad7d89..fbd891e842 100644--- a/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts+++ b/backend/src/ee/services/dynamic-secret/providers/templateUtils.ts@@ -1,14 +1,60 @@/* 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,@@ -26,8 +72,22 @@ const compileUsernameTemplate = ({toUpperCase?: boolean;};}): string => {- const hbs = createHandlebarsClient();-+ // 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 instanceconst context = {randomUsername,unixTimestamp,diff --git a/backend/src/ee/services/dynamic-secret/providers/vertica.ts b/backend/src/ee/services/dynamic-secret/providers/vertica.tsindex 583aa047dd..759417285c 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 createHandlebarsClient().compile(usernameTemplate)({+ return handlebars.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 = createHandlebarsClient().compile(providerInputs.creationStatement, { noEscape: true })({+ const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({username,password});@@ -332,7 +332,7 @@ export const VerticaProvider = ({try {client = await $getClient({ ...providerInputs, hostIp: host, port });- const revokeStatement = createHandlebarsClient().compile(providerInputs.revocationStatement, { noEscape: true })({+ const revokeStatement = handlebars.compile(providerInputs.revocationStatement, { noEscape: true })({username});diff --git a/backend/src/ee/services/permission/permission-fns.ts b/backend/src/ee/services/permission/permission-fns.tsindex 767bc056b7..542c543161 100644--- a/backend/src/ee/services/permission/permission-fns.ts+++ b/backend/src/ee/services/permission/permission-fns.ts@@ -1,5 +1,6 @@/* eslint-disable no-nested-ternary */import { ForbiddenError, MongoAbility, PureAbility, RawRuleOf, subject } from "@casl/ability";+import handlebars from "handlebars";import { z } from "zod";import { TOrganizations } from "@app/db/schemas";@@ -19,6 +20,7 @@ import {ProjectPermissionV2Schema,SecretSubjectFields} from "./project-permission";+import { logger } from "@app/lib/logger";export function throwIfMissingSecretReadValueOrDescribePermission(permission: MongoAbility<ProjectPermissionSet> | PureAbility,@@ -366,9 +368,30 @@ const expandLegacyForbidActions = <T extends RawRuleOf<MongoAbility<ProjectPermi});};++const createHandlebarsClient = () => {+ const hbs = handlebars.create();++ hbs.registerHelper('substr', hbsSubstr);+ hbs.registerHelper("stripPrefix", hbsStripPrefix);++ return hbs;+}++const hbsSubstr = (text: string, start: number, end?: number) => {+ const endIndex = end && typeof end === 'number' ? end : undefined;+ logger.info({text, start, end: end ?? 'undefined'}, 'substr')+ return text.substring(start, endIndex);+}++const hbsStripPrefix = (text: string, prefix: string) => {+ return text.startsWith(prefix) ? text.substring(prefix.length) : text;+}+export {assertPermissionBoundary,constructPermissionErrorMessage,+ createHandlebarsClient,escapeHandlebarsMissingDict,expandLegacyForbidActions,isAuthMethodSaml,diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex 6eac4b166b..1c615cb214 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -1,6 +1,7 @@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,@@ -62,7 +63,7 @@ import {OrgPermissionSubjects} from "./org-permission";import { TPermissionDALFactory } from "./permission-dal";-import { escapeHandlebarsMissingDict, expandLegacyForbidActions, validateOrgSSO } from "./permission-fns";+import { createHandlebarsClient, escapeHandlebarsMissingDict, expandLegacyForbidActions, validateOrgSSO } from "./permission-fns";import {TBuildOrgPermissionDTO,TBuildProjectPermissionDTO,@@ -76,8 +77,6 @@ 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 scopediff --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.tsindex 1a0ded60d4..457bf0c105 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,3 +1,4 @@+import handlebars from "handlebars";import { Knex } from "knex";import {@@ -9,7 +10,6 @@ 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 = createHandlebarsClient().compile(userProvidedRotationStatement)({+ const revokeStatement = handlebars.compile(userProvidedRotationStatement)({username,password,database: connection.credentials.databasediff --git a/backend/src/lib/template/handlebars-client.ts b/backend/src/lib/template/handlebars-client.tsdeleted file mode 100644index 6ec72dd010..0000000000--- a/backend/src/lib/template/handlebars-client.ts+++ /dev/null@@ -1,73 +0,0 @@-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 filediff --git a/backend/src/lib/template/validate-handlebars.ts b/backend/src/lib/template/validate-handlebars.tsindex dfcec21ff6..d7b1dc7ef1 100644--- a/backend/src/lib/template/validate-handlebars.ts+++ b/backend/src/lib/template/validate-handlebars.ts@@ -1,14 +1,16 @@+import handlebars from "handlebars";+import { BadRequestError } from "../errors";import { logger } from "../logger";-import { createHandlebarsClient } from "./handlebars-client";type SanitizationArg = {allowedExpressions?: (arg: string) => boolean;+ allowedHelpers?: string[];};const isValidExpression = (expression: string, dto: SanitizationArg): boolean => {// Allow helper functions (replace, truncate)- const allowedHelpers = ["replace", "truncate", "random", "uppercase", "lowercase", "substr", "stripPrefix"];+ const allowedHelpers = dto.allowedHelpers ?? ["replace", "truncate", "random", "uppercase", "lowercase"];if (allowedHelpers.includes(expression)) {return true;}@@ -18,7 +20,7 @@ const isValidExpression = (expression: string, dto: SanitizationArg): boolean =>};export const validateHandlebarTemplate = (templateName: string, template: string, dto: SanitizationArg) => {- const parsedAst = createHandlebarsClient().parse(template);+ const parsedAst = handlebars.parse(template);parsedAst.body.forEach((el) => {if (el.type === "ContentStatement") return;if (el.type === "MustacheStatement" && "path" in el) {@@ -31,7 +33,7 @@ export const validateHandlebarTemplate = (templateName: string, template: string};export const isValidHandleBarTemplate = (template: string, dto: SanitizationArg) => {- const parsedAst = createHandlebarsClient().parse(template);+ const parsedAst = handlebars.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.tsindex 6025935f51..46b86c4b87 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 = createHandlebarsClient().compile(certificateNameSchema)({+ targetName = handlebars.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.tsindex 874811dea1..937585926a 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 = createHandlebarsClient().compile(certificateNameSchema)({+ targetCertKeyName = handlebars.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.tsindex f7d5f3c712..2895865108 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 = createHandlebarsClient().compile(schema)({+ const newName = handlebars.compile(schema)({certificateId,environment});@@ -117,7 +117,7 @@ export const stripCertificateNameSchema = (): TCertificateMap => {if (!schema) return certificateMap;- const compiledSchemaPattern = createHandlebarsClient().compile(schema)({+ const compiledSchemaPattern = handlebars.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 = createHandlebarsClient().compile(schema)({+ const compiledSchemaPattern = handlebars.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.tsindex c1e1283037..6314cdc25d 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 = createHandlebarsClient().compile(certificateNameSchema)(templateData);+ certificateName = handlebars.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/role/role-service.ts b/backend/src/services/role/role-service.tsindex 48c7f0c3a3..181f390e4d 100644--- a/backend/src/services/role/role-service.ts+++ b/backend/src/services/role/role-service.ts@@ -103,7 +103,8 @@ export const roleServiceFactory = ({if (existingRole) throw new BadRequestError({ message: `Role with ${data.slug} already exists` });validateHandlebarTemplate("Role Creation", JSON.stringify(data.permissions || []), {- allowedExpressions: (val) => val.includes("identity.")+ allowedExpressions: (val) => val.includes("identity."),+ allowedHelpers: ["substr", "stripPrefix"]});const role = await roleDAL.create({@@ -148,7 +149,8 @@ export const roleServiceFactory = ({}validateHandlebarTemplate("Role Update", JSON.stringify(data.permissions || []), {- allowedExpressions: (val) => val.includes("identity.")+ allowedExpressions: (val) => val.includes("identity."),+ allowedHelpers: ["substr", "stripPrefix"]});const role = await roleDAL.updateById(existingRole.id, {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.tsindex 6bc4d2f336..695640f52b 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; keySchemathrow new SecretSyncError({ message: `Key schema cannot contain leading '/'`, shouldRetry: false });}- const keySchemaSegments = createHandlebarsClient()+ const keySchemaSegments = handlebars.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.tsindex 38f57ab132..f860ef20a9 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 createHandlebarsClient().compile(schema)({+ return handlebars.compile(schema)({secretKey: key,environment});@@ -197,7 +197,7 @@ const addSchema = (unprocessedSecretMap: TSecretMap, environment: string, schemaconst processedSecretMap: TSecretMap = {};for (const [key, value] of Object.entries(unprocessedSecretMap)) {- const newKey = createHandlebarsClient().compile(schema)({+ const newKey = handlebars.compile(schema)({secretKey: key,environment});@@ -212,7 +212,7 @@ const addSchema = (unprocessedSecretMap: TSecretMap, environment: string, schemaconst stripSchema = (unprocessedSecretMap: TSecretMap, environment: string, schema?: string): TSecretMap => {if (!schema) return unprocessedSecretMap;- const compiledSchemaPattern = createHandlebarsClient().compile(schema)({+ const compiledSchemaPattern = handlebars.compile(schema)({secretKey: "{{secretKey}}", // Keep secretKeyenvironment});@@ -240,7 +240,7 @@ const stripSchema = (unprocessedSecretMap: TSecretMap, environment: string, scheexport const matchesSchema = (key: string, environment: string, schema?: string): boolean => {if (!schema) return true;- const compiledSchemaPattern = createHandlebarsClient().compile(schema)({+ const compiledSchemaPattern = handlebars.compile(schema)({secretKey: "{{secretKey}}", // Keep secretKeyenvironment});