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
fix PR comments
Matheus Nogueira5c27c97048c9
diff --git a/backend/AGENTS.md b/backend/AGENTS.mdindex 8600853e2d..a195fc23d5 100644--- a/backend/AGENTS.md+++ b/backend/AGENTS.md@@ -1233,7 +1233,7 @@ EE routes register before community routes so they can override/extend endpoints**Secret Scanning** is single-project (see the root `AGENTS.md`): `secret-scanning-v2-project-bootstrap.ts` creates the project with the org when it has a creator to make admin (like PAM and Agent Vault), `secret-scanning-v2-project-resolver.ts` picks the active project and lazily creates it, with every org admin as project admin, for older orgs and for orgs created from the admin console, whose admins are only invited after the org exists, and routes that take `projectId` read `req.internalSecretScanningProjectId`. A data source covers the resources it has rows for (added by a user or discovered from a push); its `config` only says where to look (Bitbucket workspace, GitLab group), never which resources, so scans, "included" state and GitLab account-scope webhooks all key off rows. Stored configs may still carry the old `includeRepos` / `includeProjects` keys, which nothing reads.-**Secret scanning scans record what started them in `trigger`** (`SecretScanningScanTrigger`: `manual`, `resources-added`, `push`, `pull-request`), separate from `type`, which says how much was scanned (`historical` / `realtime`). Rows from before the column are null. `metadata` (jsonb) holds trigger-specific data and is parsed by trigger; it is omitted from API responses. **GitHub pull request checks** are realtime scans with `trigger: pull-request`, gated on the data source's `isScanNewCommitsEnabled`. A PR on a repository that isn't a resource yet goes through `discoverResource`, the same discovery a push gets (skipped when discovery is off, history scanned when historical scan is on), so both webhooks add repositories the same way. `secret-scanning-v2-queue.ts` stays provider-agnostic: provider behavior goes behind hooks on the data source factory, never behind a provider check in the queue. A scan reported back to where it was requested implements `TSecretScanningScanReport` (`start`, `getCompletedScanMetadata`, `complete`, `fail`, `cancel`), which the factory builds from the diff job payload (`getDiffScanReport`, so a scan whose data source was deleted can still close it) or from the saved scan (`getScanReport`, for the stuck-scan reaper). `getDiffScanFindingsPayload` returns `{ findings, details? }`, where `details` is what the report needs beyond the findings (GitHub: commit counts). Webhook events other than pushes go through `queueDataSourceEvent` as a `TQueueSecretScanningDataSourceEvent` and are handled by the provider factory's optional `processEvent`, which gets `discoverResource` and `queueReportedDiffScan` per call (as `initialize` gets the DAL) (inserts the scan under the ID its report already carries, and closes the report if queueing fails). The `pull_request`, `check_run.rerequested`, `check_suite.rerequested` and `check_run.requested_action` webhook handlers in `github-secret-scanning-service.ts` only enqueue a reduced `TQueueGitHubPullRequestEvent` that way (job ID from the GitHub delivery ID, 3 attempts); `processGitHubPullRequestEvent` in `github-secret-scanning-fns.ts` processes it in the worker. Everything before the check run is created is safe to repeat and nothing after it throws, which is what makes the retries safe. The processor creates the check run *before* the scan row: the scan's uuid is generated in the app and sent as the check run's `external_id`, so a `check_run.rerequested` event (whose `pull_requests` is empty for forks) loads the scan by primary key and reads the PR from `metadata` (`GitHubPullRequestScanMetadataSchema`). `check_suite.rerequested` ("Re-run all checks") names only the suite, so it lists the suite's latest check run with our name and takes the same path from its `external_id`. If the check run can't be created (typically an installation that hasn't accepted the Checks permission), nothing is scanned. The scan lists commits with the compare API pinned to the event's base and head SHAs (not `pulls.listCommits`, which caps at 250 and drifts as commits land) and reuses the push path's per-commit scan, so fingerprints match and findings dedupe with push scans. The check fails on every finding in the PR's commits, not only the rows its own scan inserted: a finding a push scan saved first keeps that scan's `scanId`. Findings triaged `false-positive` or `ignore` don't fail the check: the result is judged on the rows the upsert returns, which carry their stored status, and the scan stores every finding ID in `metadata.findingIds` when it completes. A failing check offers **Skip: False positive** and **Skip: Ignore** (`PULL_REQUEST_CHECK_SKIP_ACTIONS`); the `check_run.requested_action` event verifies the scan belongs to the event's installation and repository, sets that status on the PR's findings like Infisical's own triage (audited per finding, GitHub login in `triageComment`), and starts a new check run. GitHub shows those buttons to anyone with write access to the repository. Every exit of `handleDiffScan` and the stuck-scan reaper closes the check run, since a check left `queued` blocks merging when it is required; check reporting is best effort after the scan's outcome is committed (diff scans run with one attempt).+**Secret scanning scans record what started them in `trigger`** (`SecretScanningScanTrigger`: `manual`, `resources-added`, `push`, `pull-request`), separate from `type`, which says how much was scanned (`historical` / `realtime`). Rows from before the column are null. `metadata` (jsonb) holds trigger-specific data and is parsed by trigger; it is omitted from API responses. **GitHub pull request checks** are realtime scans with `trigger: pull-request`, gated on the data source's `isScanNewCommitsEnabled`. A PR on a repository that isn't a resource yet goes through `discoverResource`, the same discovery a push gets (skipped when discovery is off, history scanned when historical scan is on), so both webhooks add repositories the same way. `secret-scanning-v2-queue.ts` stays provider-agnostic: provider behavior goes behind hooks on the data source factory, never behind a provider check in the queue. A scan reported back to where it was requested implements `TSecretScanningScanReport` (`start`, `getCompletedScanMetadata`, `complete`, `fail`, `cancel`), which the factory builds from the diff job payload (`getDiffScanReport`, so a scan whose data source was deleted can still close it) or from the saved scan (`getScanReport`, for the stuck-scan reaper). `getDiffScanFindingsPayload` returns `{ findings, details? }`, where `details` is what the report needs beyond the findings (GitHub: commit counts). Webhook events other than pushes go through `queueDataSourceEvent` as a `TQueueSecretScanningDataSourceEvent` and are handled by the provider factory's optional `processEvent`, which gets `discoverResource` and `queueReportedDiffScan` per call (as `initialize` gets the DAL) (inserts the scan under the ID its report already carries, and closes the report if queueing fails). The `pull_request`, `check_run.rerequested`, `check_suite.rerequested` and `check_run.requested_action` webhook handlers in `github-secret-scanning-service.ts` only enqueue a reduced `TQueueGitHubPullRequestEvent` that way (job ID from the GitHub delivery ID, 3 attempts); `processGitHubPullRequestEvent` in `github-secret-scanning-fns.ts` processes it in the worker. Everything before the check run is created is safe to repeat and nothing after it throws, which is what makes the retries safe. The processor creates the check run *before* the scan row: the scan's uuid is generated in the app and sent as the check run's `external_id`, so a `check_run.rerequested` event (whose `pull_requests` is empty for forks) loads the scan by primary key and reads the PR from `metadata` (`GitHubPullRequestScanMetadataSchema`). `check_suite.rerequested` ("Re-run all checks") names only the suite, so it lists the suite's latest check run with our name and takes the same path from its `external_id`. If the check run can't be created (typically an installation that hasn't accepted the Checks permission), nothing is scanned. The scan lists commits with the compare API pinned to the event's base and head SHAs (not `pulls.listCommits`, which caps at 250 and drifts as commits land) and reuses the push path's per-commit scan, so fingerprints match and findings dedupe with push scans. The check fails on every finding in the PR's commits, not only the rows its own scan inserted: a finding a push scan saved first keeps that scan's `scanId`. Findings triaged `false-positive` or `ignore` don't fail the check: the result is judged on the rows the upsert returns, which carry their stored status, and the scan stores every finding ID in `metadata.findingIds` when it completes. A failing check offers **Skip: False positive** and **Skip: Ignore** (`PULL_REQUEST_CHECK_SKIP_ACTIONS`); the `check_run.requested_action` event verifies the scan belongs to the event's installation and repository, sets that status on the PR's findings like Infisical's own triage (audited per finding, GitHub login in `triageComment`), and starts a new check run. GitHub shows those buttons to anyone with write access to the repository. Every exit of `handleDiffScan` (including a failure before the scan starts) and the stuck-scan reaper closes the check run, since a check left `queued` blocks merging when it is required. The reaper fails realtime scans left `queued` past the stuck-scan timeout as well as stuck `scanning` ones, because a realtime job's payload isn't stored and can't be redelivered; check reporting is best effort after the scan's outcome is committed (diff scans run with one attempt).**Dynamic secret lease secrets needed at revoke time go in `dynamic_secret_leases.encryptedLeaseData`**, never in `externalEntityId` or `config` (both plaintext, and `externalEntityId` is returned by every lease route and logged in audit events). A provider opts in by listing the `create()` `data` keys in `persistedLeaseFields`; the lease service encrypts them with the project's SecretManager key and every revoke path passes them back as `metadata.leaseData`. Lease routes return `SanitizedDynamicSecretLeaseSchema` so the column never reaches a response. Secret *config* fields are listed separately in `DYNAMIC_SECRET_SECRET_FIELDS` (`providers/redact.ts`), as dotted paths so nested secrets work (`clientAuth.clientSecret`): reads strip them via `redactStoredInputs`, and an update that omits one keeps the stored value via `restoreOmittedSecretFields`, because the update merge is shallow.diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.tsindex b0308b6cbb..429f00959e 100644--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.ts+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.ts@@ -9,7 +9,8 @@ import { TFindingsPayload } from "@app/ee/services/secret-scanning-v2/secret-scaimport {completePullRequestCheckRun,getPullRequestScanCheckRunResult,- isGitHubPullRequestScanPayload+ isGitHubPullRequestScanPayload,+ scanGitHubCommitsAndGetFindings} from "./github-secret-scanning-fns";const checksUpdate = vi.fn();@@ -26,6 +27,12 @@ vi.mock("@app/lib/config/env", async (importOriginal) => ({})}));+const scanContentAndGetFindings = vi.fn();++vi.mock("@app/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns", () => ({+ scanContentAndGetFindings: (...args: unknown[]) => scanContentAndGetFindings(...args)+}));+vi.mock("@app/lib/logger", () => ({logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }}));@@ -199,3 +206,32 @@ describe("completePullRequestCheckRun", () => {expect(checksUpdate.mock.calls[0][0].actions).toBeUndefined();});});++describe("scanGitHubCommitsAndGetFindings", () => {+ beforeEach(() => {+ scanContentAndGetFindings.mockReset();+ scanContentAndGetFindings.mockResolvedValue([]);+ });++ test("scans the patch of every file except removed ones", async () => {+ const getCommit = vi.fn().mockResolvedValue({+ data: {+ files: ["added", "modified", "renamed", "copied", "changed", "removed"].map((status) => ({+ status,+ filename: `${status}.txt`,+ patch: `@@ -0,0 +1 @@\n+${status}`+ }))+ }+ });++ await scanGitHubCommitsAndGetFindings({+ octokit: { repos: { getCommit } } as unknown as Parameters<typeof scanGitHubCommitsAndGetFindings>[0]["octokit"],+ repositoryFullName: "acme/api",+ resourceName: "acme/api",+ commits: [{ sha: "a".repeat(40), authorName: "a", authorEmail: "[email protected]", date: "", message: "m" }]+ });++ const scanned = scanContentAndGetFindings.mock.calls.map(([content]) => (content as string).trim());+ expect(scanned).toEqual(["added", "modified", "renamed", "copied", "changed"]);+ });+});diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.tsindex afb38644bc..f96ba6c0d5 100644--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.ts+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.ts@@ -141,7 +141,8 @@ export const scanGitHubCommitsAndGetFindings = async ({if (!commitData.data.files) continue;for (const file of commitData.data.files) {- if ((file.status === "added" || file.status === "modified") && file.patch) {+ // A renamed, copied or changed file's patch can add lines too; a removed file's adds none.+ if (file.status !== "removed" && file.patch) {// eslint-disable-next-lineconst findings = await scanContentAndGetFindings(replaceNonChangesWithNewlines(`\n${file.patch}`), configPath);@@ -690,7 +691,8 @@ export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<Treturn;}- const previousScan = await secretScanningV2DAL.scans.findById(scanId.data);+ // Primary: the event can arrive right after the scan completed, before a replica has its final metadata.+ const previousScan = await secretScanningV2DAL.scans.findById(scanId.data, secretScanningV2DAL.primaryNode());const metadata = GitHubPullRequestScanMetadataSchema.safeParse(previousScan?.metadata);if (!previousScan || previousScan.trigger !== SecretScanningScanTrigger.PullRequest || !metadata.success) {@@ -775,8 +777,11 @@ export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<Treturn;}+ // Primary throughout: a click right after the check completes can reach a replica that still has the scan's queued+ // metadata, with no finding IDs, or no scan at all.+ const primary = secretScanningV2DAL.primaryNode();const scanId = z.string().uuid().safeParse(externalId);- const previousScan = scanId.success ? await secretScanningV2DAL.scans.findById(scanId.data) : undefined;+ const previousScan = scanId.success ? await secretScanningV2DAL.scans.findById(scanId.data, primary) : undefined;const metadata = GitHubPullRequestScanMetadataSchema.safeParse(previousScan?.metadata);if (!previousScan || previousScan.trigger !== SecretScanningScanTrigger.PullRequest || !metadata.success) {@@ -786,8 +791,10 @@ export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<Treturn;}- const resource = await secretScanningV2DAL.resources.findById(previousScan.resourceId);- const dataSource = resource ? await secretScanningV2DAL.dataSources.findById(resource.dataSourceId) : undefined;+ const resource = await secretScanningV2DAL.resources.findById(previousScan.resourceId, primary);+ const dataSource = resource+ ? await secretScanningV2DAL.dataSources.findById(resource.dataSourceId, primary)+ : undefined;if (!resource ||@@ -805,7 +812,7 @@ export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<Tconst { pullRequestNumber, findingIds = [] } = metadata.data;const findings = findingIds.length- ? await secretScanningV2DAL.findings.find({ resourceId: resource.id, $in: { id: findingIds } })+ ? await secretScanningV2DAL.findings.find({ resourceId: resource.id, $in: { id: findingIds } }, { tx: primary }): [];const findingsToSkip = findings.filter((finding) => !isPullRequestCheckSkipStatus(finding.status));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 941a214d59..335d0ae8c5 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@@ -527,7 +527,16 @@ export const secretScanningV2DALFactory = (db: TDbClient) => {const findStuckScans = async (startedBefore: Date, limit: number, tx?: Knex) => {try {const scans = await (tx || db)(TableName.SecretScanningScan)- .where(`${TableName.SecretScanningScan}.status`, SecretScanningScanStatus.Scanning)+ // A realtime scan still queued this long lost its job: nothing redelivers it, unlike a queued historical scan.+ .where((qb) => {+ void qb+ .where(`${TableName.SecretScanningScan}.status`, SecretScanningScanStatus.Scanning)+ .orWhere((queued) => {+ void queued+ .where(`${TableName.SecretScanningScan}.status`, SecretScanningScanStatus.Queued)+ .where(`${TableName.SecretScanningScan}.type`, SecretScanningScanType.Realtime);+ });+ })// 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 poddiff --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 ca7f9d0232..9f8fd88f23 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@@ -82,6 +82,7 @@ const STUCK_SCAN_REAP_BATCH_SIZE = 100;const QUEUED_SCAN_REDELIVERY_GRACE = ms("5m");const STUCK_SCAN_STATUS_MESSAGE ="The scan did not complete and was cancelled. This usually means the resource is too large to scan.";+const NEVER_STARTED_SCAN_STATUS_MESSAGE = "The scan was queued but never started.";// A full scan usually dies because the worker was OOM-killed on a large repository, which retrying// does resolve — the pod that picks it up next is not the one that ran out of memory. The two@@ -774,18 +775,46 @@ export const secretScanningV2QueueServiceFactory = ({const report = factory.getDiffScanReport?.(payload);- // Primary for the same reason as the full scan: a lagging replica would drop a just-queued scan.- const primary = secretScanningV2DAL.primaryNode();- const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId, primary);- const resource = dataSource ? await secretScanningV2DAL.resources.findById(resourceId, primary) : undefined;+ const prepareScan = async () => {+ // Primary for the same reason as the full scan: a lagging replica would drop a just-queued scan.+ const primary = secretScanningV2DAL.primaryNode();+ const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId, primary);+ const resource = dataSource ? await secretScanningV2DAL.resources.findById(resourceId, primary) : undefined;++ if (!dataSource || !resource) return null;++ return { dataSource, resource, tempFolder: await createTempFolder() };+ };++ let prepared: Awaited<ReturnType<typeof prepareScan>>;++ try {+ prepared = await prepareScan();+ } catch (error) {+ logger.error(error, `secretScanningV2Queue: Diff Scan could not be prepared ${logDetails}`);++ // Nothing redelivers a diff scan, so its last attempt closes it out here rather than leaving it queued. If even+ // that fails, the stuck-scan reaper fails it later.+ if (retryCount === retryLimit) {+ const statusMessage = parseScanErrorMessage(error);++ try {+ if (await markScanAsFailed({ scanId, statusMessage })) await report?.fail({ reason: statusMessage });+ } catch (markError) {+ logger.error(markError, `secretScanningV2Queue: Failed to mark unprepared diff scan as failed ${logDetails}`);+ }+ }- if (!dataSource || !resource) {+ throw error;+ }++ if (!prepared) {logger.info(`secretScanningV2Queue: Diff Scan aborted, scan no longer exists ${logDetails}`);await report?.cancel();return;}- const tempFolder = await createTempFolder();+ const { dataSource, resource, tempFolder } = prepared;logger.info(`secretScanningV2Queue: Diff Scan Started ${logDetails} [scanType=${SecretScanningScanType.Realtime}] [tempFolder=${tempFolder}]`@@ -1088,14 +1117,19 @@ export const secretScanningV2QueueServiceFactory = ({const failStuckScan = async (scan: Awaited<ReturnType<typeof secretScanningV2DAL.scans.findStuck>>[number]) => {const logDetails = `[scanId=${scan.id}] [resourceId=${scan.resourceId}] [dataSourceId=${scan.dataSourceId}] [startedAt=${scan.startedAt?.toISOString()}]`;+ // A queued scan here is a realtime scan whose job was lost before it started; its payload isn't stored, so it can't+ // be redelivered the way a queued historical scan is.+ const statusMessage =+ scan.status === SecretScanningScanStatus.Queued ? NEVER_STARTED_SCAN_STATUS_MESSAGE : STUCK_SCAN_STATUS_MESSAGE;+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 },+ { id: scan.id, status: scan.status },{status: SecretScanningScanStatus.Failed,- statusMessage: STUCK_SCAN_STATUS_MESSAGE,+ statusMessage,completedAt: new Date()});@@ -1110,7 +1144,7 @@ export const secretScanningV2QueueServiceFactory = ({await SECRET_SCANNING_FACTORY_MAP[dataSource.type as SecretScanningDataSource]({ kmsService, appConnectionDAL }).getScanReport?.({ scan, dataSource, resourceName: scan.resourceName })- ?.fail({ reason: STUCK_SCAN_STATUS_MESSAGE, isTimedOut: true });+ ?.fail({ reason: statusMessage, isTimedOut: true });await queueService.queue(QueueName.SecretScanningV2,@@ -1119,7 +1153,7 @@ export const secretScanningV2QueueServiceFactory = ({status: SecretScanningScanStatus.Failed,resourceName: scan.resourceName,dataSource,- errorMessage: STUCK_SCAN_STATUS_MESSAGE+ errorMessage: statusMessage},{ jobId: `secret-scanning-notification-${scan.id}`, removeOnFail: true });