Skip to content

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

count findings from db

Matheus Nogueiraf9a4309413ca
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 3139d1f782..b895069106 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
@@ -486,6 +486,26 @@ export const secretScanningV2DALFactory = (db: TDbClient) => {
}
};
+ /**
+ * Counts the findings this scan was the first to discover, which is the number the scan's own
+ * detail view shows. It is read back from the database rather than accumulated in the handler
+ * because a full scan persists its findings batch by batch and can be retried or resumed by
+ * another worker: whatever an in-memory counter holds covers only the batches that one attempt
+ * happened to run.
+ *
+ * Read from the primary, not a replica: the caller counts immediately after writing the last
+ * batch, so replication lag would report a total short of what it just stored.
+ */
+ const countFindingsByScanId = async (scanId: string, tx?: Knex) => {
+ try {
+ const [result] = await (tx || db)(TableName.SecretScanningFinding).where({ scanId }).count({ count: "*" });
+
+ return Number(result?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count By Scan ID - Secret Scanning Finding" });
+ }
+ };
+
return {
dataSources: {
...dataSourceOrm,
@@ -507,7 +527,10 @@ export const secretScanningV2DALFactory = (db: TDbClient) => {
findByDataSourceId: findScansByDataSourceId,
findStuck: findStuckScans
},
- findings: findingOrm,
+ findings: {
+ ...findingOrm,
+ countByScanId: countFindingsByScanId
+ },
configs: configOrm
};
};
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts
index dc04b7a747..80fd50086f 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-fns.test.ts
@@ -216,7 +216,24 @@ describe("planCommitBatches", () => {
});
});
- test("restarts when a newly reachable ref lands commits ahead of the resume point", async () => {
+ test("enumerates the default branch only", async () => {
+ await withRepo(async (repoPath) => {
+ await commit(repoPath, "a", "2020-01-01T00:00:00Z");
+ await commit(repoPath, "b", "2020-01-02T00:00:00Z");
+
+ // Never merged, so it is not part of the default branch's history. Commits that only ever
+ // existed on another branch are covered by realtime scanning of the push that created them.
+ await git(repoPath, ["checkout", "-b", "feature"]);
+ await commit(repoPath, "unmerged", "2020-01-03T00:00:00Z");
+ await git(repoPath, ["checkout", "main"]);
+
+ const plan = await planCommitBatches({ repoPath, batchSize: 10 });
+
+ expect(plan.totalCommits).toBe(2);
+ });
+ });
+
+ test("restarts when a merge lands commits ahead of the resume point", async () => {
await withRepo(async (repoPath) => {
await commit(repoPath, "a", "2020-01-01T00:00:00Z");
await commit(repoPath, "b", "2020-01-02T00:00:00Z");
@@ -225,11 +242,13 @@ describe("planCommitBatches", () => {
const [firstBatch] = (await planCommitBatches({ repoPath, batchSize: 2 })).batches;
- // A branch rooted before the resume point, carrying a commit older than it. `--all` picks it
- // up and the date ordering sorts it into the prefix, shifting every index after it.
- await git(repoPath, ["checkout", "-b", "old", "HEAD~3"]);
- const smuggled = await commit(repoPath, "smuggled", "2020-01-01T12:00:00Z");
+ // A long-lived branch rooted before the resume point, merged in afterwards. Its commit keeps
+ // its own older date, so the date ordering sorts it into the prefix and shifts every index
+ // after it — on the default branch alone, with no second ref involved.
+ await git(repoPath, ["checkout", "-b", "feature", "HEAD~3"]);
+ const merged = await commit(repoPath, "feat-old", "2020-01-01T12:00:00Z");
await git(repoPath, ["checkout", "main"]);
+ await git(repoPath, ["merge", "--no-ff", "feature", "-m", "merge feature"]);
const resumed = await planCommitBatches({
repoPath,
@@ -243,9 +262,9 @@ describe("planCommitBatches", () => {
// Every commit is back in the plan, the never-scanned one included.
const planned = resumed.batches.reduce((total, batch) => total + batch.maxCount, 0);
- expect(resumed.totalCommits).toBe(5);
- expect(planned).toBe(5);
- expect(smuggled).toBeTruthy();
+ expect(resumed.totalCommits).toBe(6);
+ expect(planned).toBe(6);
+ expect(merged).toBeTruthy();
});
});
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 8edba48959..deedf3a644 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
@@ -156,21 +156,10 @@ export const cloneRepository = async ({ cloneUrl, repoPath }: TCloneRepository):
};
/**
- * Commits are enumerated oldest-first and scanned in slices of that order, because a newest-first
- * index shifts under every push while an oldest-first one usually survives: an ordinary push lands
- * its commits at the end, leaving everything before them where it was.
- *
- * "Usually" is not "always", which is what `lastScannedCommitDigest` is for. A ref that
- * becomes reachable between two runs — a new branch, a fetched tag — brings its commits in at their
- * own dates, which can be older than the resume point, so they sort into the middle of the ordering
- * and push every later index up. An index alone cannot tell that apart from the commits it used to
- * name, so the prefix is digested as it is walked and the resumed run checks the digest it stored
- * against the prefix it now sees.
- *
- * `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.
+ * Commits are enumerated oldest-first and scanned in slices of that order, this list
+ * of commits will be used to create the batches of commits for historical scans.
*/
-const COMMIT_LIST_ARGS = ["rev-list", "--full-history", "--all"];
+const COMMIT_LIST_ARGS = ["rev-list", "--full-history", "HEAD"];
export type TCommitBatch = {
/** Commits to skip in `git log`'s newest-first order before this batch begins. */
@@ -180,15 +169,16 @@ export type TCommitBatch = {
lastCommit: string;
/**
* Digest of every commit up to and including `lastCommit`, recorded beside it so the next run can
- * tell if a new commit has creeped into this batch and it needs to be rescanned.
- *
- * This scenario can happen if a rebase happens in the repository.
+ * tell if a new commit has crept into this batch and it needs to be rescanned. This prevents a history
+ * change (rebase) to cause some commits to not be scanned.
*/
prefixDigest: string;
};
+const COMMIT_LOG_OPTS = COMMIT_LIST_ARGS.slice(1).join(" ");
+
const buildCommitBatchLogOpts = ({ skip, maxCount }: TCommitBatch) =>
- `${COMMIT_LIST_ARGS.slice(1).join(" ")} --skip=${skip} --max-count=${maxCount}`;
+ `${COMMIT_LOG_OPTS} --skip=${skip} --max-count=${maxCount}`;
/**
* Batches are aligned on absolute position in the oldest-first ordering rather than on wherever the
@@ -218,10 +208,16 @@ export const planCommitBatches = async ({
let resumeIndex = -1;
let resumePrefixDigest = "";
let newestCommit = "";
- let prefixDigest = "";
- // 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.
+ // prefixDigest is the hash that is regenerated on every commit and can be
+ // recreated from history.
+ // A -> B -> C will generate a hash based on the commit sha and we can verify it
+ // if for some reason the history becomes: A -> B -> D -> C, when processing C
+ // the digest doesn't match anymore and it means that we have some unscanned commit
+ // in the history.
+ const prefix = crypto.nativeCrypto.createHash("sha256");
+ const prefixDigest = () => prefix.copy().digest("hex");
+
await execFileBounded("git", [...COMMIT_LIST_ARGS, "--reverse"], {
phase: SecretScanningExecPhase.Enumerate,
cwd: repoPath,
@@ -234,24 +230,25 @@ export const planCommitBatches = async ({
const index = totalCommits;
totalCommits += 1;
newestCommit = commit;
- prefixDigest = crypto.nativeCrypto.createHash("sha256").update(`${prefixDigest}${commit}`).digest("hex");
+ prefix.update(commit);
if (commit === resumeAfterCommit) {
resumeIndex = index;
- resumePrefixDigest = prefixDigest;
+ resumePrefixDigest = prefixDigest();
}
- if ((index + 1) % batchSize === 0) boundaries.push({ index, commit, prefixDigest });
+ if ((index + 1) % batchSize === 0) boundaries.push({ index, commit, prefixDigest: prefixDigest() });
}
});
const lastIndex = totalCommits - 1;
if (totalCommits && boundaries[boundaries.length - 1]?.index !== lastIndex) {
- boundaries.push({ index: lastIndex, commit: newestCommit, prefixDigest });
+ boundaries.push({ index: lastIndex, commit: newestCommit, prefixDigest: prefixDigest() });
}
- // Commits that became reachable since the last run can sort in ahead of the resume point, so the
- // indexes after it no longer name the commits they named then. Skipping to that index would step
- // over commits this scan has never looked at, so the only safe reading of the plan is a fresh one.
+ // If true, means that the history of commits have changed and there are unscanned commits
+ // This should only happen if a worker dies and clone the repo again after a rebase.
+ // If this happens, it means we can't continue and actually need to start over to ensure
+ // all commits are scanned.
const prefixChanged = resumeIndex >= 0 && resumePrefixDigest !== resumeAfterCommitDigest;
const resumableIndex = prefixChanged ? -1 : resumeIndex;
@@ -325,7 +322,7 @@ export const scanGitRepositoryAndGetFindings = async (
configPath?: string,
batch?: TCommitBatch
): TGetFindingsPayload => {
- const logOpts = batch ? buildCommitBatchLogOpts(batch) : undefined;
+ const logOpts = batch ? buildCommitBatchLogOpts(batch) : COMMIT_LOG_OPTS;
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 e78787c96b..ba7e5b72f8 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
@@ -320,15 +320,16 @@ export const secretScanningV2QueueServiceFactory = ({
await writeTextToFile(configPath, config.content);
}
- const allFindings: TSecretScanningFindings[] = [];
- let findingsCount = 0;
+ // Counts what this attempt scanned, for the progress logs only. The scan's finding total is
+ // read from the database at the end, because an attempt that resumes a partly-scanned scan
+ // never sees the batches an earlier one already persisted.
+ let scannedFindingsCount = 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 and its lease — once the reaper has given up on it, or another scan of the resource
- * has taken over, there is nothing left to make progress on.
+ * the scan and its lease.
*/
const persistBatch = async (
batchFindings: TFindingsPayload,
@@ -336,7 +337,7 @@ export const secretScanningV2QueueServiceFactory = ({
) => {
const owned = await secretScanningV2DAL.findings.transaction(async (tx) => {
if (batchFindings.length) {
- const findings = await secretScanningV2DAL.findings.upsert(
+ await secretScanningV2DAL.findings.upsert(
batchFindings.map((finding) => ({
...finding,
projectId: dataSource.projectId,
@@ -350,8 +351,6 @@ export const secretScanningV2QueueServiceFactory = ({
tx,
["resourceName", "dataSourceName"]
);
-
- allFindings.push(...findings);
}
const progressed = await secretScanningV2DAL.scans.update(
@@ -389,7 +388,7 @@ export const secretScanningV2QueueServiceFactory = ({
if (!batchSize) {
const batchFindings = await scanGitRepositoryAndGetFindings(scanPath, findingsPath, configPath);
- findingsCount += batchFindings.length;
+ scannedFindingsCount += batchFindings.length;
stillOwned = await persistBatch(batchFindings);
break;
}
@@ -424,7 +423,7 @@ export const secretScanningV2QueueServiceFactory = ({
batch
);
- findingsCount += batchFindings.length;
+ scannedFindingsCount += batchFindings.length;
// eslint-disable-next-line no-await-in-loop
stillOwned = await persistBatch(batchFindings, {
@@ -460,14 +459,16 @@ export const secretScanningV2QueueServiceFactory = ({
if (!completedScans.length) {
logger.warn(
- `secretScanningV2Queue: Full Scan finished after the scan was already closed out ${logDetails} findings=[${findingsCount}] durationMs=[${Date.now() - startedAt}]`
+ `secretScanningV2Queue: Full Scan finished after the scan was already closed out ${logDetails} scannedFindings=[${scannedFindingsCount}] durationMs=[${Date.now() - startedAt}]`
);
return;
}
- const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
+ // Read back rather than counted in the handler: the findings an earlier attempt persisted are
+ // part of this scan's total, and a resumed attempt never scanned the batches they came from.
+ const findingsCount = await secretScanningV2DAL.findings.countByScanId(scanId);
- if (newFindings.length) {
+ if (findingsCount) {
await queueService.queue(
QueueName.SecretScanningV2,
QueueJobs.SecretScanningV2SendNotification,
@@ -476,7 +477,7 @@ export const secretScanningV2QueueServiceFactory = ({
resourceName: resource.name,
isDiffScan: false,
dataSource,
- numberOfSecrets: newFindings.length,
+ numberOfSecrets: findingsCount,
scanId
},
{ removeOnFail: true, jobId: `secret-scanning-notification-${scanId}` }
@@ -505,7 +506,7 @@ export const secretScanningV2QueueServiceFactory = ({
});
logger.info(
- `secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsCount}] durationMs=[${Date.now() - startedAt}]`
+ `secretScanningV2Queue: Full Scan Complete ${logDetails} findings=[${findingsCount}] scannedFindings=[${scannedFindingsCount}] durationMs=[${Date.now() - startedAt}]`
);
} catch (error) {
if (retryCount === retryLimit) {