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
don't overwrite legit scan
Matheus Nogueira7060840a7dcf
diff --git a/backend/AGENTS.md b/backend/AGENTS.mdindex a02d61a2cf..a857cf7ff5 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`. Pull requests from forks (`head.repo` differs from the base repository, or was deleted) aren't scanned and don't discover the repository: anyone can open one on a public repository, so scanning them would let any GitHub account spend the shared scan workers and the installation's API quota and plant findings. They get a check run created already completed with conclusion `skipped`, which passes branch protection, and their commits are scanned by the push scan once merged. 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).+**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`. Pull requests from forks (`head.repo` differs from the base repository, or was deleted) aren't scanned and don't discover the repository: anyone can open one on a public repository, so scanning them would let any GitHub account spend the shared scan workers and the installation's API quota and plant findings. They get a check run with the scan's check name created already completed with conclusion `skipped`, which passes branch protection, unless the head commit already has one of our check runs: checks belong to the commit, and the newest run counts, so a skipped check would otherwise replace a same-repository PR's failed scan of that commit. Their commits are scanned by the push scan once merged. 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 35ede0a4f7..f9c5d918e0 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@@ -16,9 +16,10 @@ import {const checksUpdate = vi.fn();const checksCreate = vi.fn();+const checksListForRef = vi.fn();vi.mock("probot", () => ({- ProbotOctokit: vi.fn(() => ({ checks: { update: checksUpdate, create: checksCreate } }))+ ProbotOctokit: vi.fn(() => ({ checks: { update: checksUpdate, create: checksCreate, listForRef: checksListForRef } }))}));vi.mock("@app/lib/config/env", async (importOriginal) => ({@@ -239,21 +240,32 @@ describe("scanGitHubCommitsAndGetFindings", () => {});describe("createSkippedPullRequestCheckRun", () => {- test("creates a check that is already completed as skipped, with no scan behind it", async () => {+ const params = {+ installationId: "1",+ repositoryFullName: "acme/api",+ headSha: "b".repeat(40),+ title: "Fork not scanned",+ summary: "summary"+ };++ beforeEach(() => {checksCreate.mockReset();+ checksListForRef.mockReset();+ });- await createSkippedPullRequestCheckRun({- installationId: "1",- repositoryFullName: "acme/api",- headSha: "b".repeat(40),- title: "Fork not scanned",- summary: "summary"- });+ test("creates a check with the scan's name, already completed as skipped, with no scan behind it", async () => {+ checksListForRef.mockResolvedValue({ data: { total_count: 0, check_runs: [] } });+ expect(await createSkippedPullRequestCheckRun(params)).toBe(true);++ expect(checksListForRef).toHaveBeenCalledWith(+ expect.objectContaining({ ref: "b".repeat(40), check_name: "Infisical Secret Scanning", app_id: 1 })+ );expect(checksCreate).toHaveBeenCalledWith(expect.objectContaining({owner: "acme",repo: "api",+ name: "Infisical Secret Scanning",head_sha: "b".repeat(40),status: "completed",conclusion: "skipped"@@ -261,4 +273,11 @@ describe("createSkippedPullRequestCheckRun", () => {);expect(checksCreate.mock.calls[0][0]).not.toHaveProperty("external_id");});++ test("leaves a commit that a scan already reported on alone", async () => {+ checksListForRef.mockResolvedValue({ data: { total_count: 1, check_runs: [{ id: 7 }] } });++ expect(await createSkippedPullRequestCheckRun(params)).toBe(false);+ expect(checksCreate).not.toHaveBeenCalled();+ });});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 0d3b9b8604..ead1f4bedc 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@@ -290,7 +290,10 @@ export const createPullRequestCheckRun = async ({return data.id;};-// Completed on creation, so a required check doesn't block the pull request. `skipped` passes branch protection.+// Completed on creation and named like the scan's check, so a required check doesn't block the pull request: `skipped`+// passes branch protection. Checks belong to the commit, not the pull request, and the newest run with our name is the+// one GitHub counts, so a commit a scan already reported on keeps that result. Otherwise pushing a scanned head to a fork+// and opening a pull request from it would turn a failed check into a skipped one. Returns whether it was created.export const createSkippedPullRequestCheckRun = async ({installationId,repositoryFullName,@@ -307,16 +310,29 @@ export const createSkippedPullRequestCheckRun = async ({const octokit = getGitHubRadarInstallationOctokit(installationId);const { owner, repo } = splitRepositoryFullName(repositoryFullName);+ const { data: existing } = await octokit.checks.listForRef({+ owner,+ repo,+ ref: headSha,+ check_name: GITHUB_PULL_REQUEST_CHECK_NAME,+ app_id: Number(getConfig().INF_APP_CONNECTION_GITHUB_RADAR_APP_ID),+ per_page: 1+ });++ if (existing.total_count > 0) return false;+await octokit.checks.create({owner,repo,- name: `${GITHUB_PULL_REQUEST_CHECK_NAME} (fork skipped)`,+ name: GITHUB_PULL_REQUEST_CHECK_NAME,head_sha: headSha,status: "completed",conclusion: "skipped",completed_at: new Date().toISOString(),output: { title, summary }});++ return true;};// A suite holds one App's check runs for one commit; `latest` returns only the newest run with our check's name.@@ -649,7 +665,7 @@ export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<T// scanned once merged, by the push scan. Nothing is discovered either.if (isFromFork) {try {- await createSkippedPullRequestCheckRun({+ const created = await createSkippedPullRequestCheckRun({installationId: String(installationId),repositoryFullName: repository.full_name,headSha: pullRequest.headSha,@@ -657,6 +673,12 @@ export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<Tsummary:"Infisical doesn't scan pull requests from forks. Their commits are scanned after they are merged into this repository."});++ if (!created) {+ logger.info(+ `secretScanningV2PullRequestEvent: GitHub - fork pull request head already has a check run, leaving it ${logDetails}`+ );+ }} catch (error) {logger.warn(error,