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: introduce INFISICAL_RUN_MODES
Matheus Nogueira3b74ba7950b7
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex ee978aa61f..472302c53d 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -541,7 +541,9 @@ Queue handler factories (e.g., `src/services/secret/secret-queue.ts`) follow the`queueService.start(name, handler, opts)` accepts `concurrency` (per-worker parallelism ceiling) and BullMQ's `limiter: { max, duration }` (fleet-wide throughput cap, coordinated via Redis). Use both to **rate-shape DB-heavy background work** so a large backlog drains as an even plateau instead of a burst — see `src/services/project/project-cleanup-queue.ts`. The cron cadence must not be the pacer; load is bounded by `concurrency × per-job cost`, and the limiter caps steady throughput.-**`QUEUE_WORKER_PROFILE` gates the consumer, never the producer.** Whenever workers are enabled, `start()` creates the BullMQ `Queue` for every queue and only skips creating the `Worker` when the queue isn't in this pod's profile. This invariant is what makes splitting the fleet by profile safe: a pod that doesn't consume a queue must still be able to enqueue onto it, since `queue()` silently no-ops on an uninitialized queue (`await q?.add(...)`) and would otherwise drop every job destined for another profile's worker. `QUEUE_WORKERS_ENABLED=false` is the one exception and is deliberately absolute — it returns before the `Queue` is created (`src/queue/queue-service.ts:786`), so such a pod neither consumes *nor* produces, and both `queue()` and `upsertJobScheduler` are no-ops or throw. Code that schedules work at boot must branch on that flag rather than swallowing the failure, so a genuine Redis/BullMQ error still surfaces (see `src/ee/services/audit-log/audit-log-queue.ts`).+**`INFISICAL_RUN_MODES` gates the consumer, never the producer.** `start()` creates the BullMQ `Queue` for every queue in every run mode, and only skips creating the `Worker` when the queue isn't consumed by this pod: `secret-scanning` covers `SECRET_SCANNING_QUEUES`, `general-workers` covers everything else. This invariant is what makes splitting the fleet safe — an API-only pod runs no workers at all but must still be able to enqueue, since `queue()` silently no-ops on an uninitialized queue (`await q?.add(...)`) and would otherwise drop every job destined for another pod's worker. It also means `upsertJobScheduler` works from any pod, so boot-time scheduling needs no run-mode branch.++`QUEUE_WORKERS_ENABLED` and `QUEUE_WORKER_PROFILE` were replaced by `INFISICAL_RUN_MODES` and no longer exist.### Scheduled Jobs (Cron Manager)diff --git a/backend/e2e-test/run-modes.spec.ts b/backend/e2e-test/run-modes.spec.tsnew file mode 100644index 0000000000..cf46d5529a--- /dev/null+++ b/backend/e2e-test/run-modes.spec.ts@@ -0,0 +1,98 @@+import { keyValueStoreDALFactory } from "@app/keystore/key-value-store-dal";+import { keyStoreFactory } from "@app/keystore/keystore";+import { buildClickHouseFromConfig } from "@app/lib/config/clickhouse";+import { initEnvConfig } from "@app/lib/config/env";+import { buildRedisFromConfig } from "@app/lib/config/redis";+import { initLogger } from "@app/lib/logger";+import { RunMode } from "@app/lib/types";+import { queueServiceFactory } from "@app/queue";+import { main } from "@app/server/app";++import { mockSmtpServer } from "./mocks/smtp";++// One route per registration block gated by the api run mode, so dropping the gate on any single+// block fails a case here. `url` is the registered pattern (what hasRoute matches), `requestUrl` a+// concrete path to send.+const API_ROUTES = [+ { method: "GET" as const, url: "/api/v1/admin/config", requestUrl: "/api/v1/admin/config" },+ { method: "GET" as const, url: "/api/v2/users/me/organizations", requestUrl: "/api/v2/users/me/organizations" },+ { method: "GET" as const, url: "/api/v3/secrets/raw", requestUrl: "/api/v3/secrets/raw" },+ { method: "GET" as const, url: "/api/v4/secrets/", requestUrl: "/api/v4/secrets" },+ { method: "POST" as const, url: "/secret-scanning/webhooks/github", requestUrl: "/secret-scanning/webhooks/github" },+ {+ method: "GET" as const,+ url: "/.well-known/est/:identifier/cacerts",+ requestUrl: "/.well-known/est/some-template/cacerts"+ }+];++describe("INFISICAL_RUN_MODES route registration", () => {+ describe("with the api run mode (the shared test server)", () => {+ test("serves the status endpoint", async () => {+ const res = await testServer.inject({ method: "GET", url: "/api/status" });++ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.payload)).toHaveProperty("message", "Ok");+ });++ test("serves the product API", async () => {+ const res = await testServer.inject({ method: "GET", url: "/api/v1/admin/config" });++ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.payload)).toHaveProperty("config");+ });++ test.each(API_ROUTES)("registers $method $url", ({ method, url }) => {+ expect(testServer.hasRoute({ method, url })).toBe(true);+ });+ });++ describe("without the api run mode (a worker-only pod)", () => {+ let workerServer: Awaited<ReturnType<typeof main>>;+ const originalRunModes = process.env.INFISICAL_RUN_MODES;++ beforeAll(async () => {+ // Spec files run in a separate module graph from the shared test server, so re-initializing+ // the env config here rebinds only this file's copy — the running test server is untouched.+ initLogger();+ process.env.INFISICAL_RUN_MODES = `${RunMode.GeneralWorkers},${RunMode.SecretScanning}`;+ const envConfig = await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL);++ workerServer = await main({+ db: testDb,+ smtp: mockSmtpServer(),+ queue: queueServiceFactory(envConfig),+ keyStore: keyStoreFactory(envConfig, keyValueStoreDALFactory(testDb)),+ redis: buildRedisFromConfig(envConfig),+ clickhouse: buildClickHouseFromConfig(envConfig),+ hsmService: testHsmService,+ kmsRootConfigDAL: testKmsRootConfigDAL,+ superAdminDAL: testSuperAdminDAL,+ envConfig+ });+ });++ afterAll(async () => {+ await workerServer?.close();++ if (originalRunModes === undefined) delete process.env.INFISICAL_RUN_MODES;+ else process.env.INFISICAL_RUN_MODES = originalRunModes;+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL);+ });++ test("still serves the status endpoint so probes keep working", async () => {+ const res = await workerServer.inject({ method: "GET", url: "/api/status" });++ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.payload)).toHaveProperty("message", "Ok");+ });++ test.each(API_ROUTES)("does not register $method $url", async ({ method, url, requestUrl }) => {+ expect(workerServer.hasRoute({ method, url })).toBe(false);++ // 404 rather than 401: the route is absent, not merely refusing the caller.+ const res = await workerServer.inject({ method, url: requestUrl });+ expect(res.statusCode).toBe(404);+ });+ });+});diff --git a/backend/src/ee/services/audit-log/audit-log-queue.test.ts b/backend/src/ee/services/audit-log/audit-log-queue.test.tsindex c7babe2740..5adf8017a8 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.test.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.test.ts@@ -11,8 +11,7 @@ const mockConfig = {CLICKHOUSE_AUDIT_LOG_TABLE_NAME: "audit_logs",CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS: {},AUDIT_LOG_STREAMS_ENABLED: false,- DISABLE_POSTGRES_AUDIT_LOG_STORAGE: false,- QUEUE_WORKERS_ENABLED: true+ DISABLE_POSTGRES_AUDIT_LOG_STORAGE: false};vi.mock("@app/lib/config/env", async (importOriginal) => ({@@ -53,10 +52,9 @@ const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => (lastId});-const createHarness = async ({ clickhouse = false, streamsEnabled = false, queueWorkersEnabled = true } = {}) => {+const createHarness = async ({ clickhouse = false, streamsEnabled = false } = {}) => {mockConfig.CLICKHOUSE_AUDIT_LOG_ENABLED = clickhouse;mockConfig.AUDIT_LOG_STREAMS_ENABLED = streamsEnabled;- mockConfig.QUEUE_WORKERS_ENABLED = queueWorkersEnabled;const startHandlers = new Map<string, (job?: unknown) => Promise<void>>();const queueService = {@@ -144,14 +142,6 @@ describe("audit-log-queue construction", () => {expect(queueService.upsertJobScheduler).toHaveBeenCalledTimes(1);});-- test("skips scheduler registration when queue workers are disabled", async () => {- // A pod with workers disabled never initializes the queue, and upsertJobScheduler throws on a- // missing queue; the factory must branch instead of crashing the boot.- const { queueService } = await createHarness({ queueWorkersEnabled: false });-- expect(queueService.upsertJobScheduler).not.toHaveBeenCalled();- });});describe("audit-log-queue pushToLog", () => {diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex 37200d5c34..09f67773a4 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -334,18 +334,12 @@ export const auditLogQueueServiceFactory = async ({// "audit-log-clickhouse-batch" so the existing Redis scheduler key isn't orphaned on upgrade.queueService.start(QueueName.AuditLogClickHouseBatch, consumeAuditLogStream);- // A pod with the workers disabled never initializes the queue, and upsertJobScheduler throws on a- // missing queue.- if (getConfig().QUEUE_WORKERS_ENABLED) {- await queueService.upsertJobScheduler(- QueueName.AuditLogClickHouseBatch,- `${JOB_SCHEDULER_PREFIX}:audit-log-clickhouse-batch`,- { every: 5000 },- { name: QueueJobs.AuditLogClickHouseBatch }- );- } else {- logger.info("audit-log-queue: Skipped audit log batch scheduler registration, queue workers are disabled");- }+ await queueService.upsertJobScheduler(+ QueueName.AuditLogClickHouseBatch,+ `${JOB_SCHEDULER_PREFIX}:audit-log-clickhouse-batch`,+ { every: 5000 },+ { name: QueueJobs.AuditLogClickHouseBatch }+ );return {pushToLogdiff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 3d9b6ceffb..ece2a91be7 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -3,7 +3,7 @@ import { z } from "zod";import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";import { crypto } from "@app/lib/crypto/cryptography";import { initializePqcSupport } from "@app/lib/crypto/pqc";-import { QueueWorkerProfile } from "@app/lib/types";+import { RunMode } from "@app/lib/types";import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";import { TSuperAdminDALFactory } from "@app/services/super-admin/super-admin-dal";@@ -37,6 +37,26 @@ const zodStrBool = z.optional().transform((val) => val === "true");+// Which responsibilities this process takes on, as a comma-separated list. Splitting the fleet by+// run mode is what lets an API pod, a general worker pod and a secret scanning pod share one image.+export const runModesSchema = zpStr(z.string().optional())+ .transform((val) =>+ (val ?? Object.values(RunMode).join(","))+ .split(",")+ .map((mode) => mode.trim().toLowerCase())+ .filter(Boolean)+ )+ .pipe(+ z+ .nativeEnum(RunMode, {+ errorMap: () => ({+ message: `INFISICAL_RUN_MODES must be a comma-separated list of: ${Object.values(RunMode).join(", ")}`+ })+ })+ .array()+ .nonempty("INFISICAL_RUN_MODES must name at least one run mode")+ );+/*** Everything a secret scan spends outside the clone and the scan itself: measuring the clone* (30s ceiling), writing findings, notifications and audit logs, and queue/DB overhead. Used as@@ -203,8 +223,7 @@ const envSchema = z// A convergence window, not a rollback window: it lets instances that have not restarted onto the// new key keep booting, and covers a new key that turns out to be lost. Then the old key is gone.KMS_ROOT_KEY_RETENTION_DAYS: z.coerce.number().int().min(1).max(90).default(7),- QUEUE_WORKERS_ENABLED: zodStrBool.default("true"),- QUEUE_WORKER_PROFILE: z.nativeEnum(QueueWorkerProfile).default(QueueWorkerProfile.All),+ INFISICAL_RUN_MODES: runModesSchema,HTTPS_ENABLED: zodStrBool,ROTATION_DEVELOPMENT_MODE: zodStrBool.default("false").optional(),DAILY_RESOURCE_CLEAN_UP_DEVELOPMENT_MODE: zodStrBool.default("false").optional(),@@ -648,6 +667,9 @@ const envSchema = zdata.NODE_ENV === "development" && data.DAILY_RESOURCE_CLEAN_UP_DEVELOPMENT_MODE,isAcmeDevelopmentMode: data.NODE_ENV === "development" && data.ACME_DEVELOPMENT_MODE,isProductionMode: data.NODE_ENV === "production" || IS_PACKAGED,+ isApiRunModeEnabled: data.INFISICAL_RUN_MODES.includes(RunMode.Api),+ isGeneralWorkerRunModeEnabled: data.INFISICAL_RUN_MODES.includes(RunMode.GeneralWorkers),+ isSecretScanningRunModeEnabled: data.INFISICAL_RUN_MODES.includes(RunMode.SecretScanning),isRedisSentinelMode: Boolean(data.REDIS_SENTINEL_HOSTS),isBddNockApiEnabled: data.NODE_ENV !== "production" && data.BDD_NOCK_API_ENABLED,REDIS_SENTINEL_HOSTS: data.REDIS_SENTINEL_HOSTS?.trim()diff --git a/backend/src/lib/config/run-modes.test.ts b/backend/src/lib/config/run-modes.test.tsnew file mode 100644index 0000000000..669caee999--- /dev/null+++ b/backend/src/lib/config/run-modes.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test } from "vitest";++import { RunMode } from "@app/lib/types";++import { runModesSchema } from "./env";++describe("INFISICAL_RUN_MODES parsing", () => {+ test("defaults to every run mode when unset", () => {+ expect(runModesSchema.parse(undefined)).toEqual([RunMode.Api, RunMode.GeneralWorkers, RunMode.SecretScanning]);+ });++ test("defaults to every run mode when blank", () => {+ expect(runModesSchema.parse(" ")).toEqual([RunMode.Api, RunMode.GeneralWorkers, RunMode.SecretScanning]);+ });++ test("parses a single run mode", () => {+ expect(runModesSchema.parse("api")).toEqual([RunMode.Api]);+ });++ test("tolerates surrounding whitespace and casing", () => {+ expect(runModesSchema.parse(" General-Workers , secret-scanning ")).toEqual([+ RunMode.GeneralWorkers,+ RunMode.SecretScanning+ ]);+ });++ test("rejects an unknown run mode instead of silently ignoring it", () => {+ const result = runModesSchema.safeParse("api,workers");++ expect(result.success).toBe(false);+ if (!result.success) {+ expect(result.error.issues[0].message).toContain("api, general-workers, secret-scanning");+ }+ });++ test("rejects a list that names no run mode", () => {+ expect(runModesSchema.safeParse(",,").success).toBe(false);+ });+});diff --git a/backend/src/lib/types/index.ts b/backend/src/lib/types/index.tsindex 5fbe8ca799..d8d218158d 100644--- a/backend/src/lib/types/index.ts+++ b/backend/src/lib/types/index.ts@@ -89,9 +89,9 @@ export type ProjectServiceActor = {orgId: string;};-export enum QueueWorkerProfile {- All = "all",- Standard = "standard",+export enum RunMode {+ Api = "api",+ GeneralWorkers = "general-workers",SecretScanning = "secret-scanning"}diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 0d71807eb7..cc1a7d9663 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -38,7 +38,7 @@ import {queueStalledCounter,resolveCoreMeter} from "@app/lib/telemetry/metrics";-import { QueueWorkerProfile } from "@app/lib/types";+import {TAppConnectionCredentialRotationRotateJobPayload,TAppConnectionCredentialRotationSendNotificationJobPayload@@ -602,20 +602,11 @@ const SECRET_SCANNING_QUEUES = [QueueName.SecretPushEventScan];-const NON_STANDARD_QUEUES = [...SECRET_SCANNING_QUEUES];-const isQueueEnabled = (name: QueueName) => {const appCfg = getConfig();- switch (appCfg.QUEUE_WORKER_PROFILE) {- case QueueWorkerProfile.Standard:- return !NON_STANDARD_QUEUES.includes(name);- case QueueWorkerProfile.SecretScanning:- return SECRET_SCANNING_QUEUES.includes(name);- case QueueWorkerProfile.All:- default:- // allow all- return true;- }+ return SECRET_SCANNING_QUEUES.includes(name)+ ? appCfg.isSecretScanningRunModeEnabled+ : appCfg.isGeneralWorkerRunModeEnabled;};export type TQueueServiceFactory = {@@ -806,15 +797,11 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFathrow new Error(`${name} queue is already initialized`);}- const appCfg = getConfig();-- if (!appCfg.QUEUE_WORKERS_ENABLED) return;-const fipsSettings = crypto.isFipsModeEnabled() ? { settings: { repeatKeyHashAlgorithm: "sha256" as const } } : {};- // The Queue (producer) is created regardless of worker profile — only the Worker (consumer) is+ // The Queue (producer) is created regardless of run mode — only the Worker (consumer) is// gated below. A pod that doesn't consume a queue must still be able to enqueue onto it, or- // splitting the fleet by profile silently drops every job destined for another profile's worker.+ // splitting the fleet by run mode silently drops every job destined for another pod's worker.queueContainer[name] = new Queue(name as string, {prefix: isClusterMode ? `{${name}}` : undefined,...queueSettings,@@ -885,8 +872,7 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa};const listen: TQueueServiceFactory["listen"] = (name, event, listener) => {- const appCfg = getConfig();- if (!appCfg.QUEUE_WORKERS_ENABLED || !isQueueEnabled(name)) {+ if (!isQueueEnabled(name)) {return;}diff --git a/backend/src/server/app.ts b/backend/src/server/app.tsindex 3cc47e4c55..3e4bdb50b5 100644--- a/backend/src/server/app.ts+++ b/backend/src/server/app.ts@@ -181,10 +181,12 @@ export const main = async ({kmsRootConfigDAL});- await server.register(registerServeUI, {- standaloneMode: appCfg.STANDALONE_MODE || IS_PACKAGED,- dir: path.join(__dirname, IS_PACKAGED ? "../../../" : "../../")- });+ if (appCfg.isApiRunModeEnabled) {+ await server.register(registerServeUI, {+ standaloneMode: appCfg.STANDALONE_MODE || IS_PACKAGED,+ dir: path.join(__dirname, IS_PACKAGED ? "../../../" : "../../")+ });+ }await server.ready();server.swagger();diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 73b42880ff..e51cf0de57 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -591,9 +591,11 @@ export const registerRoutes = async (// singleton rather than threaded through every call site.const gatewayLoadTracker = initGatewayLoadTracker(keyStore);- await server.register(registerSecretScanningV2Webhooks, {- prefix: "/secret-scanning/webhooks"- });+ if (envConfig.isApiRunModeEnabled) {+ await server.register(registerSecretScanningV2Webhooks, {+ prefix: "/secret-scanning/webhooks"+ });+ }// db layersconst userDAL = userDALFactory(db);@@ -4349,38 +4351,43 @@ export const registerRoutes = async (}});- // register special routes- await server.register(registerCertificateEstRouter, { prefix: "/.well-known/est" });- await server.register(registerPkiScepRouter, { prefix: "/scep" });-- // register routes for v1- await server.register(- async (v1Server) => {- await v1Server.register(registerV1EERoutes);- await v1Server.register(registerV1Routes);- },- { prefix: "/api/v1" }- );- await server.register(- async (v2Server) => {- await v2Server.register(registerV2EERoutes);- await v2Server.register(registerV2Routes);- },- { prefix: "/api/v2" }- );- await server.register(- async (v3Server) => {- await v3Server.register(registerV3EERoutes);- await v3Server.register(registerV3Routes);- },- { prefix: "/api/v3" }- );- await server.register(registerV4Routes, { prefix: "/api/v4" });+ // A worker-only pod still serves /api/status so liveness and readiness probes keep working, but+ // none of the product API. Everything above this point (service wiring, queue workers, crons) runs+ // in every run mode.+ if (envConfig.isApiRunModeEnabled) {+ // register special routes+ await server.register(registerCertificateEstRouter, { prefix: "/.well-known/est" });+ await server.register(registerPkiScepRouter, { prefix: "/scep" });++ // register routes for v1+ await server.register(+ async (v1Server) => {+ await v1Server.register(registerV1EERoutes);+ await v1Server.register(registerV1Routes);+ },+ { prefix: "/api/v1" }+ );+ await server.register(+ async (v2Server) => {+ await v2Server.register(registerV2EERoutes);+ await v2Server.register(registerV2Routes);+ },+ { prefix: "/api/v2" }+ );+ await server.register(+ async (v3Server) => {+ await v3Server.register(registerV3EERoutes);+ await v3Server.register(registerV3Routes);+ },+ { prefix: "/api/v3" }+ );+ await server.register(registerV4Routes, { prefix: "/api/v4" });- // Note: This is a special route for BDD tests. It's only available in development mode and only for BDD tests.- // This route should NEVER BE ENABLED IN PRODUCTION!- if (getConfig().isBddNockApiEnabled) {- await server.register(registerBddNockRouter, { prefix: "/api/__bdd_nock__" });+ // Note: This is a special route for BDD tests. It's only available in development mode and only for BDD tests.+ // This route should NEVER BE ENABLED IN PRODUCTION!+ if (getConfig().isBddNockApiEnabled) {+ await server.register(registerBddNockRouter, { prefix: "/api/__bdd_nock__" });+ }}server.addHook("onClose", async () => {