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): improve repository size handling and enhance error management
Victor Hugo dos Santosd467f6221066
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 7cc7e5e543..df159136eb 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -248,7 +248,7 @@ 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.+**`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`).### Scheduled Jobs (Cron Manager)diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex f44a6fdc22..37200d5c34 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,17 @@ 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 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 {+ // 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 });- } catch (err) {- logger.warn(err, "audit-log-queue: Skipped audit log batch scheduler registration");+ } else {+ logger.info("audit-log-queue: Skipped audit log batch scheduler registration, queue workers are disabled");}return {diff --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 7a875ee638..f8e79c436e 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,7 +8,7 @@ import {SecretScanningResource} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import {- assertRepositoryWithinSizeLimit,+ assertProviderRepositorySizeWithinLimit,cloneRepository,convertPatchLineToFileLineNumber,replaceNonChangesWithNewlines@@ -186,19 +186,19 @@ export const BitbucketSecretScanningFactory = () => {// `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"+ await assertProviderRepositorySizeWithinLimit(resourceName, async () => {+ const { data: repository } = await request.get<{ size?: number | null }>(+ `${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)- );+ );++ return repository.size;+ });await cloneRepository({cloneUrl: `https://${encodeURIComponent(username)}:${apiToken}@bitbucket.org/${resourceName}.git`,diff --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 dc3a589e8c..ab98296434 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,7 +9,7 @@ import {SecretScanningResource} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import {- assertRepositoryWithinSizeLimit,+ assertProviderRepositorySizeWithinLimit,cloneRepository,convertPatchLineToFileLineNumber,replaceNonChangesWithNewlines@@ -136,8 +136,10 @@ export const GitHubSecretScanningFactory = () => {// 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 assertProviderRepositorySizeWithinLimit(resourceName, async () => {+ const { data: repository } = await octokit.repos.get({ owner, repo });+ return repository.size == null ? null : repository.size * 1024;+ });await cloneRepository({cloneUrl: `https://x-access-token:${token}@github.com/${resourceName}.git`,diff --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 46701301b7..c848b2fc8b 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,7 +8,7 @@ import {SecretScanningResource} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";import {- assertRepositoryWithinSizeLimit,+ assertProviderRepositorySizeWithinLimit,cloneRepository,convertPatchLineToFileLineNumber,replaceNonChangesWithNewlines@@ -264,12 +264,10 @@ export const GitLabSecretScanningFactory = ({ appConnectionDAL, kmsService }: TS// 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)- );+ await assertProviderRepositorySizeWithinLimit(resourceName, async () => {+ const project = await client.Projects.show(resourceName, { statistics: true });+ return project.statistics?.repositorySize;+ });const validatedHostname = new URL(instanceUrl).host;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 9c2446f4af..026932acfe 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@@ -66,6 +66,39 @@ export const assertRepositoryWithinSizeLimit = (resourceName: string, sizeMb: nuif (sizeMb > limitMb) throw new SecretScanningSizeLimitError(resourceName, sizeMb, limitMb);};+const BYTES_PER_MB = 1024 * 1024;++/**+ * Reads a provider's reported repository size and applies the ceiling to it. The lookup is an+ * optimisation — `assertClonedRepositoryWithinSizeLimit` enforces the same ceiling once the clone+ * is on disk — so a rate-limited, forbidden or otherwise failing metadata call must never fail a+ * scan that would otherwise have run. A size the provider doesn't report is "unknown", not zero:+ * `null` (GitLab hides statistics from tokens without the privilege) must not read as 0 MB and+ * quietly pass the gate.+ */+export const assertProviderRepositorySizeWithinLimit = async (+ resourceName: string,+ readSizeBytes: () => Promise<number | string | null | undefined>+) => {+ let sizeBytes: number | string | null | undefined;++ try {+ sizeBytes = await readSizeBytes();+ } catch (error) {+ logger.warn(+ error,+ `secretScanningV2: Repository size lookup failed, deferring to the post-clone check [resourceName=${resourceName}]`+ );+ return;+ }++ if (sizeBytes === null || sizeBytes === undefined) return;++ const sizeMb = Math.round(Number(sizeBytes) / BYTES_PER_MB);++ assertRepositoryWithinSizeLimit(resourceName, Number.isNaN(sizeMb) ? undefined : sizeMb);+};+const SizePackRegex = new RE2(/^size-pack:\s*(\d+)/m);/**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 4008c9c12b..3f1923402f 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@@ -256,7 +256,7 @@ export const secretScanningV2QueueServiceFactory = ({throw new Error("Unhandled resource type");}- const allFindings = await secretScanningV2DAL.findings.transaction(async (tx) => {+ const { allFindings, closedOutByThisRun } = await secretScanningV2DAL.findings.transaction(async (tx) => {let findings: TSecretScanningFindings[] = [];if (findingsPayload.length) {findings = await secretScanningV2DAL.findings.upsert(@@ -275,17 +275,28 @@ export const secretScanningV2QueueServiceFactory = ({);}- await secretScanningV2DAL.scans.update(- { id: scanId },+ // Guarded on the state this run is finishing: if the reaper already gave up on this scan,+ // the row keeps its failure and this update matches nothing. Findings are still written —+ // they are real — but the outcome the customer was told about is not rewritten underneath+ // them.+ const completedScans = await secretScanningV2DAL.scans.update(+ { id: scanId, status: SecretScanningScanStatus.Scanning },{status: SecretScanningScanStatus.Completed,statusMessage: null});- return findings;+ return { allFindings: findings, closedOutByThisRun: Boolean(completedScans.length) };});+ if (!closedOutByThisRun) {+ logger.warn(+ `secretScanningV2Queue: Full Scan finished after the scan was already closed out ${logDetails} findings=[${findingsPayload.length}] durationMs=[${Date.now() - startedAt}]`+ );+ return;+ }+const newFindings = allFindings.filter((finding) => finding.scanId === scanId);if (newFindings.length) {@@ -332,45 +343,53 @@ export const secretScanningV2QueueServiceFactory = ({if (retryCount === retryLimit) {const errorMessage = parseScanErrorMessage(error);- await secretScanningV2DAL.scans.update(- { id: scanId },+ // Only a scan this run still owns is closed out here. A failure before the status was set+ // to `scanning` leaves the row `queued`, which is why that state is accepted too — but a+ // scan the reaper has already failed and notified on is left exactly as it is.+ const failedScans = await secretScanningV2DAL.scans.update(+ {+ id: scanId,+ $in: { status: [SecretScanningScanStatus.Queued, SecretScanningScanStatus.Scanning] }+ },{status: SecretScanningScanStatus.Failed,statusMessage: errorMessage});- await queueService.queue(- QueueName.SecretScanningV2,- QueueJobs.SecretScanningV2SendNotification,- {- status: SecretScanningScanStatus.Failed,- resourceName: resource.name,- dataSource,- errorMessage- },- { jobId: `secret-scanning-notification-${scanId}`, removeOnFail: true }- );+ if (failedScans.length) {+ await queueService.queue(+ QueueName.SecretScanningV2,+ QueueJobs.SecretScanningV2SendNotification,+ {+ status: SecretScanningScanStatus.Failed,+ resourceName: resource.name,+ dataSource,+ errorMessage+ },+ { jobId: `secret-scanning-notification-${scanId}`, 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: resource.id,- resourceType: resource.type,- scanId,- scanStatus: SecretScanningScanStatus.Failed,- scanType: SecretScanningScanType.FullScan+ 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: resource.id,+ resourceType: resource.type,+ scanId,+ scanStatus: SecretScanningScanStatus.Failed,+ scanType: SecretScanningScanType.FullScan+ }}- }- });+ });+ }}logger.error(@@ -511,7 +530,7 @@ export const secretScanningV2QueueServiceFactory = ({configPath});- const allFindings = await secretScanningV2DAL.findings.transaction(async (tx) => {+ const { allFindings, closedOutByThisRun } = await secretScanningV2DAL.findings.transaction(async (tx) => {let findings: TSecretScanningFindings[] = [];if (findingsPayload.length) {@@ -531,16 +550,24 @@ export const secretScanningV2QueueServiceFactory = ({);}- await secretScanningV2DAL.scans.update(- { id: scanId },+ // Same guard as the full scan: a scan the reaper already failed keeps that outcome.+ const completedScans = await secretScanningV2DAL.scans.update(+ { id: scanId, status: SecretScanningScanStatus.Scanning },{status: SecretScanningScanStatus.Completed});- return findings;+ return { allFindings: findings, closedOutByThisRun: Boolean(completedScans.length) };});+ if (!closedOutByThisRun) {+ logger.warn(+ `secretScanningV2Queue: Diff Scan finished after the scan was already closed out ${logDetails} findings=[${findingsPayload.length}] durationMs=[${Date.now() - startedAt}]`+ );+ return;+ }+const newFindings = allFindings.filter((finding) => finding.scanId === scanId);if (newFindings.length) {@@ -590,45 +617,52 @@ export const secretScanningV2QueueServiceFactory = ({if (retryCount === retryLimit) {const errorMessage = parseScanErrorMessage(error);- await secretScanningV2DAL.scans.update(- { id: scanId },+ // Same guard as the full scan: `queued` covers a failure before the scan started, and a+ // scan the reaper already closed out is left alone.+ const failedScans = await secretScanningV2DAL.scans.update(+ {+ id: scanId,+ $in: { status: [SecretScanningScanStatus.Queued, SecretScanningScanStatus.Scanning] }+ },{status: SecretScanningScanStatus.Failed,statusMessage: errorMessage});- await queueService.queue(- QueueName.SecretScanningV2,- QueueJobs.SecretScanningV2SendNotification,- {- status: SecretScanningScanStatus.Failed,- resourceName: resource.name,- dataSource,- errorMessage- },- { jobId: `secret-scanning-notification-${scanId}` }- );+ if (failedScans.length) {+ await queueService.queue(+ QueueName.SecretScanningV2,+ QueueJobs.SecretScanningV2SendNotification,+ {+ status: SecretScanningScanStatus.Failed,+ resourceName: resource.name,+ dataSource,+ errorMessage+ },+ { jobId: `secret-scanning-notification-${scanId}` }+ );- 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: resource.id,- resourceType: resource.type,- scanId,- scanStatus: SecretScanningScanStatus.Failed,- scanType: SecretScanningScanType.DiffScan+ 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: resource.id,+ resourceType: resource.type,+ scanId,+ scanStatus: SecretScanningScanStatus.Failed,+ scanType: SecretScanningScanType.DiffScan+ }}- }- });+ });+ }}logger.error(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.tsindex f5cac6eed4..c9ec13532a 100644--- a/backend/src/ee/services/secret-scanning/secret-scanning-exec.test.ts+++ b/backend/src/ee/services/secret-scanning/secret-scanning-exec.test.ts@@ -55,6 +55,36 @@ describe("execFileBounded", () => {expect(execError.message).not.toContain("boom");});+ test("redacts credentials embedded in a URL out of the retained output", async () => {+ // What a clone against a rejected token can print: the remote URL carries the credential+ // inline, and `output` ends up in logs wherever the error object is serialized.+ const error = await execFileBounded(+ "sh",+ [+ "-c",+ "echo \"fatal: could not read from 'https://x-access-token:[email protected]/acme/app.git'\" >&2; exit 128"+ ],+ { phase: SecretScanningExecPhase.Clone, timeoutMs: 10_000 }+ ).catch((err: unknown) => err);++ const execError = error as SecretScanningExecError;+ expect(execError.output).not.toContain("ghs_supersecret");+ expect(execError.output).not.toContain("x-access-token");+ // The rest of the line survives: it is what tells an operator what actually failed.+ expect(execError.output).toContain("github.com/acme/app.git");+ });++ test("decodes multi-byte output split across chunk boundaries", async () => {+ // printf writes the two halves of a 3-byte character in separate writes, so a per-chunk+ // toString would turn one character into replacement characters.+ const output = await execFileBounded("sh", ["-c", 'printf "\\xe2\\x9c"; sleep 0.2; printf "\\x93"'], {+ phase: SecretScanningExecPhase.Scan,+ timeoutMs: 10_000+ });++ expect(output).toBe("✓");+ });+test("rejects when the binary cannot be started", async () => {const error = await execFileBounded("this-binary-does-not-exist", [], {phase: SecretScanningExecPhase.Scan,diff --git a/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts b/backend/src/ee/services/secret-scanning/secret-scanning-exec.tsindex d7bc45000b..71382e5255 100644--- a/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts+++ b/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts@@ -1,4 +1,6 @@import { spawn } from "child_process";+import RE2 from "re2";+import { StringDecoder } from "string_decoder";import { getConfig } from "@app/lib/config/env";@@ -21,6 +23,14 @@ export enum SecretScanningExecPhase {const MAX_RETAINED_OUTPUT_CHARS = 4_000;+// Clone URLs carry the credential inline (`https://x-access-token:<token>@github.com/...`). Current+// git strips the userinfo before printing a URL back, but that is git's choice, not a guarantee we+// hold — the token is redacted here, at the point of capture, so nothing downstream has to be+// careful about logging `output`.+const UrlCredentialsRegex = new RE2(/([a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi);++const redactUrlCredentials = (value: string) => value.replace(UrlCredentialsRegex, "$1[REDACTED]@");+type TSecretScanningExecErrorParams = {failure: SecretScanningExecFailure;phase: SecretScanningExecPhase;@@ -72,7 +82,9 @@ export class SecretScanningExecError extends Error {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;+ const retainedOutput =+ output.length > MAX_RETAINED_OUTPUT_CHARS ? output.slice(-MAX_RETAINED_OUTPUT_CHARS) : output;+ this.output = redactUrlCredentials(retainedOutput);this.exitCode = exitCode;this.signal = signal;this.timeoutMs = timeoutMs;@@ -128,14 +140,38 @@ export const execFileBounded = (let output = "";let capturedBytes = 0;- const capture = (chunk: Buffer) => {+ // One decoder per stream: a multi-byte character split across two reads would otherwise be+ // decoded as two replacement characters.+ const decoders = { stdout: new StringDecoder("utf8"), stderr: new StringDecoder("utf8") };+ const capture = (stream: keyof typeof decoders) => (chunk: Buffer) => {if (capturedBytes >= MAX_CAPTURED_OUTPUT_BYTES) return;capturedBytes += chunk.length;- output += chunk.toString("utf8");+ output += decoders[stream].write(chunk);};- child.stdout.on("data", capture);- child.stderr.on("data", capture);+ child.stdout.on("data", capture("stdout"));+ child.stderr.on("data", capture("stderr"));++ // Killing the process group can tear a pipe down mid-read. An `error` with no listener is an+ // uncaught exception, which would take the worker down over a child we were killing anyway, so+ // it is recorded and folded into the captured output; the exit path reports the failure.+ let stdioError: Error | undefined;+ const rememberStdioError = (err: Error) => {+ stdioError = err;+ };+ child.stdout.on("error", rememberStdioError);+ child.stderr.on("error", rememberStdioError);++ // Flush whatever each decoder is still holding, so a trailing partial character isn't dropped.+ // `error` and `close` can both fire, so this only takes effect once.+ let finalized = false;+ const finalizeOutput = () => {+ if (finalized) return;+ finalized = true;+ output += decoders.stdout.end();+ output += decoders.stderr.end();+ if (stdioError) output += `\n[stdio error] ${stdioError.message}`;+ };let timedOut = false;const timer = setTimeout(() => {@@ -145,6 +181,7 @@ export const execFileBounded = (child.on("error", (err) => {clearTimeout(timer);+ finalizeOutput();reject(new SecretScanningExecError({failure: SecretScanningExecFailure.Spawn,@@ -158,6 +195,7 @@ export const execFileBounded = (child.on("close", (exitCode, signal) => {clearTimeout(timer);+ finalizeOutput();if (timedOut) {reject(diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 3716a8d800..fb69319204 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -37,6 +37,13 @@ const zodStrBool = z.optional().transform((val) => val === "true");+/**+ * 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.+ */+const SECRET_SCANNING_SCAN_OVERHEAD_MS = 5 * 60 * 1000;+const databaseReadReplicaSchema = z.object({DB_CONNECTION_URI: z.string().describe("Postgres read replica database connection string"),@@ -605,15 +612,13 @@ 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;+ const scanBudgetMs =+ data.SECRET_SCANNING_CLONE_TIMEOUT_MS + data.SECRET_SCANNING_SCAN_TIMEOUT_MS + SECRET_SCANNING_SCAN_OVERHEAD_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.`+ 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 plus ${SECRET_SCANNING_SCAN_OVERHEAD_MS}ms of measurement and bookkeeping (${scanBudgetMs}ms), otherwise healthy in-flight scans are reaped as stuck.`});}})diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdxindex b2a689f78b..6838b8063c 100644--- a/docs/self-hosting/configuration/envars.mdx+++ b/docs/self-hosting/configuration/envars.mdx@@ -989,10 +989,10 @@ You can configure third-party app connections for re-use across Infisical Projec<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.+ above `SECRET_SCANNING_MAX_REPO_SIZE_MB` that scanned before the upgrade is now rejected — before+ cloning when the provider reports a size, otherwise once the clone is measured on disk — 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>{" "}@@ -1003,8 +1003,8 @@ You can configure third-party app connections for re-use across Infisical Projecdefault="600000"optional>- How long a single scan may run before it is cancelled and the scan is marked- failed.+ How long, in milliseconds, a single scan may run before it is cancelled and+ the scan is marked failed. Defaults to `600000` (10 minutes).</ParamField>{" "}@@ -1015,8 +1015,8 @@ You can configure third-party app connections for re-use across Infisical Projecdefault="600000"optional>- How long cloning a repository may take before it is cancelled and the scan is- marked failed.+ How long, in milliseconds, cloning a repository may take before it is+ cancelled and the scan is marked failed. Defaults to `600000` (10 minutes).</ParamField>{" "}@@ -1027,9 +1027,9 @@ You can configure third-party app connections for re-use across Infisical Projecdefault="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.+ Soft memory ceiling for the scanner process, in MB. It collects garbage more+ aggressively as it approaches this limit rather than growing. Defaults to+ `2048` (2 GB). Set to `0` to disable.</ParamField>{" "}@@ -1040,13 +1040,15 @@ You can configure third-party app connections for re-use across Infisical Projecdefault="5120"optional>- Repositories larger than this are rejected instead of scanned. Set to `0` to- disable.+ Repositories larger than this many MB are rejected instead of scanned.+ Defaults to `5120` (5 GB). 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.+ How long, in milliseconds, a scan may stay in progress before it is assumed dead — its worker+ was killed — and marked failed. Defaults to `3600000` (1 hour). Must exceed the clone and scan+ timeouts plus the time a scan spends measuring the repository and writing its results; the+ server refuses to start otherwise.</ParamField></Accordion>