Skip to content

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

implement initial batching

Matheus Nogueirac493d42eb9af
diff --git a/backend/src/db/migrations/20260916120000_add-last-scanned-commit-to-secret-scanning-scans.ts b/backend/src/db/migrations/20260916120000_add-last-scanned-commit-to-secret-scanning-scans.ts
index baf877cabf..59cc9d3217 100644
--- a/backend/src/db/migrations/20260916120000_add-last-scanned-commit-to-secret-scanning-scans.ts
+++ b/backend/src/db/migrations/20260916120000_add-last-scanned-commit-to-secret-scanning-scans.ts
@@ -4,20 +4,24 @@ import { TableName } from "../schemas";
export async function up(knex: Knex): Promise<void> {
const hasLastScannedCommit = await knex.schema.hasColumn(TableName.SecretScanningScan, "lastScannedCommit");
+ const hasProgressUpdatedAt = await knex.schema.hasColumn(TableName.SecretScanningScan, "progressUpdatedAt");
- if (!hasLastScannedCommit) {
+ if (!hasLastScannedCommit || !hasProgressUpdatedAt) {
await knex.schema.alterTable(TableName.SecretScanningScan, (t) => {
- t.string("lastScannedCommit").nullable();
+ if (!hasLastScannedCommit) t.string("lastScannedCommit").nullable();
+ if (!hasProgressUpdatedAt) t.timestamp("progressUpdatedAt").nullable();
});
}
}
export async function down(knex: Knex): Promise<void> {
const hasLastScannedCommit = await knex.schema.hasColumn(TableName.SecretScanningScan, "lastScannedCommit");
+ const hasProgressUpdatedAt = await knex.schema.hasColumn(TableName.SecretScanningScan, "progressUpdatedAt");
- if (hasLastScannedCommit) {
+ if (hasLastScannedCommit || hasProgressUpdatedAt) {
await knex.schema.alterTable(TableName.SecretScanningScan, (t) => {
- t.dropColumn("lastScannedCommit");
+ if (hasLastScannedCommit) t.dropColumn("lastScannedCommit");
+ if (hasProgressUpdatedAt) t.dropColumn("progressUpdatedAt");
});
}
}
diff --git a/backend/src/db/schemas/secret-scanning-scans.ts b/backend/src/db/schemas/secret-scanning-scans.ts
index 619b665777..3e5c665d1c 100644
--- a/backend/src/db/schemas/secret-scanning-scans.ts
+++ b/backend/src/db/schemas/secret-scanning-scans.ts
@@ -15,7 +15,8 @@ export const SecretScanningScansSchema = z.object({
resourceId: z.string().uuid(),
createdAt: z.date().nullable().optional(),
scanningStartedAt: z.date().nullable().optional(),
- lastScannedCommit: z.string().nullable().optional()
+ lastScannedCommit: z.string().nullable().optional(),
+ progressUpdatedAt: z.date().nullable().optional()
});
export type TSecretScanningScans = z.infer<typeof SecretScanningScansSchema>;
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.ts
index 7347f7d0ab..3139d1f782 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
@@ -437,17 +437,17 @@ export const secretScanningV2DALFactory = (db: TDbClient) => {
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);
- });
- })
+ // A batched full scan outlives any single scan timeout, so what is being measured is time
+ // since the scan last made progress, not time since it started. `progressUpdatedAt` is
+ // stamped as each commit batch is persisted; rows written before it existed, or by a pod
+ // still running an older image mid-deploy, fall back to the start and then the creation
+ // time so they're reaped too.
+ .whereRaw(`COALESCE(??, ??, ??) < ?`, [
+ `${TableName.SecretScanningScan}.progressUpdatedAt`,
+ `${TableName.SecretScanningScan}.scanningStartedAt`,
+ `${TableName.SecretScanningScan}.createdAt`,
+ startedBefore
+ ])
.join(
TableName.SecretScanningResource,
`${TableName.SecretScanningResource}.id`,
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 0be4a22c59..5c27702c09 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
@@ -155,11 +155,102 @@ export const cloneRepository = async ({ cloneUrl, repoPath }: TCloneRepository):
});
};
-export async function scanDirectory(inputPath: string, outputPath: string, configPath?: string): Promise<void> {
+/**
+ * Commits are enumerated oldest-first and scanned in slices of that order, because that is the only
+ * ordering a resumed scan can trust: new commits land at the end, so an index into it still means
+ * the same commit on the next run, where a newest-first index shifts under every push.
+ *
+ * `git log` itself only walks newest-first, so a slice is expressed as a skip/count against that
+ * order. Both halves must enumerate with identical flags for the two orderings to correspond.
+ */
+const COMMIT_LIST_ARGS = ["rev-list", "--full-history", "--all"];
+
+// Enumeration is a traversal with no patch generation, so it is bounded separately from the scan
+// rather than spending any of the customer-tunable scan budget.
+const COMMIT_ENUMERATION_TIMEOUT = 5 * 60 * 1000;
+
+export type TCommitBatch = {
+ /** Commits to skip in `git log`'s newest-first order before this batch begins. */
+ skip: number;
+ maxCount: number;
+ /** The batch's newest commit, recorded as the scan's resume point once the batch completes. */
+ lastCommit: string;
+};
+
+const buildCommitBatchLogOpts = ({ skip, maxCount }: TCommitBatch) =>
+ `${COMMIT_LIST_ARGS.slice(1).join(" ")} --skip=${skip} --max-count=${maxCount}`;
+
+/**
+ * Batches are aligned on absolute position in the oldest-first ordering rather than on wherever the
+ * previous run stopped, so a resumed scan lands on the same boundaries as an uninterrupted one even
+ * if the batch size changed between runs. Overlap that alignment causes is harmless: findings are
+ * upserted on their fingerprint, so rescanning a commit rewrites the same row.
+ */
+export const planCommitBatches = async ({
+ repoPath,
+ batchSize,
+ resumeAfterCommit
+}: {
+ repoPath: string;
+ batchSize: number;
+ resumeAfterCommit?: string | null;
+}): Promise<{ totalCommits: number; batches: TCommitBatch[]; resumed: boolean }> => {
+ const boundaries: { index: number; commit: string }[] = [];
+ let totalCommits = 0;
+ let resumeIndex = -1;
+ let newestCommit = "";
+
+ // A repository with hundreds of thousands of commits emits more than the exec layer will buffer,
+ // and nothing here needs the full list: only the batch edges and the resume point are retained.
+ await execFileBounded("git", [...COMMIT_LIST_ARGS, "--reverse"], {
+ phase: SecretScanningExecPhase.Enumerate,
+ cwd: repoPath,
+ timeoutMs: COMMIT_ENUMERATION_TIMEOUT,
+ env: GIT_PROCESS_ENV,
+ onStdoutLine: (line) => {
+ const commit = line.trim();
+ if (!commit) return;
+
+ const index = totalCommits;
+ totalCommits += 1;
+ newestCommit = commit;
+
+ if (commit === resumeAfterCommit) resumeIndex = index;
+ if ((index + 1) % batchSize === 0) boundaries.push({ index, commit });
+ }
+ });
+
+ const lastIndex = totalCommits - 1;
+ if (totalCommits && boundaries[boundaries.length - 1]?.index !== lastIndex) {
+ boundaries.push({ index: lastIndex, commit: newestCommit });
+ }
+
+ const batches = boundaries
+ .map(({ index, commit }, position) => ({
+ index,
+ skip: totalCommits - 1 - index,
+ maxCount: index - position * batchSize + 1,
+ lastCommit: commit
+ }))
+ .filter(({ index }) => index > resumeIndex)
+ .map(({ skip, maxCount, lastCommit }) => ({ skip, maxCount, lastCommit }));
+
+ return { totalCommits, batches, resumed: resumeIndex >= 0 };
+};
+
+export async function scanDirectory(
+ inputPath: string,
+ outputPath: string,
+ configPath?: string,
+ logOpts?: string
+): Promise<void> {
const args = ["scan", "--exit-code=77", "-r", outputPath];
if (configPath) {
args.push("-c", configPath);
}
+ if (logOpts) {
+ args.push(`--log-opts=${logOpts}`);
+ }
await execFileBounded("infisical", args, {
phase: SecretScanningExecPhase.Scan,
@@ -195,9 +286,11 @@ export async function scanFile(inputPath: string, configPath?: string): Promise<
export const scanGitRepositoryAndGetFindings = async (
scanPath: string,
findingsPath: string,
- configPath?: string
+ configPath?: string,
+ batch?: TCommitBatch
): TGetFindingsPayload => {
- await scanDirectory(scanPath, findingsPath, configPath);
+ const logOpts = batch ? buildCommitBatchLogOpts(batch) : undefined;
+ await scanDirectory(scanPath, findingsPath, configPath, logOpts);
const findingsData = JSON.parse(await readFindingsFile(findingsPath)) as SecretMatch[];
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 e64947653a..ad28b9b4a2 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
@@ -10,6 +10,7 @@ import {
import {
assertClonedRepositoryWithinSizeLimit,
parseScanErrorMessage,
+ planCommitBatches,
scanGitRepositoryAndGetFindings
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-fns";
import { getConfig } from "@app/lib/config/env";
@@ -204,12 +205,17 @@ export const secretScanningV2QueueServiceFactory = ({
if (!resource) throw new Error(`Resource with ID "${resourceId}" not found`);
+ const scan = await secretScanningV2DAL.scans.findById(scanId);
+
+ if (!scan) throw new Error(`Scan with ID "${scanId}" not found`);
+
try {
await secretScanningV2DAL.scans.update(
{ id: scanId },
{
status: SecretScanningScanStatus.Scanning,
- scanningStartedAt: new Date()
+ scanningStartedAt: new Date(),
+ progressUpdatedAt: new Date()
}
);
@@ -243,7 +249,47 @@ export const secretScanningV2QueueServiceFactory = ({
await writeTextToFile(configPath, config.content);
}
- let findingsPayload: TFindingsPayload;
+ const allFindings: TSecretScanningFindings[] = [];
+ let findingsCount = 0;
+
+ /**
+ * Each batch is made durable on its own: its findings and the commit it reached are committed
+ * before the next `infisical scan` starts, so a worker killed mid-scan resumes from there
+ * rather than re-walking history it has already paid for. Returns whether this run still owns
+ * the scan — once the reaper has given up on it, there is nothing left to make progress on.
+ */
+ const persistBatch = async (batchFindings: TFindingsPayload, lastScannedCommit?: string) =>
+ secretScanningV2DAL.findings.transaction(async (tx) => {
+ if (batchFindings.length) {
+ const findings = await secretScanningV2DAL.findings.upsert(
+ batchFindings.map((finding) => ({
+ ...finding,
+ projectId: dataSource.projectId,
+ dataSourceName: dataSource.name,
+ dataSourceType: dataSource.type,
+ resourceName: resource.name,
+ resourceType: resource.type,
+ scanId
+ })),
+ ["projectId", "fingerprint"],
+ tx,
+ ["resourceName", "dataSourceName"]
+ );
+
+ allFindings.push(...findings);
+ }
+
+ const owned = await secretScanningV2DAL.scans.update(
+ { id: scanId, status: SecretScanningScanStatus.Scanning },
+ { lastScannedCommit, progressUpdatedAt: new Date() },
+ tx
+ );
+
+ return Boolean(owned.length);
+ });
+
+ let stillOwned = true;
+
switch (resource.type) {
case SecretScanningResource.Repository:
case SecretScanningResource.Project: {
@@ -251,51 +297,76 @@ export const secretScanningV2QueueServiceFactory = ({
logger.info(`secretScanningV2Queue: Full Scan Cloned ${logDetails} repoSizeMb=[${repoSizeMb ?? "unknown"}]`);
- findingsPayload = await scanGitRepositoryAndGetFindings(scanPath, findingsPath, configPath);
+ const { SECRET_SCANNING_COMMIT_BATCH_SIZE: batchSize } = getConfig();
+
+ if (!batchSize) {
+ const batchFindings = await scanGitRepositoryAndGetFindings(scanPath, findingsPath, configPath);
+ findingsCount += batchFindings.length;
+ stillOwned = await persistBatch(batchFindings);
+ break;
+ }
+
+ const plan = await planCommitBatches({
+ repoPath: scanPath,
+ batchSize,
+ resumeAfterCommit: scan.lastScannedCommit
+ });
+
+ // A rewritten history (force push, or a rebase landing between runs) can take the commit
+ // this scan stopped at out of the repository entirely, leaving nothing to resume from.
+ if (scan.lastScannedCommit && !plan.resumed) {
+ logger.warn(
+ `secretScanningV2Queue: Full Scan resume point is no longer in the repository, restarting ${logDetails} [lastScannedCommit=${scan.lastScannedCommit}]`
+ );
+ }
+
+ logger.info(
+ `secretScanningV2Queue: Full Scan Planned ${logDetails} totalCommits=[${plan.totalCommits}] batches=[${plan.batches.length}] batchSize=[${batchSize}] resumed=[${plan.resumed}]`
+ );
+
+ for (const [index, batch] of plan.batches.entries()) {
+ // eslint-disable-next-line no-await-in-loop
+ const batchFindings = await scanGitRepositoryAndGetFindings(
+ scanPath,
+ join(tempFolder, `findings-${index}.json`),
+ configPath,
+ batch
+ );
+
+ findingsCount += batchFindings.length;
+
+ // eslint-disable-next-line no-await-in-loop
+ stillOwned = await persistBatch(batchFindings, batch.lastCommit);
+
+ if (!stillOwned) break;
+
+ logger.info(
+ `secretScanningV2Queue: Full Scan Batch Complete ${logDetails} batch=[${index + 1}/${plan.batches.length}] findings=[${batchFindings.length}] durationMs=[${Date.now() - startedAt}]`
+ );
+ }
+
break;
}
default:
throw new Error("Unhandled resource type");
}
- const { allFindings, closedOutByThisRun } = await secretScanningV2DAL.findings.transaction(async (tx) => {
- let findings: TSecretScanningFindings[] = [];
- if (findingsPayload.length) {
- findings = await secretScanningV2DAL.findings.upsert(
- findingsPayload.map((finding) => ({
- ...finding,
- projectId: dataSource.projectId,
- dataSourceName: dataSource.name,
- dataSourceType: dataSource.type,
- resourceName: resource.name,
- resourceType: resource.type,
- scanId
- })),
- ["projectId", "fingerprint"],
- tx,
- ["resourceName", "dataSourceName"]
- );
- }
-
- // 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
- },
- tx
- );
-
- return { allFindings: findings, closedOutByThisRun: Boolean(completedScans.length) };
- });
+ // 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 = stillOwned
+ ? await secretScanningV2DAL.scans.update(
+ { id: scanId, status: SecretScanningScanStatus.Scanning },
+ {
+ status: SecretScanningScanStatus.Completed,
+ statusMessage: null
+ }
+ )
+ : [];
- if (!closedOutByThisRun) {
+ if (!completedScans.length) {
logger.warn(
- `secretScanningV2Queue: Full Scan finished after the scan was already closed out ${logDetails} findings=[${findingsPayload.length}] durationMs=[${Date.now() - startedAt}]`
+ `secretScanningV2Queue: Full Scan finished after the scan was already closed out ${logDetails} findings=[${findingsCount}] durationMs=[${Date.now() - startedAt}]`
);
return;
}
@@ -334,13 +405,13 @@ export const secretScanningV2QueueServiceFactory = ({
scanId,
scanStatus: SecretScanningScanStatus.Completed,
scanType: SecretScanningScanType.FullScan,
- numberOfSecretsDetected: findingsPayload.length
+ numberOfSecretsDetected: findingsCount
}
}
});
logger.info(
- `secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsPayload.length}] durationMs=[${Date.now() - startedAt}]`
+ `secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsCount}] durationMs=[${Date.now() - startedAt}]`
);
} catch (error) {
if (retryCount === retryLimit) {
diff --git a/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts b/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts
index 46fca3c4b5..673907cdd9 100644
--- a/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts
+++ b/backend/src/ee/services/secret-scanning/secret-scanning-exec.ts
@@ -18,6 +18,7 @@ export enum SecretScanningExecFailure {
export enum SecretScanningExecPhase {
Clone = "clone",
Measure = "measure",
+ Enumerate = "enumerate",
Scan = "scan"
}
@@ -123,12 +124,18 @@ type TExecFileBoundedOptions = {
env?: Record<string, string>;
/** Exit codes treated as success. The scanner uses 77 to signal "findings were written". */
successExitCodes?: number[];
+ /**
+ * Consumes stdout a line at a time instead of buffering it. `git rev-list` on a large repository
+ * emits far more than the capture ceiling below, and the caller only needs to fold over the
+ * lines, so with this set stdout is never accumulated and the resolved value is stderr only.
+ */
+ onStdoutLine?: (line: string) => void;
};
export const execFileBounded = (
file: string,
args: string[],
- { phase, cwd, timeoutMs, env, successExitCodes = [0] }: TExecFileBoundedOptions
+ { phase, cwd, timeoutMs, env, successExitCodes = [0], onStdoutLine }: TExecFileBoundedOptions
): Promise<string> =>
new Promise((resolve, reject) => {
const child = spawn(file, args, {
@@ -149,7 +156,16 @@ export const execFileBounded = (
output += decoders[stream].write(chunk);
};
- child.stdout.on("data", capture("stdout"));
+ // A line can straddle two chunks, so the tail is held back until the next one arrives.
+ const emitLine = onStdoutLine ?? (() => {});
+ let pendingLine = "";
+ const consumeLines = (chunk: Buffer) => {
+ const lines = (pendingLine + decoders.stdout.write(chunk)).split("\n");
+ pendingLine = lines.pop() ?? "";
+ for (const line of lines) emitLine(line);
+ };
+
+ child.stdout.on("data", onStdoutLine ? consumeLines : 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
@@ -168,7 +184,13 @@ export const execFileBounded = (
const finalizeOutput = () => {
if (finalized) return;
finalized = true;
- output += decoders.stdout.end();
+ if (onStdoutLine) {
+ pendingLine += decoders.stdout.end();
+ if (pendingLine) emitLine(pendingLine);
+ pendingLine = "";
+ } else {
+ output += decoders.stdout.end();
+ }
output += decoders.stderr.end();
if (stdioError) output += `\n[stdio error] ${stdioError.message}`;
};
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index 7672c48ae7..21d0242217 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -469,6 +469,14 @@ const envSchema = z
.describe(
"CPU thread ceiling for scanning child processes, applied as GOMAXPROCS to the Go scanner and pack.threads to git clone. Both otherwise use every core on the host, so one full scan can saturate the instance. Set to 0 to remove the cap."
),
+ SECRET_SCANNING_COMMIT_BATCH_SIZE: z.coerce
+ .number()
+ .int()
+ .min(0)
+ .default(1000)
+ .describe(
+ "Commits scanned per `infisical scan` invocation during a full scan. Each batch's findings and resume point are persisted before the next one starts, so a worker killed mid-scan resumes rather than restarting. Set to 0 to scan the whole history in a single invocation."
+ ),
SECRET_SCANNING_MAX_REPO_SIZE_MB: z.coerce
.number()
.int()