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(secret-scanning): enhance scanning process with new features and error handling
Victor Hugo dos Santos07469ddbde81
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex d1707f5456..7cc7e5e543 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -248,6 +248,8 @@ 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.** `start()` always creates the BullMQ `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. Anything that calls `upsertJobScheduler` must tolerate a missing queue — it throws when the queue was never created (`QUEUE_WORKERS_ENABLED=false`), and boot must not fail over a schedule another pod owns.+### Scheduled Jobs (Cron Manager)Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`cronJobFactory`). A single instance is constructed in `src/server/routes/index.ts` (~line 541) and injected as `cronJob` into any service that needs to schedule periodic work. The factory exposes `register`, `start`, and `stop`; `start` is called once after construction, and `stop` is invoked during graceful shutdown to drain in-flight handlers.diff --git a/backend/src/db/migrations/20260729120000_add-secret-scanning-scan-started-at.ts b/backend/src/db/migrations/20260729120000_add-secret-scanning-scan-started-at.tsnew file mode 100644index 0000000000..00b0713763--- /dev/null+++ b/backend/src/db/migrations/20260729120000_add-secret-scanning-scan-started-at.ts@@ -0,0 +1,37 @@+import { Knex } from "knex";++import { SecretScanningScanStatus } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";++import { TableName } from "../schemas";++const SCANNING_STARTED_AT_INDEX = "secret_scanning_scans_scanning_started_at_index";++export async function up(knex: Knex): Promise<void> {+ const hasScanningStartedAt = await knex.schema.hasColumn(TableName.SecretScanningScan, "scanningStartedAt");++ await knex.schema.alterTable(TableName.SecretScanningScan, (t) => {+ if (!hasScanningStartedAt) {+ // When the worker picked the job up, as distinct from when the scan was enqueued. The reaper+ // measures against this so a scan that sat in a queue backlog isn't mistaken for a hung one.+ t.datetime("scanningStartedAt").nullable();+ // Partial index: the reaper only ever scans rows still in progress, which is a tiny slice of+ // a table that is otherwise all completed/failed history.+ // whereRaw, not where: Postgres rejects bound parameters in DDL, and the query-builder form+ // emits the status as a placeholder.+ t.index(["scanningStartedAt"], SCANNING_STARTED_AT_INDEX, {+ predicate: knex.whereRaw(`status = '${SecretScanningScanStatus.Scanning}'`)+ });+ }+ });+}++export async function down(knex: Knex): Promise<void> {+ const hasScanningStartedAt = await knex.schema.hasColumn(TableName.SecretScanningScan, "scanningStartedAt");++ await knex.schema.alterTable(TableName.SecretScanningScan, (t) => {+ if (hasScanningStartedAt) {+ t.dropIndex(["scanningStartedAt"], SCANNING_STARTED_AT_INDEX);+ t.dropColumn("scanningStartedAt");+ }+ });+}diff --git a/backend/src/db/schemas/secret-scanning-scans.ts b/backend/src/db/schemas/secret-scanning-scans.tsindex 88e676b5bc..8ce79050ab 100644--- a/backend/src/db/schemas/secret-scanning-scans.ts+++ b/backend/src/db/schemas/secret-scanning-scans.ts@@ -13,7 +13,8 @@ export const SecretScanningScansSchema = z.object({statusMessage: z.string().nullable().optional(),type: z.string(),resourceId: z.string().uuid(),- createdAt: z.date().nullable().optional()+ createdAt: z.date().nullable().optional(),+ scanningStartedAt: z.date().nullable().optional()});export type TSecretScanningScans = z.infer<typeof SecretScanningScansSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex 09f67773a4..f44a6fdc22 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -334,12 +334,19 @@ export const auditLogQueueServiceFactory = async ({// "audit-log-clickhouse-batch" so the existing Redis scheduler key isn't orphaned on upgrade.queueService.start(QueueName.AuditLogClickHouseBatch, consumeAuditLogStream);- await queueService.upsertJobScheduler(- QueueName.AuditLogClickHouseBatch,- `${JOB_SCHEDULER_PREFIX}:audit-log-clickhouse-batch`,- { every: 5000 },- { name: QueueJobs.AuditLogClickHouseBatch }- );+ // A pod that doesn't run this queue's worker (QUEUE_WORKERS_ENABLED=false) never initializes the+ // queue, and upsertJobScheduler throws on a missing queue. Boot must not fail over a scheduler+ // this pod was never going to run — another pod in the fleet owns the schedule.+ try {+ await queueService.upsertJobScheduler(+ QueueName.AuditLogClickHouseBatch,+ `${JOB_SCHEDULER_PREFIX}:audit-log-clickhouse-batch`,+ { every: 5000 },+ { name: QueueJobs.AuditLogClickHouseBatch }+ );+ } catch (err) {+ logger.warn(err, "audit-log-queue: Skipped audit log batch scheduler registration");+ }return {pushToLogdiff --git a/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.ts b/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.tsindex 23d342313a..7a875ee638 100644--- a/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.ts+++ b/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.ts@@ -8,6 +8,7 @@ import {SecretScanningResource} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import {+ assertRepositoryWithinSizeLimit,cloneRepository,convertPatchLineToFileLineNumber,replaceNonChangesWithNewlines@@ -180,6 +181,25 @@ export const BitbucketSecretScanningFactory = () => {const { username } = await getBitbucketUser({ email, apiToken });+ // Checked before the clone: measuring afterwards means the network, wall clock and ephemeral+ // disk have already been spent. Bitbucket reports `size` in bytes.+ // `resourceName` is `workspace/repo`: the slash is a path separator here, so it must survive+ // into the URL. BasicRepositoryRegex above already constrains both segments to URL-safe+ // characters, which is what makes interpolating it directly safe.+ const { data: repository } = await request.get<{ size?: number }>(+ `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${resourceName}`,+ {+ headers: {+ Authorization: `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`,+ Accept: "application/json"+ }+ }+ );+ assertRepositoryWithinSizeLimit(+ resourceName,+ repository.size === undefined ? undefined : Math.round(repository.size / 1024 / 1024)+ );+await cloneRepository({cloneUrl: `https://${encodeURIComponent(username)}:${apiToken}@bitbucket.org/${resourceName}.git`,repoPathdiff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-factory.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-factory.tsindex 175e5d8cc7..dc3a589e8c 100644--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-factory.ts+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-factory.ts@@ -9,6 +9,7 @@ import {SecretScanningResource} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import {+ assertRepositoryWithinSizeLimit,cloneRepository,convertPatchLineToFileLineNumber,replaceNonChangesWithNewlines@@ -131,6 +132,13 @@ export const GitHubSecretScanningFactory = () => {throw new Error("Invalid GitHub repository name");}+ const [owner, repo] = resourceName.split("/");++ // Checked before the clone: measuring afterwards means the network, wall clock and ephemeral+ // disk have already been spent. GitHub reports `size` in KB.+ const { data: repository } = await octokit.repos.get({ owner, repo });+ assertRepositoryWithinSizeLimit(resourceName, Math.round(repository.size / 1024));+await cloneRepository({cloneUrl: `https://x-access-token:${token}@github.com/${resourceName}.git`,repoPathdiff --git a/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts b/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.tsindex 13c22d4030..46701301b7 100644--- a/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts+++ b/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts@@ -8,6 +8,7 @@ import {SecretScanningResource} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import {+ assertRepositoryWithinSizeLimit,cloneRepository,convertPatchLineToFileLineNumber,replaceNonChangesWithNewlines@@ -260,6 +261,16 @@ export const GitLabSecretScanningFactory = ({ appConnectionDAL, kmsService }: TSthrow new Error("Invalid GitLab project name");}+ // Checked before the clone: measuring afterwards means the network, wall clock and ephemeral+ // disk have already been spent. `repositorySize` is in bytes and is only returned to callers+ // with sufficient privileges — when it is absent the post-clone check is the backstop.+ const project = await client.Projects.show(resourceName, { statistics: true });+ const repositorySize = project.statistics?.repositorySize;+ assertRepositoryWithinSizeLimit(+ resourceName,+ repositorySize === undefined ? undefined : Math.round(Number(repositorySize) / 1024 / 1024)+ );+const validatedHostname = new URL(instanceUrl).host;await cloneRepository({diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.tsindex 83bbc37b51..7347f7d0ab 100644--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts@@ -7,7 +7,10 @@ import {TableName,TSecretScanningDataSources} from "@app/db/schemas";-import { SecretScanningFindingStatus } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";+import {+ SecretScanningFindingStatus,+ SecretScanningScanStatus+} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import { DatabaseError } from "@app/lib/errors";import {buildFindFilter,@@ -428,6 +431,43 @@ export const secretScanningV2DALFactory = (db: TDbClient) => {}};+ // Reads the primary: the caller writes these rows straight after, and a replica that still shows+ // a just-completed scan as in-progress would have it reaped.+ const findStuckScans = async (startedBefore: Date, limit: number, tx?: Knex) => {+ try {+ const scans = await (tx || db)(TableName.SecretScanningScan)+ .where(`${TableName.SecretScanningScan}.status`, SecretScanningScanStatus.Scanning)+ .where((qb) => {+ void qb+ .where(`${TableName.SecretScanningScan}.scanningStartedAt`, "<", startedBefore)+ // Rows written before `scanningStartedAt` existed, or by a pod still running an older+ // image mid-deploy, fall back to their creation time so they're reaped too.+ .orWhere((nullStartedAt) => {+ void nullStartedAt+ .whereNull(`${TableName.SecretScanningScan}.scanningStartedAt`)+ .andWhere(`${TableName.SecretScanningScan}.createdAt`, "<", startedBefore);+ });+ })+ .join(+ TableName.SecretScanningResource,+ `${TableName.SecretScanningResource}.id`,+ `${TableName.SecretScanningScan}.resourceId`+ )+ .select(selectAllTableCols(TableName.SecretScanningScan))+ .select(+ db.ref("name").withSchema(TableName.SecretScanningResource).as("resourceName"),+ db.ref("type").withSchema(TableName.SecretScanningResource).as("resourceType"),+ db.ref("dataSourceId").withSchema(TableName.SecretScanningResource)+ )+ .orderBy(`${TableName.SecretScanningScan}.createdAt`, "asc")+ .limit(limit);++ return scans;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find Stuck - Secret Scanning Scan" });+ }+ };+const findScansByDataSourceId = async (dataSourceId: string, tx?: Knex) => {try {const scans = await (tx || db.replicaNode())(TableName.SecretScanningScan)@@ -464,7 +504,8 @@ export const secretScanningV2DALFactory = (db: TDbClient) => {scans: {...scanOrm,findWithDetailsByDataSourceId: findScansWithDetailsByDataSourceId,- findByDataSourceId: findScansByDataSourceId+ findByDataSourceId: findScansByDataSourceId,+ findStuck: findStuckScans},findings: findingOrm,configs: configOrmdiff --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.tsnew file mode 100644index 0000000000..c1cfc31589--- /dev/null+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from "vitest";++import {+ SecretScanningExecError,+ SecretScanningExecFailure,+ SecretScanningExecPhase+} from "@app/ee/services/secret-scanning/secret-scanning-exec";++import { parseScanErrorMessage, SecretScanningSizeLimitError } from "./secret-scanning-v2-fns";++describe("parseScanErrorMessage", () => {+ test("maps a scan timeout to an actionable message without leaking the command line", () => {+ const message = parseScanErrorMessage(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.Timeout,+ phase: SecretScanningExecPhase.Scan,+ command: "infisical",+ output: "scanning /tmp/infisical-scan-yunqhI",+ timeoutMs: 10 * 60 * 1000+ })+ );++ expect(message).toContain("10 minute time limit");+ expect(message).not.toContain("infisical scan");+ expect(message).not.toContain("/tmp/infisical-scan-yunqhI");+ });++ test("distinguishes a clone timeout from a scan timeout", () => {+ const message = parseScanErrorMessage(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.Timeout,+ phase: SecretScanningExecPhase.Clone,+ command: "git",+ output: "",+ timeoutMs: 10 * 60 * 1000+ })+ );++ expect(message).toContain("Cloning the repository");+ });++ test("does not describe a size measurement as a clone failure", () => {+ // Both run `git`, so the phase is the only thing separating them. Reporting a count-objects+ // timeout as a clone timeout sends the customer chasing credentials that are fine.+ const message = parseScanErrorMessage(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.Timeout,+ phase: SecretScanningExecPhase.Measure,+ command: "git",+ output: "",+ timeoutMs: 30_000+ })+ );++ expect(message).toContain("could not be measured");+ expect(message).not.toContain("Cloning");+ expect(message).not.toContain("credentials");+ });++ test("maps a rejected clone to a credentials message", () => {+ const message = parseScanErrorMessage(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.ExitCode,+ phase: SecretScanningExecPhase.Clone,+ command: "git",+ output:+ "remote: Invalid username or password.\nfatal: Authentication failed for 'https://github.com/acme/app.git/'",+ exitCode: 128+ })+ );++ expect(message).toContain("denied access");+ // The remote URL carries an embedded access token in the real failure — it must not survive.+ expect(message).not.toContain("https://");+ });++ test("passes the size limit message through — it is written for the customer", () => {+ const message = parseScanErrorMessage(new SecretScanningSizeLimitError("acme/monorepo", 12_000, 5_120));++ expect(message).toContain("acme/monorepo");+ expect(message).toContain("5120 MB scanning limit");+ });++ test("truncates an oversized message", () => {+ const message = parseScanErrorMessage(new Error("x".repeat(2000)));++ expect(message).toHaveLength(1024);+ expect(message.endsWith("...")).toBe(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.tsindex 00a3b334e2..9c2446f4af 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@@ -1,9 +1,16 @@import { AxiosError } from "axios";-import { execFile } from "child_process";import { join } from "path";import picomatch from "picomatch";import RE2 from "re2";+import {+ execFileBounded,+ getScannerProcessEnv,+ GIT_PROCESS_ENV,+ SecretScanningExecError,+ SecretScanningExecFailure,+ SecretScanningExecPhase+} from "@app/ee/services/secret-scanning/secret-scanning-exec";import {createTempFolder,deleteTempFolder,@@ -18,6 +25,7 @@ import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";import { BadRequestError } from "@app/lib/errors";import { titleCaseToCamelCase } from "@app/lib/fn";+import { logger } from "@app/lib/logger";import { SecretScanningDataSource, SecretScanningFindingSeverity } from "./secret-scanning-v2-enums";import { TCloneRepository, TGetFindingsPayload, TSecretScanningDataSourceListItem } from "./secret-scanning-v2-types";@@ -32,53 +40,105 @@ export const listSecretScanningDataSourceOptions = () => {return Object.values(SECRET_SCANNING_SOURCE_LIST_OPTIONS).sort((a, b) => a.name.localeCompare(b.name));};+// The scanner exits 77 when it wrote findings; that is a successful scan, not a failure.+const SCAN_FINDINGS_EXIT_CODE = 77;++const KIB_PER_MIB = 1024;++export class SecretScanningSizeLimitError extends Error {+ constructor(resourceName: string, sizeMb: number, limitMb: number) {+ super(`"${resourceName}" is ${sizeMb} MB, which exceeds the ${limitMb} MB scanning limit.`);+ this.name = "SecretScanningSizeLimitError";+ }+}++/**+ * Guards the clone, not just the scan: a bare clone of a large monorepo consumes network, wall clock+ * and ephemeral disk with no ceiling of its own. Providers report repository size in their metadata,+ * so this runs before any bytes are transferred. A size of `undefined` means the provider didn't+ * report one — `assertClonedRepositoryWithinSizeLimit` is the backstop for that case.+ */+export const assertRepositoryWithinSizeLimit = (resourceName: string, sizeMb: number | undefined) => {+ const { SECRET_SCANNING_MAX_REPO_SIZE_MB: limitMb } = getConfig();++ if (!limitMb || sizeMb === undefined) return;++ if (sizeMb > limitMb) throw new SecretScanningSizeLimitError(resourceName, sizeMb, limitMb);+};++const SizePackRegex = new RE2(/^size-pack:\s*(\d+)/m);++/**+ * Measures a bare clone on disk and enforces the same ceiling. This is the backstop for providers+ * that don't report a size in their repository metadata, and doubles as the measurement logged with+ * 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+ });++ const match = SizePackRegex.match(output);++ if (!match) return undefined;++ const sizeMb = Math.round(Number(match[1]) / KIB_PER_MIB);++ assertRepositoryWithinSizeLimit(resourceName, sizeMb);++ return sizeMb;+};+export const cloneRepository = async ({ cloneUrl, repoPath }: TCloneRepository): Promise<void> => {// Validate that the constructed URL is structurally valid.// This prevents malformed or tampered components from producing unexpected git behavior.// eslint-disable-next-line no-newnew URL(cloneUrl);- return new Promise((resolve, reject) => {- execFile("git", ["clone", cloneUrl, repoPath, "--bare"], (error) => {- if (error) {- reject(error);- } else {- resolve();- }- });+ await execFileBounded("git", ["clone", cloneUrl, repoPath, "--bare"], {+ phase: SecretScanningExecPhase.Clone,+ timeoutMs: getConfig().SECRET_SCANNING_CLONE_TIMEOUT_MS,+ env: GIT_PROCESS_ENV});};-export function scanDirectory(inputPath: string, outputPath: string, configPath?: string): Promise<void> {- return new Promise((resolve, reject) => {- const args = ["scan", "--exit-code=77", "-r", outputPath];- if (configPath) {- args.push("-c", configPath);- }- execFile("infisical", args, { cwd: inputPath }, (error) => {- if (error && error.code !== 77) {- reject(error);- } else {- resolve();- }- });+export async function scanDirectory(inputPath: string, outputPath: string, configPath?: string): Promise<void> {+ const args = ["scan", "--exit-code=77", "-r", outputPath];+ if (configPath) {+ args.push("-c", configPath);+ }++ await execFileBounded("infisical", args, {+ phase: SecretScanningExecPhase.Scan,+ cwd: inputPath,+ timeoutMs: getConfig().SECRET_SCANNING_SCAN_TIMEOUT_MS,+ env: getScannerProcessEnv(),+ successExitCodes: [0, SCAN_FINDINGS_EXIT_CODE]});}-export function scanFile(inputPath: string, configPath?: string): Promise<void> {- return new Promise((resolve, reject) => {- const args = ["scan", "--exit-code=77", "--source", inputPath, "--no-git"];- if (configPath) {- args.push("-c", configPath);- }- execFile("infisical", args, (error) => {- if (error && error.code === 77) {- reject(error);- } else {- resolve();- }+export async function scanFile(inputPath: string, configPath?: string): Promise<void> {+ const args = ["scan", "--exit-code=77", "--source", inputPath, "--no-git"];+ if (configPath) {+ args.push("-c", configPath);+ }++ try {+ await execFileBounded("infisical", args, {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: getConfig().SECRET_SCANNING_SCAN_TIMEOUT_MS,+ env: getScannerProcessEnv(),+ successExitCodes: [0]});- });+ } catch (error) {+ // Only exit code 77 — a detected secret — is a violation. Every other failure mode fails open so+ // a scanner hiccup can't be reported to the caller as "secret detected" and block a write.+ if (error instanceof SecretScanningExecError && error.exitCode === SCAN_FINDINGS_EXIT_CODE) throw error;++ logger.warn(error, `scanFile: Secret detection scan did not complete [inputPath=${inputPath}]`);+ }}export const scanGitRepositoryAndGetFindings = async (@@ -160,10 +220,58 @@ export const convertPatchLineToFileLineNumber = (patch: string, patchLineNumber:const MAX_MESSAGE_LENGTH = 1024;+const GitAuthFailureRegex = new RE2(+ /authentication failed|could not read Username|invalid username or password|access denied|HTTP 40[13]/i+);+const GitNotFoundRegex = new RE2(/repository not found|remote: Not Found|does not appear to be a git repository/i);++/**+ * 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.+ */+const parseExecErrorMessage = (err: SecretScanningExecError): string => {+ // The measurement runs `git count-objects` on an already-cloned repository, so none of the clone+ // advice below applies to it: there is no remote, no credentials and no customer-tunable timeout.+ if (err.phase === SecretScanningExecPhase.Measure) {+ return "The repository could not be measured before scanning.";+ }++ const isClone = err.phase === SecretScanningExecPhase.Clone;++ if (err.failure === SecretScanningExecFailure.Timeout) {+ const minutes = Math.round((err.timeoutMs ?? 0) / 60_000);+ 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.`;+ }++ if (err.failure === SecretScanningExecFailure.Spawn) {+ return isClone ? "Git could not be started on this instance." : "The secret scanner could not be started.";+ }++ if (isClone) {+ if (GitAuthFailureRegex.test(err.output)) {+ return "Failed to clone the repository: the connection was denied access. Verify the connection's credentials and that it still has access to this repository.";+ }++ if (GitNotFoundRegex.test(err.output)) {+ return "Failed to clone the repository: it could not be found. Verify it still exists and that the connection has access to it.";+ }++ return "Failed to clone the repository. Verify the connection's credentials and that the repository is still accessible.";+ }++ return "The secret scanner exited unexpectedly.";+};+export const parseScanErrorMessage = (err: unknown): string => {let errorMessage: string;- if (err instanceof AxiosError) {+ if (err instanceof SecretScanningExecError) {+ errorMessage = parseExecErrorMessage(err);+ } else if (err instanceof SecretScanningSizeLimitError) {+ errorMessage = err.message;+ } else if (err instanceof AxiosError) {errorMessage = err?.response?.data? JSON.stringify(err?.response?.data): (err?.message ?? "An unknown error occurred.");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.tsindex b8d9aa2dc8..4008c9c12b 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@@ -8,11 +8,13 @@ import {writeTextToFile} from "@app/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns";import {+ assertClonedRepositoryWithinSizeLimit,parseScanErrorMessage,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 { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { BadRequestError, InternalServerError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";@@ -46,6 +48,7 @@ import {type TSecretRotationV2QueueServiceFactoryDep = {queueService: TQueueServiceFactory;+ cronJob: TCronJobFactory;secretScanningV2DAL: TSecretScanningV2DALFactory;smtpService: Pick<TSmtpService, "sendMail">;projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;@@ -59,8 +62,22 @@ 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.";++const getFullScanLockTtlMs = () => {+ const appCfg = getConfig();+ return appCfg.SECRET_SCANNING_CLONE_TIMEOUT_MS + appCfg.SECRET_SCANNING_SCAN_TIMEOUT_MS + SCAN_LOCK_BUFFER_MS;+};+export const secretScanningV2QueueServiceFactory = ({queueService,+ cronJob,secretScanningV2DAL,projectMembershipDAL,projectDAL,@@ -155,11 +172,17 @@ export const secretScanningV2QueueServiceFactory = ({const { scanId, resourceId, dataSourceId } = job.data;const retryCount = job.attemptsMade + 1;const retryLimit = job.opts.attempts || 1;+ const startedAt = Date.now();const logDetails = `[scanId=${scanId}] [resourceId=${resourceId}] [dataSourceId=${dataSourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;const tempFolder = await createTempFolder();+ // Logged before any work so a `ps` on a saturated worker can be tied back to a scan ID.+ logger.info(+ `secretScanningV2Queue: Full Scan Started ${logDetails} [scanType=${SecretScanningScanType.FullScan}] [tempFolder=${tempFolder}]`+ );+const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId);if (!dataSource) throw new Error(`Data source with ID "${dataSourceId}" not found`);@@ -174,7 +197,7 @@ export const secretScanningV2QueueServiceFactory = ({try {lock = await keyStore.acquireLock([KeyStorePrefixes.SecretScanningLock(dataSource.id, resource.externalId)],- 60 * 1000 * 5+ getFullScanLockTtlMs());} catch (e) {throw new Error("Failed to acquire scanning lock.");@@ -183,7 +206,8 @@ export const secretScanningV2QueueServiceFactory = ({await secretScanningV2DAL.scans.update({ id: scanId },{- status: SecretScanningScanStatus.Scanning+ status: SecretScanningScanStatus.Scanning,+ scanningStartedAt: new Date()});@@ -220,9 +244,14 @@ export const secretScanningV2QueueServiceFactory = ({let findingsPayload: TFindingsPayload;switch (resource.type) {case SecretScanningResource.Repository:- case SecretScanningResource.Project:+ case SecretScanningResource.Project: {+ const repoSizeMb = await assertClonedRepositoryWithinSizeLimit(resource.name, scanPath);++ logger.info(`secretScanningV2Queue: Full Scan Cloned ${logDetails} repoSizeMb=[${repoSizeMb ?? "unknown"}]`);+findingsPayload = await scanGitRepositoryAndGetFindings(scanPath, findingsPath, configPath);break;+ }default:throw new Error("Unhandled resource type");}@@ -296,7 +325,9 @@ export const secretScanningV2QueueServiceFactory = ({}});- logger.info(`secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsPayload.length}]`);+ logger.info(+ `secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsPayload.length}] durationMs=[${Date.now() - startedAt}]`+ );} catch (error) {if (retryCount === retryLimit) {const errorMessage = parseScanErrorMessage(error);@@ -342,7 +373,10 @@ export const secretScanningV2QueueServiceFactory = ({});}- logger.error(error, `secretScanningV2Queue: Full Scan Failed ${logDetails}`);+ logger.error(+ error,+ `secretScanningV2Queue: Full Scan Failed ${logDetails} durationMs=[${Date.now() - startedAt}]`+ );throw error;} finally {await deleteTempFolder(tempFolder);@@ -421,6 +455,7 @@ export const secretScanningV2QueueServiceFactory = ({const { payload, dataSourceId, resourceId, scanId } = job.data;const retryCount = job.attemptsMade + 1;const retryLimit = job.opts.attempts || 1;+ const startedAt = Date.now();const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;@@ -439,11 +474,16 @@ export const secretScanningV2QueueServiceFactory = ({const tempFolder = await createTempFolder();+ logger.info(+ `secretScanningV2Queue: Diff Scan Started ${logDetails} [scanType=${SecretScanningScanType.DiffScan}] [tempFolder=${tempFolder}]`+ );+try {await secretScanningV2DAL.scans.update({ id: scanId },{- status: SecretScanningScanStatus.Scanning+ status: SecretScanningScanStatus.Scanning,+ scanningStartedAt: new Date()});@@ -543,7 +583,9 @@ export const secretScanningV2QueueServiceFactory = ({}});- logger.info(`secretScanningV2Queue: Diff Scan Complete ${logDetails}`);+ logger.info(+ `secretScanningV2Queue: Diff Scan Complete ${logDetails} findings=[${findingsPayload.length}] durationMs=[${Date.now() - startedAt}]`+ );} catch (error) {if (retryCount === retryLimit) {const errorMessage = parseScanErrorMessage(error);@@ -589,7 +631,10 @@ export const secretScanningV2QueueServiceFactory = ({});}- logger.error(error, `secretScanningV2Queue: Diff Scan Failed ${logDetails}`);+ logger.error(+ error,+ `secretScanningV2Queue: Diff Scan Failed ${logDetails} durationMs=[${Date.now() - startedAt}]`+ );throw error;} finally {await deleteTempFolder(tempFolder);@@ -688,6 +733,90 @@ export const secretScanningV2QueueServiceFactory = ({}};+ // A worker killed mid-scan (OOM, task replacement, host loss) never reaches its own failure path,+ // so the row it set to `scanning` stays that way forever and the customer sees a scan permanently+ // in progress.+ const failStuckScan = async (scan: Awaited<ReturnType<typeof secretScanningV2DAL.scans.findStuck>>[number]) => {+ const logDetails = `[scanId=${scan.id}] [resourceId=${scan.resourceId}] [dataSourceId=${scan.dataSourceId}] [scanningStartedAt=${scan.scanningStartedAt?.toISOString()}]`;++ try {+ // Guarded on the status we read: if the worker did finish between the read and this write, the+ // update matches nothing and the scan keeps its real outcome.+ const updatedScans = await secretScanningV2DAL.scans.update(+ { id: scan.id, status: SecretScanningScanStatus.Scanning },+ {+ status: SecretScanningScanStatus.Failed,+ statusMessage: STUCK_SCAN_STATUS_MESSAGE+ }+ );++ if (!updatedScans.length) return;++ logger.warn(`secretScanningV2Queue: Reaped Stuck Scan ${logDetails}`);++ const dataSource = await secretScanningV2DAL.dataSources.findById(scan.dataSourceId);++ if (!dataSource) return;++ await queueService.queue(+ QueueName.SecretScanningV2,+ QueueJobs.SecretScanningV2SendNotification,+ {+ status: SecretScanningScanStatus.Failed,+ resourceName: scan.resourceName,+ dataSource,+ errorMessage: STUCK_SCAN_STATUS_MESSAGE+ },+ { jobId: `secret-scanning-notification-${scan.id}`, removeOnFail: true }+ );++ await auditLogService.createAuditLog({+ projectId: dataSource.projectId,+ actor: {+ type: ActorType.PLATFORM,+ metadata: {}+ },+ event: {+ type: EventType.SECRET_SCANNING_DATA_SOURCE_SCAN,+ metadata: {+ dataSourceId: dataSource.id,+ dataSourceType: dataSource.type,+ resourceId: scan.resourceId,+ resourceType: scan.resourceType,+ scanId: scan.id,+ scanStatus: SecretScanningScanStatus.Failed,+ scanType: scan.type as SecretScanningScanType+ }+ }+ });+ } catch (error) {+ logger.error(error, `secretScanningV2Queue: Failed to Reap Stuck Scan ${logDetails}`);+ }+ };++ cronJob.register({+ name: CronJobName.SecretScanningStuckScanReaper,+ pattern: "*/10 * * * *",+ runHashTtlS: 60 * 60,+ handler: async () => {+ const { SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS } = getConfig();++ const stuckScans = await secretScanningV2DAL.scans.findStuck(+ new Date(Date.now() - SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS),+ STUCK_SCAN_REAP_BATCH_SIZE+ );++ if (!stuckScans.length) return;++ logger.warn(`secretScanningV2Queue: Reaping Stuck Scans [count=${stuckScans.length}]`);++ for (const scan of stuckScans) {+ // eslint-disable-next-line no-await-in-loop+ await failStuckScan(scan);+ }+ }+ });+queueService.start(QueueName.SecretScanningV2, async (job) => {if (job.name === QueueJobs.SecretScanningV2FullScan) {await handleFullScan(job as Parameters<typeof handleFullScan>[0]);diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.tsindex c48139e17a..36a425d7b2 100644--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts@@ -45,6 +45,7 @@ import {} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-types";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";@@ -315,8 +316,12 @@ export const secretScanningV2ServiceFactory = ({...createdDataSource,connection} as TSecretScanningDataSourceWithConnection);- } catch {- // silently fail, don't want to block creation, they'll try scanning when they don't see anything and get the error+ } catch (error) {+ // Deliberately non-fatal — a scan that can't be queued shouldn't block creating the data source.+ logger.error(+ error,+ `secretScanningV2Service: Failed to queue initial full scan on data source creation [dataSourceId=${createdDataSource.id}] [projectId=${payload.projectId}]`+ );}}diff --git a/backend/src/ee/services/secret-scanning/secret-scanning-exec.test.ts b/backend/src/ee/services/secret-scanning/secret-scanning-exec.test.tsnew file mode 100644index 0000000000..f5cac6eed4--- /dev/null+++ b/backend/src/ee/services/secret-scanning/secret-scanning-exec.test.ts@@ -0,0 +1,89 @@+import { execFile } from "child_process";+import { promisify } from "util";+import { describe, expect, test } from "vitest";++import {+ execFileBounded,+ SecretScanningExecError,+ SecretScanningExecFailure,+ SecretScanningExecPhase+} from "./secret-scanning-exec";++const execFileAsync = promisify(execFile);++const isProcessAlive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+};++describe("execFileBounded", () => {+ test("resolves with captured output on success", async () => {+ const output = await execFileBounded("sh", ["-c", "echo hello"], {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: 10_000+ });++ expect(output.trim()).toBe("hello");+ });++ test("treats a configured non-zero exit code as success", async () => {+ await expect(+ execFileBounded("sh", ["-c", "exit 77"], {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: 10_000,+ successExitCodes: [0, 77]+ })+ ).resolves.toBeDefined();+ });++ test("rejects with the exit code and captured output on failure", async () => {+ const error = await execFileBounded("sh", ["-c", "echo boom >&2; exit 3"], {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: 10_000+ }).catch((err: unknown) => err);++ expect(error).toBeInstanceOf(SecretScanningExecError);+ const execError = error as SecretScanningExecError;+ expect(execError.failure).toBe(SecretScanningExecFailure.ExitCode);+ expect(execError.exitCode).toBe(3);+ expect(execError.output).toContain("boom");+ // The command line and output must not leak into the message — it reaches the customer.+ expect(execError.message).not.toContain("boom");+ });++ test("rejects when the binary cannot be started", async () => {+ const error = await execFileBounded("this-binary-does-not-exist", [], {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: 10_000+ }).catch((err: unknown) => err);++ expect(error).toBeInstanceOf(SecretScanningExecError);+ expect((error as SecretScanningExecError).failure).toBe(SecretScanningExecFailure.Spawn);+ });++ test("kills the whole process group on timeout, not just the direct child", async () => {+ // Mirrors the real shape: the scanner spawns a long-running grandchild (`git log -p`) that is+ // the process actually holding memory. Signalling only the direct child orphans it.+ const grandchildPidFile = `${process.env.TMPDIR ?? "/tmp"}/exec-bounded-grandchild-${process.pid}.pid`;++ const error = await execFileBounded("sh", ["-c", `sh -c 'echo $$ > ${grandchildPidFile}; sleep 60' & wait`], {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: 1_000+ }).catch((err: unknown) => err);++ expect(error).toBeInstanceOf(SecretScanningExecError);+ expect((error as SecretScanningExecError).failure).toBe(SecretScanningExecFailure.Timeout);++ const { stdout } = await execFileAsync("cat", [grandchildPidFile]);+ const grandchildPid = Number(stdout.trim());++ expect(Number.isNaN(grandchildPid)).toBe(false);+ expect(isProcessAlive(grandchildPid)).toBe(false);++ await execFileAsync("rm", ["-f", grandchildPidFile]);+ }, 15_000);+});diff --git a/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts b/backend/src/ee/services/secret-scanning/secret-scanning-exec.tsnew file mode 100644index 0000000000..d7bc45000b--- /dev/null+++ b/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts@@ -0,0 +1,212 @@+import { spawn } from "child_process";++import { getConfig } from "@app/lib/config/env";++export enum SecretScanningExecFailure {+ Timeout = "timeout",+ ExitCode = "exit-code",+ Spawn = "spawn"+}++/**+ * What the child process was doing, so a failure can be described to the customer accurately. The+ * binary name is not enough: `git clone` and `git count-objects` are both git but mean very+ * different things to whoever reads the scan's status message.+ */+export enum SecretScanningExecPhase {+ Clone = "clone",+ Measure = "measure",+ Scan = "scan"+}++const MAX_RETAINED_OUTPUT_CHARS = 4_000;++type TSecretScanningExecErrorParams = {+ failure: SecretScanningExecFailure;+ phase: SecretScanningExecPhase;+ command: string;+ output: string;+ exitCode?: number | null;+ signal?: NodeJS.Signals | null;+ timeoutMs?: number;+ cause?: Error;+};++/**+ * Raised for any non-success termination of a scanner/git child process. `message` is kept free of+ * command lines and process output so it is safe to log; `output` holds the captured stdout/stderr+ * and must never be forwarded to a customer-facing status message.+ */+export class SecretScanningExecError extends Error {+ readonly failure: SecretScanningExecFailure;++ readonly phase: SecretScanningExecPhase;++ readonly command: string;++ readonly output: string;++ readonly exitCode?: number | null;++ readonly signal?: NodeJS.Signals | null;++ readonly timeoutMs?: number;++ constructor({ failure, phase, command, output, exitCode, signal, timeoutMs, cause }: TSecretScanningExecErrorParams) {+ let message: string;+ switch (failure) {+ case SecretScanningExecFailure.Timeout:+ message = `"${command}" exceeded its ${timeoutMs}ms time limit and was terminated`;+ break;+ case SecretScanningExecFailure.Spawn:+ message = `"${command}" could not be started: ${cause?.message ?? "unknown error"}`;+ break;+ default:+ message = `"${command}" exited with code ${exitCode ?? "null"}${signal ? ` (signal ${signal})` : ""}`;+ }++ super(message);++ this.name = "SecretScanningExecError";+ this.failure = failure;+ this.phase = phase;+ this.command = command;+ // Only the tail is retained — it carries the actual failure reason and keeps log lines bounded.+ this.output = output.length > MAX_RETAINED_OUTPUT_CHARS ? output.slice(-MAX_RETAINED_OUTPUT_CHARS) : output;+ this.exitCode = exitCode;+ this.signal = signal;+ this.timeoutMs = timeoutMs;+ }+}++// Matches Node's default execFile maxBuffer. Findings are written to a file via `-r`, so this only+// ever holds progress output — but it is captured explicitly so a chatty child can't grow the heap.+const MAX_CAPTURED_OUTPUT_BYTES = 1024 * 1024;++/**+ * `infisical scan` shells out to `git log -p -U0 --full-history --all`, and that grandchild is the+ * process actually holding the memory. Signalling only the direct child orphans it, so the child is+ * spawned `detached` (its own process group) and the whole group is signalled by negative pid.+ */+const killProcessGroup = (pid: number | undefined) => {+ if (!pid) return;++ try {+ process.kill(-pid, "SIGKILL");+ } catch {+ // The group is already gone (normal exit raced the timer) or we never became a group leader;+ // fall back to the direct child so we at least don't leave it running.+ try {+ process.kill(pid, "SIGKILL");+ } catch {+ // nothing left to kill+ }+ }+};++type TExecFileBoundedOptions = {+ phase: SecretScanningExecPhase;+ cwd?: string;+ timeoutMs: number;+ env?: Record<string, string>;+ /** Exit codes treated as success. The scanner uses 77 to signal "findings were written". */+ successExitCodes?: number[];+};++export const execFileBounded = (+ file: string,+ args: string[],+ { phase, cwd, timeoutMs, env, successExitCodes = [0] }: TExecFileBoundedOptions+): Promise<string> =>+ new Promise((resolve, reject) => {+ const child = spawn(file, args, {+ cwd,+ detached: true,+ env: env ? { ...process.env, ...env } : process.env,+ stdio: ["ignore", "pipe", "pipe"]+ });++ let output = "";+ let capturedBytes = 0;+ const capture = (chunk: Buffer) => {+ if (capturedBytes >= MAX_CAPTURED_OUTPUT_BYTES) return;+ capturedBytes += chunk.length;+ output += chunk.toString("utf8");+ };++ child.stdout.on("data", capture);+ child.stderr.on("data", capture);++ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ killProcessGroup(child.pid);+ }, timeoutMs);++ child.on("error", (err) => {+ clearTimeout(timer);+ reject(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.Spawn,+ phase,+ command: file,+ output,+ cause: err+ })+ );+ });++ child.on("close", (exitCode, signal) => {+ clearTimeout(timer);++ if (timedOut) {+ reject(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.Timeout,+ phase,+ command: file,+ output,+ timeoutMs+ })+ );+ return;+ }++ if (exitCode !== null && successExitCodes.includes(exitCode)) {+ resolve(output);+ return;+ }++ reject(+ new SecretScanningExecError({+ failure: SecretScanningExecFailure.ExitCode,+ phase,+ command: file,+ output,+ exitCode,+ signal+ })+ );+ });+ });++/**+ * Without this git blocks on an interactive credential prompt when the embedded credentials are+ * rejected, turning an auth failure into a wait for the clone timeout.+ */+export const GIT_PROCESS_ENV = { GIT_TERMINAL_PROMPT: "0" };++/**+ * Environment overrides for the Go-based scanner CLI. GOMEMLIMIT is a soft ceiling: as the scanner+ * approaches it the Go runtime collects more aggressively instead of growing, so a repository+ * slightly over budget still completes rather than being killed. Runtimes older than Go 1.19 simply+ * ignore it. RLIMIT_AS (`ulimit -v`) is deliberately not used — Go reserves large virtual address+ * arenas at startup, so hard virtual-memory limits break Go binaries in confusing ways.+ */+export const getScannerProcessEnv = (): Record<string, string> | undefined => {+ const { SECRET_SCANNING_MEMORY_LIMIT_MB } = getConfig();++ if (!SECRET_SCANNING_MEMORY_LIMIT_MB) return undefined;++ return { GOMEMLIMIT: `${SECRET_SCANNING_MEMORY_LIMIT_MB}MiB` };+};diff --git a/backend/src/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns.ts b/backend/src/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns.tsindex ab561ae505..f2f18d108e 100644--- a/backend/src/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns.ts+++ b/backend/src/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns.ts@@ -1,12 +1,22 @@import { Octokit } from "@octokit/rest";-import { execFile } from "child_process";import { readFile, rm, writeFile } from "fs";import { mkdtemp } from "fs/promises";import { tmpdir } from "os";import { join } from "path";+import {+ execFileBounded,+ getScannerProcessEnv,+ GIT_PROCESS_ENV,+ SecretScanningExecPhase+} from "@app/ee/services/secret-scanning/secret-scanning-exec";+import { getConfig } from "@app/lib/config/env";+import { SecretMatch } from "./secret-scanning-queue-types";+// The scanner exits 77 when it wrote findings; that is a successful scan, not a failure.+const SCAN_FINDINGS_EXIT_CODE = 77;+export function createTempFolder(): Promise<string> {return mkdtemp(join(tmpdir(), "infisical-scan-"));}@@ -33,42 +43,34 @@ export async function cloneRepo(// eslint-disable-next-line no-newnew URL(cloneUrl);- return new Promise((resolve, reject) => {- execFile("git", ["clone", cloneUrl, repoPath, "--bare"], (error) => {- if (error) {- reject(error);- } else {- resolve();- }- });+ await execFileBounded("git", ["clone", cloneUrl, repoPath, "--bare"], {+ phase: SecretScanningExecPhase.Clone,+ timeoutMs: getConfig().SECRET_SCANNING_CLONE_TIMEOUT_MS,+ env: GIT_PROCESS_ENV});}-export function runInfisicalScanOnRepo(repoPath: string, outputPath: string): Promise<void> {- return new Promise((resolve, reject) => {- execFile("infisical", ["scan", "--exit-code=77", "-r", outputPath], { cwd: repoPath }, (error) => {- if (error && error.code !== 77) {- reject(error);- } else {- resolve();- }- });+export async function runInfisicalScanOnRepo(repoPath: string, outputPath: string): Promise<void> {+ await execFileBounded("infisical", ["scan", "--exit-code=77", "-r", outputPath], {+ phase: SecretScanningExecPhase.Scan,+ cwd: repoPath,+ timeoutMs: getConfig().SECRET_SCANNING_SCAN_TIMEOUT_MS,+ env: getScannerProcessEnv(),+ successExitCodes: [0, SCAN_FINDINGS_EXIT_CODE]});}-export function runInfisicalScan(inputPath: string, outputPath: string, configPath?: string): Promise<void> {- return new Promise((resolve, reject) => {- const args = ["scan", "--exit-code=77", "--source", inputPath, "--no-git", "-r", outputPath];- if (configPath) {- args.push("-c", configPath);- }- execFile("infisical", args, (error) => {- if (error && error.code !== 77) {- reject(error);- } else {- resolve();- }- });+export async function runInfisicalScan(inputPath: string, outputPath: string, configPath?: string): Promise<void> {+ const args = ["scan", "--exit-code=77", "--source", inputPath, "--no-git", "-r", outputPath];+ if (configPath) {+ args.push("-c", configPath);+ }++ await execFileBounded("infisical", args, {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: getConfig().SECRET_SCANNING_SCAN_TIMEOUT_MS,+ env: getScannerProcessEnv(),+ successExitCodes: [0, SCAN_FINDINGS_EXIT_CODE]});}diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 4ada40f300..3716a8d800 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -344,6 +344,40 @@ const envSchema = zSECRET_SCANNING_PRIVATE_KEY: zpStr(z.string().optional()),SECRET_SCANNING_ORG_WHITELIST: zpStr(z.string().optional()),SECRET_SCANNING_GIT_APP_SLUG: zpStr(z.string().default("infisical-radar")),+ SECRET_SCANNING_SCAN_TIMEOUT_MS: z.coerce+ .number()+ .int()+ .min(1)+ .default(10 * 60 * 1000)+ .describe("Wall-clock ceiling for a single `infisical scan` invocation before its process group is killed"),+ SECRET_SCANNING_CLONE_TIMEOUT_MS: z.coerce+ .number()+ .int()+ .min(1)+ .default(10 * 60 * 1000)+ .describe("Wall-clock ceiling for a single `git clone` invocation before its process group is killed"),+ SECRET_SCANNING_MEMORY_LIMIT_MB: z.coerce+ .number()+ .int()+ .min(0)+ .default(2048)+ .describe(+ "Soft memory ceiling (GOMEMLIMIT) handed to the Go scanner process. The runtime GCs harder as it approaches the limit rather than growing. Set to 0 to disable."+ ),+ SECRET_SCANNING_MAX_REPO_SIZE_MB: z.coerce+ .number()+ .int()+ .min(0)+ .default(5120)+ .describe("Repositories larger than this are rejected before/after cloning. Set to 0 to disable."),+ SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS: z.coerce+ .number()+ .int()+ .min(1)+ .default(60 * 60 * 1000)+ .describe(+ "A scan left in the `scanning` state for longer than this is marked failed by the reaper. Must exceed clone + scan timeouts combined."+ ),// LICENSELICENSE_SERVER_URL: zpStr(z.string().optional().default("https://portal.infisical.com")),LICENSE_SERVER_KEY: zpStr(z.string().optional()),@@ -570,6 +604,18 @@ const envSchema = z});}});++ // A scan that is still inside its own clone + scan budget is healthy, so the reaper must not be+ // able to reach it: raising one of the two timeouts without raising this one would otherwise+ // mark in-flight scans failed and notify on them.+ const scanBudgetMs = data.SECRET_SCANNING_CLONE_TIMEOUT_MS + data.SECRET_SCANNING_SCAN_TIMEOUT_MS;+ if (data.SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS <= scanBudgetMs) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS"],+ message: `SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS (${data.SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS}ms) must exceed SECRET_SCANNING_CLONE_TIMEOUT_MS + SECRET_SCANNING_SCAN_TIMEOUT_MS (${scanBudgetMs}ms), otherwise healthy in-flight scans are reaped as stuck.`+ });+ }}).transform((data) => ({...data,diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.tsindex 77988b7154..e9cdc8856e 100644--- a/backend/src/lib/cron/cron-job.ts+++ b/backend/src/lib/cron/cron-job.ts@@ -43,6 +43,7 @@ export const CronJobName = {LicenseUsageFlush: "license-usage-flush",PamCredentialRotationQueueRotations: "pam-credential-rotation-queue-rotations",DailyAlertProcessing: "daily-alert-processing",+ SecretScanningStuckScanReaper: "secret-scanning-stuck-scan-reaper",InstanceUpdateCheck: "instance-update-check"} as const;diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 27f2250cb1..15a647559c 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -785,16 +785,11 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFaif (!appCfg.QUEUE_WORKERS_ENABLED) return;- if (appCfg.QUEUE_WORKER_PROFILE === QueueWorkerProfile.Standard && NON_STANDARD_QUEUES.includes(name)) {- return;- }-- if (appCfg.QUEUE_WORKER_PROFILE === QueueWorkerProfile.SecretScanning && !SECRET_SCANNING_QUEUES.includes(name)) {- return;- }-const fipsSettings = crypto.isFipsModeEnabled() ? { settings: { repeatKeyHashAlgorithm: "sha256" as const } } : {};+ // The Queue (producer) is created regardless of worker profile — 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.queueContainer[name] = new Queue(name as string, {prefix: isClusterMode ? `{${name}}` : undefined,...queueSettings,@@ -802,7 +797,7 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFaconnection});- if (!appCfg.QUEUE_WORKERS_ENABLED || !isQueueEnabled(name)) {+ if (!isQueueEnabled(name)) {return;}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e23b544dcf..2cca4e52ef 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3815,6 +3815,7 @@ export const registerRoutes = async (auditLogService,secretScanningV2DAL,queueService,+ cronJob,projectDAL,projectMembershipDAL,smtpService,diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdxindex ae3d31b346..b2a689f78b 100644--- a/docs/self-hosting/configuration/envars.mdx+++ b/docs/self-hosting/configuration/envars.mdx@@ -983,6 +983,73 @@ You can configure third-party app connections for re-use across Infisical Projec</ParamField></Accordion>+<Accordion title="Scan limits">+ These bound the resources a single scan can consume. The defaults only trip on outliers — a+ repository large enough to exhaust a worker — so most deployments never need to change them.++<Note>+ The limits apply from the release that introduces them, on existing instances too. A repository+ above `SECRET_SCANNING_MAX_REPO_SIZE_MB` that scanned before the upgrade is now rejected before+ cloning, and the scanner runs under a memory ceiling it previously did not have. If you scan+ repositories larger than the defaults, raise both values or set them to `0` for the previous+ unbounded behaviour.+</Note>++{" "}++<ParamField+ query="SECRET_SCANNING_SCAN_TIMEOUT_MS"+ type="number"+ default="600000"+ optional+>+ How long a single scan may run before it is cancelled and the scan is marked+ failed.+</ParamField>++{" "}++<ParamField+ query="SECRET_SCANNING_CLONE_TIMEOUT_MS"+ type="number"+ default="600000"+ optional+>+ How long cloning a repository may take before it is cancelled and the scan is+ marked failed.+</ParamField>++{" "}++<ParamField+ query="SECRET_SCANNING_MEMORY_LIMIT_MB"+ type="number"+ default="2048"+ optional+>+ Soft memory ceiling for the scanner process. It collects garbage more+ aggressively as it approaches this limit rather than growing. Set to `0` to+ disable.+</ParamField>++{" "}++<ParamField+ query="SECRET_SCANNING_MAX_REPO_SIZE_MB"+ type="number"+ default="5120"+ optional+>+ Repositories larger than this are rejected instead of scanned. Set to `0` to+ disable.+</ParamField>++ <ParamField query="SECRET_SCANNING_STUCK_SCAN_TIMEOUT_MS" type="number" default="3600000" optional>+ How long a scan may stay in progress before it is assumed dead — its worker was killed — and+ marked failed. Must be larger than the clone and scan timeouts combined.+ </ParamField>+</Accordion>+## ObservabilityYou can configure Infisical to collect and expose telemetry data for analytics and monitoring.