Skip to content

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

fix(secret-scanning): address review feedback on scan resource bounds

Scott Wilsone7bdc880d9ea
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.ts
index dc162f5b83..c7babe2740 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,7 +11,8 @@ 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
+ DISABLE_POSTGRES_AUDIT_LOG_STORAGE: false,
+ QUEUE_WORKERS_ENABLED: true
};
vi.mock("@app/lib/config/env", async (importOriginal) => ({
@@ -52,9 +53,10 @@ const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => (
lastId
});
-const createHarness = async ({ clickhouse = false, streamsEnabled = false } = {}) => {
+const createHarness = async ({ clickhouse = false, streamsEnabled = false, queueWorkersEnabled = true } = {}) => {
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 = {
@@ -136,6 +138,22 @@ beforeEach(() => {
vi.clearAllMocks();
});
+describe("audit-log-queue construction", () => {
+ test("registers the batch scheduler when queue workers are enabled", async () => {
+ const { queueService } = await createHarness();
+
+ 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", () => {
test("resolves the entry and appends it with a pinned id, ISO timestamps, and orgId", async () => {
const { service, keyStore } = await createHarness();
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index 8c78b81217..d2dafc0b36 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -91,13 +91,13 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
auditLogsRetentionDays: 0,
auditLogStreams: false,
auditLogStreamLimit: 3,
- samlSSO: false,
+ samlSSO: true,
enforceGoogleSSO: false,
hsm: false,
oidcSSO: false,
- scim: false,
+ scim: true,
ldap: false,
- groups: false,
+ groups: true,
status: null,
trial_end: null,
has_used_trial: true,
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts
index c1cfc31589..86fe51eac5 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts
@@ -1,4 +1,7 @@
-import { describe, expect, test } from "vitest";
+import { mkdtemp, rm } from "fs/promises";
+import { tmpdir } from "os";
+import { join } from "path";
+import { describe, expect, test, vi } from "vitest";
import {
SecretScanningExecError,
@@ -6,7 +9,23 @@ import {
SecretScanningExecPhase
} from "@app/ee/services/secret-scanning/secret-scanning-exec";
-import { parseScanErrorMessage, SecretScanningSizeLimitError } from "./secret-scanning-v2-fns";
+import {
+ assertClonedRepositoryWithinSizeLimit,
+ parseScanErrorMessage,
+ SecretScanningSizeLimitError
+} from "./secret-scanning-v2-fns";
+
+// getConfig is read lazily inside the functions under test; only the size limit matters here.
+const mockConfig = { SECRET_SCANNING_MAX_REPO_SIZE_MB: 5120 };
+
+vi.mock("@app/lib/config/env", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/lib/config/env")>()),
+ getConfig: () => mockConfig
+}));
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
describe("parseScanErrorMessage", () => {
test("maps a scan timeout to an actionable message without leaking the command line", () => {
@@ -81,6 +100,21 @@ describe("parseScanErrorMessage", () => {
expect(message).toContain("5120 MB scanning limit");
});
+ test("renders sub-minute ceilings in seconds instead of a rounded zero", () => {
+ const message = parseScanErrorMessage(
+ new SecretScanningExecError({
+ failure: SecretScanningExecFailure.Timeout,
+ phase: SecretScanningExecPhase.Scan,
+ command: "infisical",
+ output: "",
+ timeoutMs: 3_000
+ })
+ );
+
+ expect(message).toContain("3 second time limit");
+ expect(message).not.toContain("0 minute");
+ });
+
test("truncates an oversized message", () => {
const message = parseScanErrorMessage(new Error("x".repeat(2000)));
@@ -88,3 +122,31 @@ describe("parseScanErrorMessage", () => {
expect(message.endsWith("...")).toBe(true);
});
});
+
+describe("assertClonedRepositoryWithinSizeLimit", () => {
+ // `git count-objects` in a plain directory exits 128, standing in for any measurement failure.
+ test("fails open when the size limit is disabled and the measurement cannot run", async () => {
+ mockConfig.SECRET_SCANNING_MAX_REPO_SIZE_MB = 0;
+ const dir = await mkdtemp(join(tmpdir(), "e2e-not-a-repo-"));
+
+ try {
+ await expect(assertClonedRepositoryWithinSizeLimit("acme/app", dir)).resolves.toBeUndefined();
+ } finally {
+ mockConfig.SECRET_SCANNING_MAX_REPO_SIZE_MB = 5120;
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("fails closed when the limit is enforced and the measurement cannot run", async () => {
+ mockConfig.SECRET_SCANNING_MAX_REPO_SIZE_MB = 5120;
+ const dir = await mkdtemp(join(tmpdir(), "e2e-not-a-repo-"));
+
+ try {
+ await expect(assertClonedRepositoryWithinSizeLimit("acme/app", dir)).rejects.toBeInstanceOf(
+ SecretScanningExecError
+ );
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.ts
index 026932acfe..e514780064 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.ts
@@ -107,11 +107,28 @@ const SizePackRegex = new RE2(/^size-pack:\s*(\d+)/m);
* each scan.
*/
export const assertClonedRepositoryWithinSizeLimit = async (resourceName: string, repoPath: string) => {
- const output = await execFileBounded("git", ["count-objects", "-v"], {
- phase: SecretScanningExecPhase.Measure,
- cwd: repoPath,
- timeoutMs: 30_000
- });
+ let output: string;
+
+ try {
+ output = await execFileBounded("git", ["count-objects", "-v"], {
+ phase: SecretScanningExecPhase.Measure,
+ cwd: repoPath,
+ timeoutMs: 30_000
+ });
+ } catch (error) {
+ // With the limit disabled the measurement is informational only (it feeds the scan log), so a
+ // measurement failure must not fail a scan the operator explicitly chose not to bound. With the
+ // limit enabled this is the enforcement backstop and stays fail-closed.
+ if (!getConfig().SECRET_SCANNING_MAX_REPO_SIZE_MB) {
+ logger.warn(
+ error,
+ `secretScanningV2: Repository measurement failed with the size limit disabled, continuing [resourceName=${resourceName}]`
+ );
+ return undefined;
+ }
+
+ throw error;
+ }
const match = SizePackRegex.match(output);
@@ -258,6 +275,14 @@ const GitAuthFailureRegex = new RE2(
);
const GitNotFoundRegex = new RE2(/repository not found|remote: Not Found|does not appear to be a git repository/i);
+// "10 minute time limit" for the defaults, "30 second time limit" for sub-minute ceilings, which
+// would otherwise round to a nonsensical "0 minute time limit".
+const formatTimeoutLimit = (timeoutMs: number) => {
+ const minutes = Math.round(timeoutMs / 60_000);
+ if (minutes >= 1) return `${minutes} minute`;
+ return `${Math.max(1, Math.round(timeoutMs / 1_000))} second`;
+};
+
/**
* Maps a scan failure onto a message the customer can act on. Command lines and raw scanner/git
* output never reach this return value — they stay in the logs attached to the original error.
@@ -272,10 +297,10 @@ const parseExecErrorMessage = (err: SecretScanningExecError): string => {
const isClone = err.phase === SecretScanningExecPhase.Clone;
if (err.failure === SecretScanningExecFailure.Timeout) {
- const minutes = Math.round((err.timeoutMs ?? 0) / 60_000);
+ const limit = formatTimeoutLimit(err.timeoutMs ?? 0);
return isClone
- ? `Cloning the repository exceeded the ${minutes} minute time limit and was cancelled. The repository is likely too large to scan.`
- : `The scan exceeded the ${minutes} minute time limit and was cancelled. The repository is likely too large to scan in full.`;
+ ? `Cloning the repository exceeded the ${limit} time limit and was cancelled. The repository is likely too large to scan.`
+ : `The scan exceeded the ${limit} time limit and was cancelled. The repository is likely too large to scan in full.`;
}
if (err.failure === SecretScanningExecFailure.Spawn) {
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
index 147943cc1d..3d1ae084f8 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
@@ -13,7 +13,7 @@ import {
scanGitRepositoryAndGetFindings
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-fns";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
-import { getConfig } from "@app/lib/config/env";
+import { getConfig, SECRET_SCANNING_SCAN_OVERHEAD_MS } from "@app/lib/config/env";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -62,17 +62,18 @@ type TSecretRotationV2QueueServiceFactoryDep = {
export type TSecretScanningV2QueueServiceFactory = ReturnType<typeof secretScanningV2QueueServiceFactory>;
-// The lock has to outlive the worst case a scan can now take — clone timeout plus scan timeout —
-// or it expires mid-scan and a second scan of the same resource can start alongside the first.
-const SCAN_LOCK_BUFFER_MS = 60 * 1000;
-
const STUCK_SCAN_REAP_BATCH_SIZE = 100;
const STUCK_SCAN_STATUS_MESSAGE =
"The scan did not complete and was cancelled. This usually means the resource is too large to scan.";
+// The lock has to outlive the worst case a scan can take: clone timeout plus scan timeout plus the
+// same measurement/bookkeeping overhead the stuck-scan boot validation budgets for. Anything
+// shorter can expire mid-scan and let a second scan of the same resource start alongside the first.
const getFullScanLockTtlMs = () => {
const appCfg = getConfig();
- return appCfg.SECRET_SCANNING_CLONE_TIMEOUT_MS + appCfg.SECRET_SCANNING_SCAN_TIMEOUT_MS + SCAN_LOCK_BUFFER_MS;
+ return (
+ appCfg.SECRET_SCANNING_CLONE_TIMEOUT_MS + appCfg.SECRET_SCANNING_SCAN_TIMEOUT_MS + SECRET_SCANNING_SCAN_OVERHEAD_MS
+ );
};
export const secretScanningV2QueueServiceFactory = ({
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index fb69319204..498defef67 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -40,9 +40,10 @@ const zodStrBool = z
/**
* 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
- * headroom when validating the stuck-scan threshold so the reaper can't reach a healthy scan.
+ * headroom when validating the stuck-scan threshold so the reaper can't reach a healthy scan, and
+ * as the scan lock TTL headroom so the lock outlives any scan the reaper would consider healthy.
*/
-const SECRET_SCANNING_SCAN_OVERHEAD_MS = 5 * 60 * 1000;
+export const SECRET_SCANNING_SCAN_OVERHEAD_MS = 5 * 60 * 1000;
const databaseReadReplicaSchema = z
.object({