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
move cache keys and ttl hard coded values to keystore
adilsonb8f006eacbda
diff --git a/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.ts b/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.tsindex 568d8c34ef..d38e829485 100644--- a/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.ts+++ b/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.ts@@ -9,7 +9,7 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotimport { z } from "zod";import { ActionProjectType, TAiMcpEndpoints } from "@app/db/schemas";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto as cryptoModule } from "@app/lib/crypto";import { DatabaseErrorCode } from "@app/lib/error-codes";@@ -113,8 +113,6 @@ const OauthChallengeCodeSchema = z.object({})});-const OAUTH_FLOW_EXPIRY_IN_SECS = 5 * 60;-// PKCE challenge computationconst computePkceChallenge = (codeVerifier: string) => {const sha256 = crypto.createHash("sha256").update(codeVerifier).digest();@@ -1019,7 +1017,7 @@ export const aiMcpEndpointServiceFactory = ({await keyStore.setItemWithExpiry(KeyStorePrefixes.AiMcpEndpointOAuthClient(clientId),- OAUTH_FLOW_EXPIRY_IN_SECS,+ KeyStoreTtls.AiMcpEndpointOAuthFlowInSeconds,JSON.stringify(payload));@@ -1035,7 +1033,7 @@ export const aiMcpEndpointServiceFactory = ({// Update with stateawait keyStore.setItemWithExpiry(KeyStorePrefixes.AiMcpEndpointOAuthClient(clientId),- OAUTH_FLOW_EXPIRY_IN_SECS,+ KeyStoreTtls.AiMcpEndpointOAuthFlowInSeconds,JSON.stringify({ ...JSON.parse(oauthClientCache), state }));};@@ -1085,7 +1083,7 @@ export const aiMcpEndpointServiceFactory = ({const code = crypto.randomBytes(32).toString("hex");await keyStore.setItemWithExpiry(KeyStorePrefixes.AiMcpEndpointOAuthCode(clientId, code),- OAUTH_FLOW_EXPIRY_IN_SECS,+ KeyStoreTtls.AiMcpEndpointOAuthFlowInSeconds,JSON.stringify({codeChallenge,codeChallengeMethod,diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.tsindex 8834dc4ce4..9b81452707 100644--- a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts@@ -11,7 +11,7 @@ import { isAxiosError } from "axios";import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -65,8 +65,6 @@ type TAiMcpServerServiceFactoryDep = {export type TAiMcpServerServiceFactory = ReturnType<typeof aiMcpServerServiceFactory>;-const OAUTH_SESSION_TTL_SECONDS = 10 * 60; // 10 minutes-// Buffer time before token expiry to trigger refresh (5 minutes)const TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1000;@@ -611,7 +609,7 @@ export const aiMcpServerServiceFactory = ({await keyStore.setItemWithExpiry(KeyStorePrefixes.AiMcpServerOAuth(sessionId),- OAUTH_SESSION_TTL_SECONDS,+ KeyStoreTtls.AiMcpServerOAuthSessionInSeconds,JSON.stringify(sessionData));@@ -697,7 +695,7 @@ export const aiMcpServerServiceFactory = ({await keyStore.setItemWithExpiry(KeyStorePrefixes.AiMcpServerOAuth(sessionId),- OAUTH_SESSION_TTL_SECONDS,+ KeyStoreTtls.AiMcpServerOAuthSessionInSeconds,JSON.stringify(updatedSession));diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.tsindex cefcd8349d..9c30f1838a 100644--- a/backend/src/ee/services/audit-log/audit-log-service.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.ts@@ -2,7 +2,7 @@ import { ForbiddenError } from "@casl/ability";import { requestContext } from "@fastify/request-context";import { ActionProjectType, OrganizationActionScope, TUsers } from "@app/db/schemas";-import { TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";@@ -23,7 +23,6 @@ import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, TAuditLogServiceFactory } froconst AUDIT_LOG_ROW_WARNING_THRESHOLD = 350_000_000;const AUDIT_LOG_ALERT_ROW_INCREMENT = 10_000_000;-const AUDIT_LOG_MIGRATION_ALERT_STATE_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 daystype TAuditLogServiceFactoryDep = {auditLogDAL: TAuditLogDALFactory;@@ -192,7 +191,7 @@ export const auditLogServiceFactory = ({if (rowCount < AUDIT_LOG_ROW_WARNING_THRESHOLD) return;- const lastAlertedRowCountStr: string | null = await keyStore.getItem("audit-log-migration-alert-last-row-count");+ const lastAlertedRowCountStr: string | null = await keyStore.getItem(KeyStorePrefixes.AuditLogMigrationAlert);const lastAlertedRowCount = lastAlertedRowCountStr ? Number(lastAlertedRowCountStr) : 0;if (lastAlertedRowCount > 0 && rowCount < lastAlertedRowCount + AUDIT_LOG_ALERT_ROW_INCREMENT) return;@@ -210,8 +209,8 @@ export const auditLogServiceFactory = ({if (superAdminsResult.users.length === 0) {await keyStore.setItemWithExpiry(- "audit-log-migration-alert-last-row-count",- AUDIT_LOG_MIGRATION_ALERT_STATE_TTL_SECONDS,+ KeyStorePrefixes.AuditLogMigrationAlert,+ KeyStoreTtls.AuditLogMigrationAlertInSeconds,String(rowCount));return;@@ -253,8 +252,8 @@ export const auditLogServiceFactory = ({});await keyStore.setItemWithExpiry(- "audit-log-migration-alert-last-row-count",- AUDIT_LOG_MIGRATION_ALERT_STATE_TTL_SECONDS,+ KeyStorePrefixes.AuditLogMigrationAlert,+ KeyStoreTtls.AuditLogMigrationAlertInSeconds,String(rowCount));logger.info(`checkPostgresAuditLogVolumeMigrationAlert: alert sent to super admins (rowCount=${rowCount})`);diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.tsindex c8e311621f..8da2c8d60d 100644--- a/backend/src/ee/services/license/license-service.ts+++ b/backend/src/ee/services/license/license-service.ts@@ -10,7 +10,7 @@ import { CronJob } from "cron";import { Knex } from "knex";import { OrganizationActionScope } from "@app/db/schemas";-import { TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { TEnvConfig } from "@app/lib/config/env";import { verifyOfflineLicense } from "@app/lib/crypto";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -63,9 +63,6 @@ export type TLicenseServiceFactory = ReturnType<typeof licenseServiceFactory>;const LICENSE_SERVER_CLOUD_LOGIN = "/api/auth/v1/license-server-login";const LICENSE_SERVER_ON_PREM_LOGIN = "/api/auth/v1/license-login";-const LICENSE_SERVER_CLOUD_PLAN_TTL = 5 * 60; // 5 mins-const FEATURE_CACHE_KEY = (orgId: string) => `infisical-cloud-plan-${orgId}`;-export const licenseServiceFactory = ({orgDAL,permissionService,@@ -201,7 +198,7 @@ export const licenseServiceFactory = ({logger.info(`getPlan: attempting to fetch plan for [orgId=${orgId}] [projectId=${projectId}]`);try {if (instanceType === InstanceType.Cloud) {- const cachedPlan = await keyStore.getItem(FEATURE_CACHE_KEY(orgId));+ const cachedPlan = await keyStore.getItem(KeyStorePrefixes.LicenseCloudPlan(orgId));if (cachedPlan) {logger.info(`getPlan: plan fetched from cache [orgId=${orgId}] [projectId=${projectId}]`);return JSON.parse(cachedPlan) as TFeatureSet;@@ -239,8 +236,8 @@ export const licenseServiceFactory = ({currentPlan.identitiesUsed = identityUsed;await keyStore.setItemWithExpiry(- FEATURE_CACHE_KEY(org.id),- LICENSE_SERVER_CLOUD_PLAN_TTL,+ KeyStorePrefixes.LicenseCloudPlan(org.id),+ KeyStoreTtls.LicenseCloudPlanInSeconds,JSON.stringify(currentPlan));@@ -252,8 +249,8 @@ export const licenseServiceFactory = ({`getPlan: encountered an error when fetching pan [orgId=${orgId}] [projectId=${projectId}] [error]`);await keyStore.setItemWithExpiry(- FEATURE_CACHE_KEY(orgId),- LICENSE_SERVER_CLOUD_PLAN_TTL,+ KeyStorePrefixes.LicenseCloudPlan(orgId),+ KeyStoreTtls.LicenseCloudPlanInSeconds,JSON.stringify(onPremFeatures));return onPremFeatures;@@ -264,7 +261,7 @@ export const licenseServiceFactory = ({};const refreshPlan = async (orgId: string) => {- await keyStore.deleteItem(FEATURE_CACHE_KEY(orgId));+ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));if (instanceType === InstanceType.Cloud) {await getPlan(orgId);}@@ -307,7 +304,7 @@ export const licenseServiceFactory = ({quantityIdentities});}- await keyStore.deleteItem(FEATURE_CACHE_KEY(rootOrgId));+ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(rootOrgId));} else if (instanceType === InstanceType.EnterpriseOnPrem) {const usedSeats = await licenseDAL.countOfOrgMembers(null, tx);const usedIdentitySeats = await licenseDAL.countOrgUsersAndIdentities(null, tx);@@ -406,7 +403,7 @@ export const licenseServiceFactory = ({`/api/license-server/v1/customers/${organization.customerId}/session/trial`,{ success_url });- await keyStore.deleteItem(FEATURE_CACHE_KEY(orgId));+ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));return { url };};@@ -920,7 +917,7 @@ export const licenseServiceFactory = ({};const invalidateGetPlan = async (orgId: string) => {- await keyStore.deleteItem(FEATURE_CACHE_KEY(orgId));+ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));};const getCustomerId = () => {diff --git a/backend/src/keystore/keystore.test.ts b/backend/src/keystore/keystore.test.tsnew file mode 100644index 0000000000..473e52a13e--- /dev/null+++ b/backend/src/keystore/keystore.test.ts@@ -0,0 +1,86 @@+import { describe, expect, test } from "vitest";++import { KeyStorePrefixes, KeyStoreTtls } from "./keystore";++describe("KeyStorePrefixes", () => {+ test("AdminConfig matches previously hardcoded value", () => {+ expect(KeyStorePrefixes.AdminConfig).toBe("infisical-admin-cfg");+ });++ test("InvalidatingCache matches previously hardcoded value", () => {+ expect(KeyStorePrefixes.InvalidatingCache).toBe("invalidating-cache");+ });++ test("SecretManagerCachePattern matches previously hardcoded value", () => {+ expect(KeyStorePrefixes.SecretManagerCachePattern).toBe("secret-manager:*");+ });++ test("AuditLogMigrationAlert matches previously hardcoded value", () => {+ expect(KeyStorePrefixes.AuditLogMigrationAlert).toBe("audit-log-migration-alert-last-row-count");+ });++ test("LicenseCloudPlan factory matches previously hardcoded template", () => {+ const orgId = "org-123";+ expect(KeyStorePrefixes.LicenseCloudPlan(orgId)).toBe(`infisical-cloud-plan-${orgId}`);+ });++ test("IdentityLockoutState factory matches previously hardcoded template", () => {+ const identityId = "id-abc";+ const authMethod = "ldap-auth";+ const slug = "my-user";+ expect(KeyStorePrefixes.IdentityLockoutState(identityId, authMethod, slug)).toBe(+ `lockout:identity:${identityId}:${authMethod}:${slug}`+ );+ });++ test("TelemetryIdentify factory matches previously hardcoded template", () => {+ const distinctId = "user-xyz";+ expect(KeyStorePrefixes.TelemetryIdentify(distinctId)).toBe(`telemetry-identify:${distinctId}`);+ });+});++describe("KeyStoreTtls", () => {+ test("AdminConfigInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.AdminConfigInSeconds).toBe(60);+ });++ test("InvalidatingCacheInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.InvalidatingCacheInSeconds).toBe(1800);+ });++ test("AuditLogMigrationAlertInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.AuditLogMigrationAlertInSeconds).toBe(7 * 24 * 60 * 60);+ });++ test("LicenseCloudPlanInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.LicenseCloudPlanInSeconds).toBe(5 * 60);+ });++ test("AiMcpEndpointOAuthFlowInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.AiMcpEndpointOAuthFlowInSeconds).toBe(5 * 60);+ });++ test("AiMcpServerOAuthSessionInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.AiMcpServerOAuthSessionInSeconds).toBe(10 * 60);+ });++ test("DashboardCacheInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.DashboardCacheInSeconds).toBe(600);+ });++ test("ProjectEnvironmentOperationMarkerInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.ProjectEnvironmentOperationMarkerInSeconds).toBe(10);+ });++ test("UserMfaUnlockEmailSentInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.UserMfaUnlockEmailSentInSeconds).toBe(300);+ });++ test("TelemetryGroupIdentifyInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.TelemetryGroupIdentifyInSeconds).toBe(3600);+ });++ test("TelemetryAggregatedEventInSeconds matches previously hardcoded value", () => {+ expect(KeyStoreTtls.TelemetryAggregatedEventInSeconds).toBe(600);+ });+});diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex cb59a899f7..a567d32dde 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -98,6 +98,7 @@ export const KeyStorePrefixes = {TelemetryIdentifyIdentity: (dedupKey: string) => `telemetry-identify-identity:${dedupKey}` as const,TelemetryGroupIdentify: (orgId: string) => `telemetry-group-identify:${orgId}` as const,+ TelemetryIdentify: (distinctId: string) => `telemetry-identify:${distinctId}` as const,SecretEtag: (projectId: string) => `secret-etag:${projectId}` as const,PamAwsIamAccessKeyId: (sessionId: string) => `pam-aws-iam-access-key-id:${sessionId}` as const,@@ -106,7 +107,15 @@ export const KeyStorePrefixes = {CertActivityTrend: (projectId: string, range: string) => `cert-activity-trend:${projectId}:${range}` as const,CertPqcTrend: (projectId: string, range: string) => `cert-pqc-trend:${projectId}:${range}` as const,RefreshTokenGrace: (sessionId: string) => `refresh-token-grace:${sessionId}` as const,- InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const+ InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const,++ AdminConfig: "infisical-admin-cfg",+ InvalidatingCache: "invalidating-cache",+ SecretManagerCachePattern: "secret-manager:*",+ AuditLogMigrationAlert: "audit-log-migration-alert-last-row-count",+ LicenseCloudPlan: (orgId: string) => `infisical-cloud-plan-${orgId}` as const,+ IdentityLockoutState: (identityId: string, authMethod: string, slug: string) =>+ `lockout:identity:${identityId}:${authMethod}:${slug}` as const};export const KeyStoreTtls = {@@ -121,7 +130,18 @@ export const KeyStoreTtls = {ProjectSSEConnectionTtlSeconds: 180, // Must be > heartbeat interval (60s) * 2TelemetryIdentifyIdentityInSeconds: 86400, // 24 hoursRefreshTokenGraceInSeconds: 10,- InsightsCacheInSeconds: 300 // 5 minutes+ InsightsCacheInSeconds: 300, // 5 minutes+ AdminConfigInSeconds: 60,+ InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation job+ AuditLogMigrationAlertInSeconds: 604800, // 7 days+ LicenseCloudPlanInSeconds: 300, // 5 minutes+ AiMcpEndpointOAuthFlowInSeconds: 300, // 5 minutes+ AiMcpServerOAuthSessionInSeconds: 600, // 10 minutes+ DashboardCacheInSeconds: 600, // 10 minutes+ ProjectEnvironmentOperationMarkerInSeconds: 10,+ UserMfaUnlockEmailSentInSeconds: 300, // 5 minutes+ TelemetryGroupIdentifyInSeconds: 3600, // 1 hour+ TelemetryAggregatedEventInSeconds: 600 // 10 minutes};type TDeleteItems = {diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex 33a00c2bc8..1adb30638c 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -12,7 +12,7 @@ import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/aimport { OrgPermissionSsoActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto, generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";import { getUserPrivateKey } from "@app/lib/crypto/srp";@@ -758,7 +758,11 @@ export const authLoginServiceFactory = ({});// Mark that an unlock email was sent, expires after 5 minutes- await keyStore.setItemWithExpiry(KeyStorePrefixes.UserMfaUnlockEmailSent(userId), 300, "1");+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.UserMfaUnlockEmailSent(userId),+ KeyStoreTtls.UserMfaUnlockEmailSentInSeconds,+ "1"+ );}} catch (lockErr) {if (lock) {diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.tsindex cb6c80350c..a42b3a427e 100644--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts@@ -870,9 +870,9 @@ export const identityLdapAuthServiceFactory = ({const identity = await identityDAL.findById(identityId);const orgId = identity?.orgId ?? null;- const LOCKOUT_KEY = `lockout:identity:${identityId}:${IdentityAuthMethod.LDAP_AUTH}:${usernameSlug}`;+ const lockoutKey = KeyStorePrefixes.IdentityLockoutState(identityId, IdentityAuthMethod.LDAP_AUTH, usernameSlug);- const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);+ const lockoutRaw = await keyStore.getItem(lockoutKey);let lockout: LockoutObject | undefined;if (lockoutRaw) {@@ -899,7 +899,7 @@ export const identityLdapAuthServiceFactory = ({// If auth succeeds, clear any existing lockoutif (lockout) {- await keyStore.deleteItem(LOCKOUT_KEY);+ await keyStore.deleteItem(lockoutKey);}return result;@@ -909,14 +909,14 @@ export const identityLdapAuthServiceFactory = ({if (identityLdapAuth.lockoutEnabled) {let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;try {- lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 500, {+ lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(lockoutKey)], 500, {retryCount: 10,retryDelay: 300,retryJitter: 100});// Re-fetch the latest lockout data while holding the lock- const lockoutRawNew = await keyStore.getItem(LOCKOUT_KEY);+ const lockoutRawNew = await keyStore.getItem(lockoutKey);if (lockoutRawNew) {lockout = JSON.parse(lockoutRawNew) as LockoutObject;} else {@@ -939,7 +939,7 @@ export const identityLdapAuthServiceFactory = ({}await keyStore.setItemWithExpiry(- LOCKOUT_KEY,+ lockoutKey,lockout.lockedOut ? identityLdapAuth.lockoutDurationSeconds : identityLdapAuth.lockoutCounterResetSeconds,JSON.stringify(lockout));diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.tsindex e72be0e146..50bbd3a3cd 100644--- a/backend/src/services/identity-ua/identity-ua-service.ts+++ b/backend/src/services/identity-ua/identity-ua-service.ts@@ -104,9 +104,13 @@ export const identityUaServiceFactory = ({trustedIps: identityUa.clientSecretTrustedIps as TIp[]});- const LOCKOUT_KEY = `lockout:identity:${identityUa.identityId}:${IdentityAuthMethod.UNIVERSAL_AUTH}:${clientId}`;+ const lockoutKey = KeyStorePrefixes.IdentityLockoutState(+ identityUa.identityId,+ IdentityAuthMethod.UNIVERSAL_AUTH,+ clientId+ );- const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);+ const lockoutRaw = await keyStore.getItem(lockoutKey);let lockout: LockoutObject | undefined;if (lockoutRaw) {@@ -146,14 +150,14 @@ export const identityUaServiceFactory = ({if (identityUa.lockoutEnabled) {let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;try {- lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 300, {+ lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(lockoutKey)], 300, {retryCount: 3,retryDelay: 300,retryJitter: 100});// Re-fetch the latest lockout data while holding the lock- const lockoutRawNew = await keyStore.getItem(LOCKOUT_KEY);+ const lockoutRawNew = await keyStore.getItem(lockoutKey);if (lockoutRawNew) {lockout = JSON.parse(lockoutRawNew) as LockoutObject;} else {@@ -181,7 +185,7 @@ export const identityUaServiceFactory = ({}await keyStore.setItemWithExpiry(- LOCKOUT_KEY,+ lockoutKey,lockout.lockedOut ? identityUa.lockoutDurationSeconds : identityUa.lockoutCounterResetSeconds,JSON.stringify(lockout));@@ -211,7 +215,7 @@ export const identityUaServiceFactory = ({});} else if (lockout) {// If credentials are valid, clear any existing lockout record- await keyStore.deleteItem(LOCKOUT_KEY);+ await keyStore.deleteItem(lockoutKey);}const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo;diff --git a/backend/src/services/project-env/project-env-service.ts b/backend/src/services/project-env/project-env-service.tsindex cf14cd5585..8b7a6cae43 100644--- a/backend/src/services/project-env/project-env-service.ts+++ b/backend/src/services/project-env/project-env-service.ts@@ -6,7 +6,7 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-serviceimport { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { TSecretApprovalPolicyEnvironmentDALFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-environment-dal";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";@@ -114,7 +114,7 @@ export const projectEnvServiceFactory = ({await keyStore.setItemWithExpiry(KeyStorePrefixes.WaitUntilReadyProjectEnvironmentOperation(projectId),- 10,+ KeyStoreTtls.ProjectEnvironmentOperationMarkerInSeconds,"true");@@ -201,7 +201,7 @@ export const projectEnvServiceFactory = ({await keyStore.setItemWithExpiry(KeyStorePrefixes.WaitUntilReadyProjectEnvironmentOperation(projectId),- 10,+ KeyStoreTtls.ProjectEnvironmentOperationMarkerInSeconds,"true");@@ -263,7 +263,7 @@ export const projectEnvServiceFactory = ({await keyStore.setItemWithExpiry(KeyStorePrefixes.WaitUntilReadyProjectEnvironmentOperation(projectId),- 10,+ KeyStoreTtls.ProjectEnvironmentOperationMarkerInSeconds,"true");diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex 863125f161..48b72064c3 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -40,7 +40,7 @@ import { TSshCertificateDALFactory } from "@app/ee/services/ssh-certificate/ssh-import { TSshCertificateTemplateDALFactory } from "@app/ee/services/ssh-certificate-template/ssh-certificate-template-dal";import { TSshHostDALFactory } from "@app/ee/services/ssh-host/ssh-host-dal";import { TSshHostGroupDALFactory } from "@app/ee/services/ssh-host-group/ssh-host-group-dal";-import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { withCache } from "@app/lib/cache/with-cache";import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";import { getConfig } from "@app/lib/config/env";@@ -125,8 +125,6 @@ import {TUpgradeProjectDTO} from "./project-types";-const DASHBOARD_CACHE_TTL = 600;-export const DEFAULT_PROJECT_ENVS = [{ name: "Development", slug: "dev" },{ name: "Staging", slug: "staging" },@@ -1365,7 +1363,7 @@ export const projectServiceFactory = ({return withCache({keyStore,key: KeyStorePrefixes.CertDashboardStats(projectId),- ttlSeconds: DASHBOARD_CACHE_TTL,+ ttlSeconds: KeyStoreTtls.DashboardCacheInSeconds,fetcher: () => certificateDAL.getDashboardStats(projectId)});};@@ -1401,7 +1399,7 @@ export const projectServiceFactory = ({return withCache({keyStore,key: KeyStorePrefixes.CertActivityTrend(projectId, range),- ttlSeconds: DASHBOARD_CACHE_TTL,+ ttlSeconds: KeyStoreTtls.DashboardCacheInSeconds,fetcher: () => certificateDAL.getActivityTrend(projectId, daysBack)});};@@ -1437,7 +1435,7 @@ export const projectServiceFactory = ({return withCache({keyStore,key: KeyStorePrefixes.CertPqcTrend(projectId, range),- ttlSeconds: DASHBOARD_CACHE_TTL,+ ttlSeconds: KeyStoreTtls.DashboardCacheInSeconds,fetcher: () => certificateDAL.getPqcTrend(projectId, daysBack)});};diff --git a/backend/src/services/super-admin/invalidate-cache-queue.ts b/backend/src/services/super-admin/invalidate-cache-queue.tsindex c2a12f5d5c..0eda4e643b 100644--- a/backend/src/services/super-admin/invalidate-cache-queue.ts+++ b/backend/src/services/super-admin/invalidate-cache-queue.ts@@ -1,4 +1,4 @@-import { TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";@@ -31,15 +31,19 @@ export const invalidateCacheQueueFactory = ({ queueService, keyStore }: TInvaliddata: { type }} = job.data;- await keyStore.setItemWithExpiry("invalidating-cache", 1800, "true"); // 30 minutes max (in case the job somehow silently fails)+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.InvalidatingCache,+ KeyStoreTtls.InvalidatingCacheInSeconds,+ "true"+ ); // 30 minutes max (in case the job somehow silently fails)if (type === CacheType.ALL || type === CacheType.SECRETS)- await keyStore.deleteItems({ pattern: "secret-manager:*" });+ await keyStore.deleteItems({ pattern: KeyStorePrefixes.SecretManagerCachePattern });- await keyStore.deleteItem("invalidating-cache");+ await keyStore.deleteItem(KeyStorePrefixes.InvalidatingCache);} catch (err) {logger.error(err, "Failed to invalidate cache");- await keyStore.deleteItem("invalidating-cache");+ await keyStore.deleteItem(KeyStorePrefixes.InvalidatingCache);}});diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.tsindex 63f21e003a..9f45c17097 100644--- a/backend/src/services/super-admin/super-admin-service.ts+++ b/backend/src/services/super-admin/super-admin-service.ts@@ -12,7 +12,7 @@ import {import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";-import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, KeyStoreTtls, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { withCache } from "@app/lib/cache/with-cache";import {getConfig,@@ -128,8 +128,6 @@ export const getInstanceIntegrationsConfig = () => {return adminIntegrationsConfig;};-const ADMIN_CONFIG_KEY = "infisical-admin-cfg";-const ADMIN_CONFIG_KEY_EXP = 60; // 60sexport const ADMIN_CONFIG_DB_UUID = "00000000-0000-0000-0000-000000000000";export const superAdminServiceFactory = ({@@ -160,8 +158,8 @@ export const superAdminServiceFactory = ({getServerCfg = async () => {const serverCfg = await withCache({keyStore,- key: ADMIN_CONFIG_KEY,- ttlSeconds: ADMIN_CONFIG_KEY_EXP,+ key: KeyStorePrefixes.AdminConfig,+ ttlSeconds: KeyStoreTtls.AdminConfigInSeconds,fetcher: async () => {const cfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);if (!cfg) {@@ -181,7 +179,7 @@ export const superAdminServiceFactory = ({};// reset on initialized- await keyStore.deleteItem(ADMIN_CONFIG_KEY);+ await keyStore.deleteItem(KeyStorePrefixes.AdminConfig);const serverCfg = await serverCfgDAL.transaction(async (tx) => {await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.SuperAdminInit]);const serverCfgInDB = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);@@ -463,9 +461,16 @@ export const superAdminServiceFactory = ({const updatedServerCfg = await serverCfgDAL.updateById(ADMIN_CONFIG_DB_UUID, updatedData);try {- await keyStore.setItemWithExpiry(ADMIN_CONFIG_KEY, ADMIN_CONFIG_KEY_EXP, JSON.stringify(updatedServerCfg));+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.AdminConfig,+ KeyStoreTtls.AdminConfigInSeconds,+ JSON.stringify(updatedServerCfg)+ );} catch (err) {- logger.warn({ key: ADMIN_CONFIG_KEY, err }, `updateServerCfg: cache write failed [key=${ADMIN_CONFIG_KEY}]`);+ logger.warn(+ { key: KeyStorePrefixes.AdminConfig, err },+ `updateServerCfg: cache write failed [key=${KeyStorePrefixes.AdminConfig}]`+ );}if (gitHubAppConnectionSettingsUpdated) {@@ -1161,7 +1166,7 @@ export const superAdminServiceFactory = ({};const checkIfInvalidatingCache = async () => {- return (await keyStore.getItem("invalidating-cache")) !== null;+ return (await keyStore.getItem(KeyStorePrefixes.InvalidatingCache)) !== null;};const initializeAdminIntegrationConfigSync = async () => {diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.tsindex 73860e48a4..b455ec1832 100644--- a/backend/src/services/telemetry/telemetry-service.ts+++ b/backend/src/services/telemetry/telemetry-service.ts@@ -18,8 +18,6 @@ export const TELEMETRY_SECRET_PROCESSED_KEY = "telemetry-secret-processed";export const TELEMETRY_SECRET_OPERATIONS_KEY = "telemetry-secret-operations";export const POSTHOG_AGGREGATED_EVENTS = [PostHogEventTypes.SecretPulled, PostHogEventTypes.MachineIdentityLogin];-const TELEMETRY_AGGREGATED_KEY_EXP = 600; // 10mins-const GROUP_IDENTIFY_CACHE_TTL = 3600; // 1 hour// Bucket configurationconst TELEMETRY_BUCKET_COUNT = 30;@@ -257,7 +255,7 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmeconst eventKey = createTelemetryEventKey(event.event, event.distinctId);await keyStore.setItemWithExpiry(eventKey,- TELEMETRY_AGGREGATED_KEY_EXP,+ KeyStoreTtls.TelemetryAggregatedEventInSeconds,JSON.stringify({distinctId: event.distinctId,event: event.event,@@ -272,7 +270,7 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme// Dedup groupIdentify: only fire once per org per hour to avoid redundant DB/API callsconst groupIdentifyCacheKey = KeyStorePrefixes.TelemetryGroupIdentify(orgId);void keyStore- .setItemWithExpiryNX(groupIdentifyCacheKey, GROUP_IDENTIFY_CACHE_TTL, "1")+ .setItemWithExpiryNX(groupIdentifyCacheKey, KeyStoreTtls.TelemetryGroupIdentifyInSeconds, "1").then((wasSet) => {if (wasSet) {return getOrgGroupProperties(orgId, resolvedOrgName).then((groupProperties) => {@@ -411,7 +409,11 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme// Dedup groupIdentify across all paths: only fire once per org per hourconst groupIdentifyCacheKey = KeyStorePrefixes.TelemetryGroupIdentify(key.org);// eslint-disable-next-line no-await-in-loop- const wasSet = await keyStore.setItemWithExpiryNX(groupIdentifyCacheKey, GROUP_IDENTIFY_CACHE_TTL, "1");+ const wasSet = await keyStore.setItemWithExpiryNX(+ groupIdentifyCacheKey,+ KeyStoreTtls.TelemetryGroupIdentifyInSeconds,+ "1"+ );if (wasSet) {let groupProperties = orgPropertiesCache.get(key.org);if (!groupProperties) {@@ -475,8 +477,6 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme}};- const TELEMETRY_IDENTIFY_CACHE_KEY_PREFIX = "telemetry-identify";- const TELEMETRY_IDENTIFY_CACHE_TTL = 86400; // 24 hours// Shorter TTL for in-memory fallback to bound memory growth during Redis outagesconst IN_MEMORY_IDENTIFY_FALLBACK_TTL_MS = 5 * 60 * 1000; // 5 minutes@@ -500,9 +500,13 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmeif (postHog && distinctId) {if (!skipDedup) {try {- const cacheKey = `${TELEMETRY_IDENTIFY_CACHE_KEY_PREFIX}:${distinctId}`;+ const cacheKey = KeyStorePrefixes.TelemetryIdentify(distinctId);// Atomic SET NX + EX: only the first caller within the TTL window proceeds- const wasSet = await keyStore.setItemWithExpiryNX(cacheKey, TELEMETRY_IDENTIFY_CACHE_TTL, "1");+ const wasSet = await keyStore.setItemWithExpiryNX(+ cacheKey,+ KeyStoreTtls.TelemetryIdentifyIdentityInSeconds,+ "1"+ );if (!wasSet) return;} catch (error) {logger.error(error, `Failed to check PostHog identify dedup cache for distinctId=${distinctId}`);