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
feat(cache): implement withCache utility for caching logic with error handling and logging; add tests for various cache scenarios
Victor Hugo dos Santos6f8fc7ce42fd
diff --git a/backend/src/lib/cache/with-cache.test.ts b/backend/src/lib/cache/with-cache.test.tsnew file mode 100644index 0000000000..3f01f76274--- /dev/null+++ b/backend/src/lib/cache/with-cache.test.ts@@ -0,0 +1,237 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { withCache } from "./with-cache";++vi.mock("@app/lib/logger", () => ({+ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }+}));++describe("withCache", () => {+ let mockKeyStore: {+ getItem: ReturnType<typeof vi.fn>;+ setItemWithExpiry: ReturnType<typeof vi.fn>;+ };++ beforeEach(() => {+ mockKeyStore = {+ getItem: vi.fn(),+ setItemWithExpiry: vi.fn().mockResolvedValue("OK")+ };+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("should return cached value on cache hit without calling fetcher", async () => {+ const data = { id: "123", name: "test" };+ mockKeyStore.getItem.mockResolvedValue(JSON.stringify(data));+ const fetcher = vi.fn();++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "test-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toEqual(data);+ expect(fetcher).not.toHaveBeenCalled();+ expect(mockKeyStore.setItemWithExpiry).not.toHaveBeenCalled();+ });++ it("should call fetcher and write to cache on cache miss", async () => {+ const data = { id: "456", items: [1, 2, 3] };+ mockKeyStore.getItem.mockResolvedValue(null);+ const fetcher = vi.fn().mockResolvedValue(data);++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "miss-key",+ ttlSeconds: 120,+ fetcher+ });++ expect(result).toEqual(data);+ expect(fetcher).toHaveBeenCalledOnce();+ expect(mockKeyStore.setItemWithExpiry).toHaveBeenCalledWith("miss-key", 120, JSON.stringify(data));+ });++ it("should fall back to fetcher when cache read throws", async () => {+ const data = { fallback: true };+ mockKeyStore.getItem.mockRejectedValue(new Error("Redis connection refused"));+ const fetcher = vi.fn().mockResolvedValue(data);++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "error-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toEqual(data);+ expect(fetcher).toHaveBeenCalledOnce();+ });++ it("should still return fetcher result when cache write throws", async () => {+ const data = { writeFailOk: true };+ mockKeyStore.getItem.mockResolvedValue(null);+ mockKeyStore.setItemWithExpiry.mockRejectedValue(new Error("Redis write failed"));+ const fetcher = vi.fn().mockResolvedValue(data);++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "write-fail-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toEqual(data);+ expect(fetcher).toHaveBeenCalledOnce();+ });++ it("should propagate fetcher errors without catching them", async () => {+ mockKeyStore.getItem.mockResolvedValue(null);+ const fetcherError = new Error("DB connection failed");+ const fetcher = vi.fn().mockRejectedValue(fetcherError);++ await expect(+ withCache({+ keyStore: mockKeyStore,+ key: "fetcher-error-key",+ ttlSeconds: 60,+ fetcher+ })+ ).rejects.toThrow("DB connection failed");+ });++ it("should pass the correct TTL to setItemWithExpiry", async () => {+ mockKeyStore.getItem.mockResolvedValue(null);+ const fetcher = vi.fn().mockResolvedValue("value");++ await withCache({+ keyStore: mockKeyStore,+ key: "ttl-key",+ ttlSeconds: 300,+ fetcher+ });++ expect(mockKeyStore.setItemWithExpiry).toHaveBeenCalledWith("ttl-key", 300, JSON.stringify("value"));+ });++ it("should handle primitive cached values (string)", async () => {+ mockKeyStore.getItem.mockResolvedValue(JSON.stringify("hello"));+ const fetcher = vi.fn();++ const result = await withCache<string>({+ keyStore: mockKeyStore,+ key: "string-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toBe("hello");+ expect(fetcher).not.toHaveBeenCalled();+ });++ it("should handle primitive cached values (number)", async () => {+ mockKeyStore.getItem.mockResolvedValue(JSON.stringify(42));+ const fetcher = vi.fn();++ const result = await withCache<number>({+ keyStore: mockKeyStore,+ key: "number-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toBe(42);+ expect(fetcher).not.toHaveBeenCalled();+ });++ it("should handle array values", async () => {+ const arr = [1, "two", { three: 3 }];+ mockKeyStore.getItem.mockResolvedValue(null);+ const fetcher = vi.fn().mockResolvedValue(arr);++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "array-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toEqual(arr);+ });++ it("should handle null fetcher result", async () => {+ mockKeyStore.getItem.mockResolvedValue(null);+ const fetcher = vi.fn().mockResolvedValue(null);++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "null-result-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toBeNull();+ expect(mockKeyStore.setItemWithExpiry).toHaveBeenCalledWith("null-result-key", 60, "null");+ });++ it("should return null from cache when null was previously cached", async () => {+ mockKeyStore.getItem.mockResolvedValue("null");+ const fetcher = vi.fn();++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "cached-null-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toBeNull();+ expect(fetcher).not.toHaveBeenCalled();+ });++ it("should fall back to fetcher when cached value is invalid JSON", async () => {+ const data = { valid: true };+ mockKeyStore.getItem.mockResolvedValue("not-valid-json{{{");+ const fetcher = vi.fn().mockResolvedValue(data);++ const result = await withCache({+ keyStore: mockKeyStore,+ key: "bad-json-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(result).toEqual(data);+ expect(fetcher).toHaveBeenCalledOnce();+ });++ it("should log warnings on cache read and write failures", async () => {+ const { logger } = await import("@app/lib/logger");++ mockKeyStore.getItem.mockRejectedValue(new Error("read error"));+ mockKeyStore.setItemWithExpiry.mockRejectedValue(new Error("write error"));+ const fetcher = vi.fn().mockResolvedValue({ ok: true });++ await withCache({+ keyStore: mockKeyStore,+ key: "log-test-key",+ ttlSeconds: 60,+ fetcher+ });++ expect(logger.warn).toHaveBeenCalledTimes(2);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.objectContaining({ key: "log-test-key" }),+ expect.stringContaining("cache read failed")+ );+ expect(logger.warn).toHaveBeenCalledWith(+ expect.objectContaining({ key: "log-test-key" }),+ expect.stringContaining("cache write failed")+ );+ });+});diff --git a/backend/src/lib/cache/with-cache.ts b/backend/src/lib/cache/with-cache.tsnew file mode 100644index 0000000000..f976297e6a--- /dev/null+++ b/backend/src/lib/cache/with-cache.ts@@ -0,0 +1,35 @@+import { TKeyStoreFactory } from "@app/keystore/keystore";+import { logger } from "@app/lib/logger";++type TWithCacheOpts<T> = {+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;+ key: string;+ ttlSeconds: number;+ fetcher: () => Promise<T>;+};++/**+ * Cache-aside helper: attempts to read from Redis, falls back to the fetcher on miss or Redis failure,+ * and writes the result back to Redis. Redis errors are caught and logged — the fetcher is always the+ * source of truth.+ */+export const withCache = async <T>({ keyStore, key, ttlSeconds, fetcher }: TWithCacheOpts<T>): Promise<T> => {+ try {+ const cached = await keyStore.getItem(key);+ if (cached !== null) {+ return JSON.parse(cached) as T;+ }+ } catch (err) {+ logger.warn({ key, err }, `withCache: cache read failed, falling back to fetcher [key=${key}]`);+ }++ const result = await fetcher();++ try {+ await keyStore.setItemWithExpiry(key, ttlSeconds, JSON.stringify(result));+ } catch (err) {+ logger.warn({ key, err }, `withCache: cache write failed [key=${key}]`);+ }++ return result;+};diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.tsindex e7fdf20b4b..d89cae3d47 100644--- a/backend/src/services/super-admin/super-admin-service.ts+++ b/backend/src/services/super-admin/super-admin-service.ts@@ -11,6 +11,7 @@ import {} from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";+import { withCache } from "@app/lib/cache/with-cache";import {getConfig,getOriginalConfig,@@ -150,26 +151,25 @@ export const superAdminServiceFactory = ({const initServerCfg = async () => {// TODO(akhilmhdh): bad pattern time less change this later to me itselfgetServerCfg = async () => {- const config = await keyStore.getItem(ADMIN_CONFIG_KEY);-- // missing in keystore means fetch from db- if (!config) {- const serverCfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);-- if (!serverCfg) {- throw new NotFoundError({ message: "Admin config not found" });+ const serverCfg = await withCache({+ keyStore,+ key: ADMIN_CONFIG_KEY,+ ttlSeconds: ADMIN_CONFIG_KEY_EXP,+ fetcher: async () => {+ const cfg = await serverCfgDAL.findById(ADMIN_CONFIG_DB_UUID);+ if (!cfg) {+ throw new NotFoundError({ message: "Admin config not found" });+ }+ return cfg;}+ });- await keyStore.setItemWithExpiry(ADMIN_CONFIG_KEY, ADMIN_CONFIG_KEY_EXP, JSON.stringify(serverCfg)); // insert it back to keystore- return serverCfg;- }-- const keyStoreServerCfg = JSON.parse(config) as TSuperAdmin & { defaultAuthOrgSlug: string | null };+ // Normalize dates — on cache hit they arrive as ISO strings from JSON.parse,+ // on miss they are already Date objects. new Date() handles both.return {- ...keyStoreServerCfg,- // this is to allow admin router to work- createdAt: new Date(keyStoreServerCfg.createdAt),- updatedAt: new Date(keyStoreServerCfg.updatedAt)+ ...serverCfg,+ createdAt: new Date(serverCfg.createdAt),+ updatedAt: new Date(serverCfg.updatedAt)};};diff --git a/backend/src/services/upgrade-path/upgrade-path-service.ts b/backend/src/services/upgrade-path/upgrade-path-service.tsindex 45c602d785..f75565dc6c 100644--- a/backend/src/services/upgrade-path/upgrade-path-service.ts+++ b/backend/src/services/upgrade-path/upgrade-path-service.ts@@ -5,10 +5,11 @@ import RE2 from "re2";import { z } from "zod";import { TKeyStoreFactory } from "@app/keystore/keystore";+import { withCache } from "@app/lib/cache/with-cache";import { logger } from "@app/lib/logger";import { fetchReleases } from "./github-client";-import { BreakingChange, FormattedRelease, UpgradePathConfig, UpgradePathResult, VersionConfig } from "./types";+import { BreakingChange, FormattedRelease, UpgradePathConfig, UpgradePathResult } from "./types";import { versionConfigSchema, versionSchema } from "./upgrade-path-schemas";export type TUpgradePathServiceFactory = {@@ -52,42 +53,35 @@ export const upgradePathServiceFactory = ({ keyStore }: TUpgradePathServiceFacto};const getUpgradePathConfig = async (): Promise<Record<string, z.infer<typeof versionConfigSchema>>> => {- const cacheKey = "upgrade-path:config";-- try {- const cached = await keyStore.getItem(cacheKey);- if (cached) return JSON.parse(cached) as Record<string, VersionConfig>;- } catch (error) {- logger.error(error, "Failed to retrieve config from cache");- }-- try {- const yamlPath = path.join(__dirname, "..", "..", "..", "upgrade-path.yaml");- const resolvedPath = path.resolve(yamlPath);- const expectedBaseDir = path.resolve(__dirname, "..", "..", "..");- if (!resolvedPath.startsWith(expectedBaseDir)) {- throw new Error("Invalid configuration file path");- }+ return withCache({+ keyStore,+ key: "upgrade-path:config",+ ttlSeconds: 24 * 60 * 60,+ fetcher: async () => {+ try {+ const yamlPath = path.join(__dirname, "..", "..", "..", "upgrade-path.yaml");+ const resolvedPath = path.resolve(yamlPath);+ const expectedBaseDir = path.resolve(__dirname, "..", "..", "..");+ if (!resolvedPath.startsWith(expectedBaseDir)) {+ throw new Error("Invalid configuration file path");+ }- const yamlContent = await readFile(yamlPath, "utf8");+ const yamlContent = await readFile(yamlPath, "utf8");- if (yamlContent.length > 1024 * 1024) {- throw new Error("Config file too large");- }-- const config = yaml.load(yamlContent, { schema: yaml.FAILSAFE_SCHEMA }) as UpgradePathConfig;- const versionConfig = config?.versions || {};+ if (yamlContent.length > 1024 * 1024) {+ throw new Error("Config file too large");+ }- await keyStore.setItemWithExpiry(cacheKey, 24 * 60 * 60, JSON.stringify(versionConfig));- return versionConfig;- } catch (error) {- if (error instanceof Error && "code" in error && error.code === "ENOENT") {- const empty = {};- await keyStore.setItemWithExpiry(cacheKey, 24 * 60 * 60, JSON.stringify(empty));- return empty;+ const config = yaml.load(yamlContent, { schema: yaml.FAILSAFE_SCHEMA }) as UpgradePathConfig;+ return config?.versions || {};+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {+ return {};+ }+ throw new Error(`Config load failed: ${error instanceof Error ? error.message : "Unknown error"}`);+ }}- throw new Error(`Config load failed: ${error instanceof Error ? error.message : "Unknown error"}`);- }+ });};const normalizeVersion = (version: string): string => {@@ -124,131 +118,128 @@ export const upgradePathServiceFactory = ({ keyStore }: TUpgradePathServiceFactoconst { fromVersion, toVersion } = validateParams(params);const cacheKey = sanitizeCacheKey(`upgrade-path:${fromVersion}:${toVersion}`);- try {- const cached = await keyStore.getItem(cacheKey);- if (cached) return JSON.parse(cached) as UpgradePathResult;- } catch (error) {- logger.error(error, "Failed to retrieve upgrade path from cache");- }+ return withCache({+ keyStore,+ key: cacheKey,+ ttlSeconds: 60 * 60,+ fetcher: async () => {+ const [releases, config] = await Promise.all([getGitHubReleases(), getUpgradePathConfig()]);- const [releases, config] = await Promise.all([getGitHubReleases(), getUpgradePathConfig()]);+ const cleanFrom = normalizeVersion(fromVersion);+ const cleanTo = normalizeVersion(toVersion);- const cleanFrom = normalizeVersion(fromVersion);- const cleanTo = normalizeVersion(toVersion);+ const compareVersions = (v1: string, v2: string): number => {+ const normalize = (v: string) => normalizeVersion(v);+ const clean1 = normalize(v1);+ const clean2 = normalize(v2);- const compareVersions = (v1: string, v2: string): number => {- const normalize = (v: string) => normalizeVersion(v);- const clean1 = normalize(v1);- const clean2 = normalize(v2);+ const parts1 = clean1.split(".").map(Number);+ const parts2 = clean2.split(".").map(Number);- const parts1 = clean1.split(".").map(Number);- const parts2 = clean2.split(".").map(Number);+ const maxLength = Math.max(parts1.length, parts2.length);+ while (parts1.length < maxLength) parts1.push(0);+ while (parts2.length < maxLength) parts2.push(0);- const maxLength = Math.max(parts1.length, parts2.length);- while (parts1.length < maxLength) parts1.push(0);- while (parts2.length < maxLength) parts2.push(0);+ for (let i = 0; i < maxLength; i += 1) {+ if (parts1[i] > parts2[i]) return 1;+ if (parts1[i] < parts2[i]) return -1;+ }+ return 0;+ };- for (let i = 0; i < maxLength; i += 1) {- if (parts1[i] > parts2[i]) return 1;- if (parts1[i] < parts2[i]) return -1;- }- return 0;- };+ if (compareVersions(cleanFrom, cleanTo) >= 0) {+ throw new Error("fromVersion must be older than toVersion");+ }- if (compareVersions(cleanFrom, cleanTo) >= 0) {- throw new Error("fromVersion must be older than toVersion");- }+ const fromIdx = releases.findIndex((r) => normalizeVersion(r.normalizedTagName) === cleanFrom);+ const toIdx = releases.findIndex((r) => normalizeVersion(r.normalizedTagName) === cleanTo);- const fromIdx = releases.findIndex((r) => normalizeVersion(r.normalizedTagName) === cleanFrom);- const toIdx = releases.findIndex((r) => normalizeVersion(r.normalizedTagName) === cleanTo);+ let upgradePath: FormattedRelease[] = [];+ const filteredPath: FormattedRelease[] = [];- let upgradePath: FormattedRelease[] = [];- const filteredPath: FormattedRelease[] = [];+ if (fromIdx !== -1 && toIdx !== -1) {+ if (fromIdx <= toIdx) throw new Error("Invalid version order");+ upgradePath = releases.slice(toIdx, fromIdx + 1).reverse();+ const [first, last] = [upgradePath[0], upgradePath[upgradePath.length - 1]];- if (fromIdx !== -1 && toIdx !== -1) {- if (fromIdx <= toIdx) throw new Error("Invalid version order");- upgradePath = releases.slice(toIdx, fromIdx + 1).reverse();- const [first, last] = [upgradePath[0], upgradePath[upgradePath.length - 1]];+ filteredPath.push(first);+ if (last !== first) filteredPath.push(last);+ }- filteredPath.push(first);- if (last !== first) filteredPath.push(last);- }+ const breakingChanges: Array<{ version: string; changes: BreakingChange[] }> = [];+ const features: Array<{ version: string; name: string; body: string; publishedAt: string }> = [];+ let hasDbMigration = false;++ const isVersionInRange = (version: string, fromVer: string, toVer: string): boolean => {+ const versionComp = compareVersions(version, fromVer);+ const toVersionComp = compareVersions(version, toVer);+ return versionComp > 0 && toVersionComp < 0;+ };++ Object.keys(config).forEach((configVersion) => {+ const versionConfig = config[configVersion];+ if (versionConfig?.breaking_changes?.length) {+ if (isVersionInRange(configVersion, cleanFrom, cleanTo)) {+ breakingChanges.push({+ version: configVersion,+ changes: versionConfig.breaking_changes+ });+ }+ }+ });+ for (let i = 0; i < upgradePath.length; i += 1) {+ const version = upgradePath[i];+ const isFromVersion = normalizeVersion(version.normalizedTagName) === cleanFrom;++ if (!isFromVersion) {+ const versionNumber = normalizeVersion(version.tagName);+ const possibleKeys = [+ version.tagName,+ version.normalizedTagName,+ versionNumber,+ `v${versionNumber}`,+ version.tagName.replace(new RE2(/^infisical\//), ""),+ version.tagName.replace(new RE2(/^infisical\/v?/), "").replace(new RE2(/-[a-zA-Z]+$/), "")+ ];++ for (const key of possibleKeys) {+ const versionConfig = config[key];+ if (+ versionConfig?.db_schema_changes &&+ typeof versionConfig.db_schema_changes === "string" &&+ versionConfig.db_schema_changes.trim()+ ) {+ hasDbMigration = true;+ break;+ }+ }+ }- const breakingChanges: Array<{ version: string; changes: BreakingChange[] }> = [];- const features: Array<{ version: string; name: string; body: string; publishedAt: string }> = [];- let hasDbMigration = false;-- const isVersionInRange = (version: string, fromVer: string, toVer: string): boolean => {- const versionComp = compareVersions(version, fromVer);- const toVersionComp = compareVersions(version, toVer);- return versionComp > 0 && toVersionComp < 0;- };-- Object.keys(config).forEach((configVersion) => {- const versionConfig = config[configVersion];- if (versionConfig?.breaking_changes?.length) {- if (isVersionInRange(configVersion, cleanFrom, cleanTo)) {- breakingChanges.push({- version: configVersion,- changes: versionConfig.breaking_changes- });- }- }- });- for (let i = 0; i < upgradePath.length; i += 1) {- const version = upgradePath[i];- const isFromVersion = normalizeVersion(version.normalizedTagName) === cleanFrom;-- if (!isFromVersion) {- const versionNumber = normalizeVersion(version.tagName);- const possibleKeys = [- version.tagName,- version.normalizedTagName,- versionNumber,- `v${versionNumber}`,- version.tagName.replace(new RE2(/^infisical\//), ""),- version.tagName.replace(new RE2(/^infisical\/v?/), "").replace(new RE2(/-[a-zA-Z]+$/), "")- ];-- for (const key of possibleKeys) {- const versionConfig = config[key];- if (- versionConfig?.db_schema_changes &&- typeof versionConfig.db_schema_changes === "string" &&- versionConfig.db_schema_changes.trim()- ) {- hasDbMigration = true;- break;+ // Collect release notes and features+ if (version.body) {+ features.push({+ version: version.tagName,+ name: version.name,+ body: version.body,+ publishedAt: version.publishedAt+ });}}- }- // Collect release notes and features- if (version.body) {- features.push({- version: version.tagName,- name: version.name,- body: version.body,- publishedAt: version.publishedAt- });+ return {+ path: filteredPath.map((r) => ({+ version: r.tagName,+ name: r.name,+ publishedAt: r.publishedAt,+ prerelease: r.prerelease+ })),+ breakingChanges,+ features,+ hasDbMigration,+ config+ };}- }-- const result: UpgradePathResult = {- path: filteredPath.map((r) => ({- version: r.tagName,- name: r.name,- publishedAt: r.publishedAt,- prerelease: r.prerelease- })),- breakingChanges,- features,- hasDbMigration,- config- };-- await keyStore.setItemWithExpiry(cacheKey, 60 * 60, JSON.stringify(result));- return result;+ });};return {