Skip to content

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

generic processEvent

Matheus Nogueira1ee5837c306c
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index b95a685767..8600853e2d 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's processor in `SECRET_SCANNING_EVENT_PROCESSOR_MAP`, which gets `discoverResource` and `queueReportedDiffScan` (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); `github-secret-scanning-event-processor.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` 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).
**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-event-processor.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-event-processor.ts
deleted file mode 100644
index 4da1402116..0000000000
--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-event-processor.ts
+++ /dev/null
@@ -1,352 +0,0 @@
-import { Repository } from "@octokit/webhooks-types";
-import { z } from "zod";
-
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import {
- SecretScanningDataSource,
- SecretScanningFindingStatus,
- SecretScanningScanTrigger
-} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
-import { TSecretScanningEventProcessor } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-types";
-import { getConfig } from "@app/lib/config/env";
-import { crypto } from "@app/lib/crypto";
-import { logger } from "@app/lib/logger";
-import { ActorType } from "@app/services/auth/auth-type";
-
-import { GitHubPullRequestEvent } from "./github-secret-scanning-enums";
-import {
- createPullRequestCheckRun,
- getLatestPullRequestCheckRunExternalId,
- getPullRequestScanMetadata,
- isPullRequestCheckSkipStatus
-} from "./github-secret-scanning-fns";
-import { GitHubPullRequestScanMetadataSchema } from "./github-secret-scanning-schemas";
-import { TGitHubPullRequestScanPayload, TQueueGitHubPullRequestEvent } from "./github-secret-scanning-types";
-
-// Runs in the secret scanning worker, so the webhook only has to enqueue the event.
-export const GitHubSecretScanningEventProcessor: TSecretScanningEventProcessor<TQueueGitHubPullRequestEvent> = ({
- secretScanningV2DAL,
- auditLogService,
- discoverResource,
- queueReportedDiffScan
-}) => {
- // Pull requests are checked only while the data source scans new commits. A repository the data source doesn't cover
- // yet is discovered the same way a push discovers it, or skipped when discovery is off. If the check run cannot be
- // created, usually because the installation has not accepted the Checks permission, there is nothing to report to
- // and nothing is scanned.
- const startPullRequestScan = async ({
- installationId,
- repository,
- pullRequest,
- expectedResourceId
- }: {
- installationId: number;
- repository: Pick<Repository, "id" | "full_name">;
- pullRequest: TGitHubPullRequestScanPayload["pullRequest"];
- expectedResourceId?: string;
- }) => {
- const logDetails = `[installationId=${installationId}] [repository=${repository.full_name}] [pullRequest=${pullRequest.number}] [headSha=${pullRequest.headSha}]`;
-
- const dataSource = await secretScanningV2DAL.dataSources.findOne({
- externalId: String(installationId),
- type: SecretScanningDataSource.GitHub
- });
-
- if (!dataSource) {
- logger.error(`secretScanningV2PullRequestEvent: GitHub - Could not find data source ${logDetails}`);
- return;
- }
-
- if (!dataSource.isScanNewCommitsEnabled) {
- logger.info(
- `secretScanningV2PullRequestEvent: GitHub - ignoring pull request, scanning new commits is disabled ${logDetails}`
- );
- return;
- }
-
- const existingResource = await secretScanningV2DAL.resources.findOne({
- dataSourceId: dataSource.id,
- externalId: String(repository.id)
- });
-
- if (!existingResource && !dataSource.isDiscoveryEnabled) {
- logger.info(
- `secretScanningV2PullRequestEvent: GitHub - ignoring pull request from unknown repository, discovery is disabled ${logDetails}`
- );
- return;
- }
-
- const resource =
- existingResource ??
- (await discoverResource({
- dataSource,
- resourcePayload: { name: repository.full_name, externalId: String(repository.id) },
- trigger: SecretScanningScanTrigger.PullRequest
- }));
-
- if (!resource) return;
-
- if (expectedResourceId && expectedResourceId !== resource.id) {
- logger.warn(
- `secretScanningV2PullRequestEvent: GitHub - ignoring re-run, the scan belongs to another resource ${logDetails} [expectedResourceId=${expectedResourceId}] [resourceId=${resource.id}]`
- );
- return;
- }
-
- const scanId = crypto.nativeCrypto.randomUUID();
- const { SITE_URL } = getConfig();
- const orgId = dataSource.connection?.orgId;
-
- let checkRunId: number;
- try {
- checkRunId = await createPullRequestCheckRun({
- installationId: String(installationId),
- repositoryFullName: repository.full_name,
- headSha: pullRequest.headSha,
- scanId,
- detailsUrl:
- SITE_URL && orgId
- ? `${SITE_URL}/organizations/${orgId}/secret-scanning/findings?resourceId=${resource.id}`
- : undefined
- });
- } catch (error) {
- logger.warn(
- error,
- `secretScanningV2PullRequestEvent: GitHub - could not create check run, skipping scan ${logDetails}`
- );
- return;
- }
-
- const payload: TGitHubPullRequestScanPayload = {
- installationId: String(installationId),
- repository: { id: repository.id, full_name: repository.full_name },
- pullRequest,
- checkRunId
- };
-
- await queueReportedDiffScan({
- scanId,
- dataSourceId: dataSource.id,
- dataSourceType: SecretScanningDataSource.GitHub,
- resourceId: resource.id,
- trigger: SecretScanningScanTrigger.PullRequest,
- metadata: getPullRequestScanMetadata(payload),
- payload
- });
- };
-
- // A re-run carries no pull request for forks, so the pull request comes from the scan the check run was created for.
- const rerunPullRequestScan = async ({
- installationId,
- repository,
- externalId,
- logDetails
- }: {
- installationId: number;
- repository: Pick<Repository, "id" | "full_name">;
- externalId: string | null;
- logDetails: string;
- }) => {
- const scanId = z.string().uuid().safeParse(externalId);
-
- if (!scanId.success) {
- logger.warn(`secretScanningV2CheckRunEvent: GitHub - check run has no scan ID ${logDetails}`);
- return;
- }
-
- const previousScan = await secretScanningV2DAL.scans.findById(scanId.data);
- const metadata = GitHubPullRequestScanMetadataSchema.safeParse(previousScan?.metadata);
-
- if (!previousScan || previousScan.trigger !== SecretScanningScanTrigger.PullRequest || !metadata.success) {
- logger.info(
- `secretScanningV2CheckRunEvent: GitHub - ignoring re-run, the pull request scan no longer exists ${logDetails} [scanId=${scanId.data}]`
- );
- return;
- }
-
- await startPullRequestScan({
- installationId,
- repository,
- pullRequest: {
- number: metadata.data.pullRequestNumber,
- baseSha: metadata.data.baseSha,
- headSha: metadata.data.headSha
- },
- expectedResourceId: previousScan.resourceId
- });
- };
-
- // "Re-run all checks" names only the suite, so the scan comes from the newest check run of ours in it.
- const rerunCheckSuite = async ({
- installationId,
- repository,
- checkSuiteId
- }: {
- installationId: number;
- repository: Pick<Repository, "id" | "full_name">;
- checkSuiteId: number;
- }) => {
- const logDetails = `[installationId=${installationId}] [repository=${repository.full_name}] [checkSuiteId=${checkSuiteId}]`;
-
- let externalId: string | null;
- try {
- externalId = await getLatestPullRequestCheckRunExternalId({
- installationId: String(installationId),
- repositoryFullName: repository.full_name,
- checkSuiteId
- });
- } catch (error) {
- logger.warn(
- error,
- `secretScanningV2CheckSuiteEvent: GitHub - could not list the suite's check runs ${logDetails}`
- );
- return;
- }
-
- if (!externalId) {
- logger.info(
- `secretScanningV2CheckSuiteEvent: GitHub - ignoring re-run, the suite has no pull request check ${logDetails}`
- );
- return;
- }
-
- await rerunPullRequestScan({ installationId, repository, externalId, logDetails });
- };
-
- // GitHub shows the skip buttons to anyone with write access to the repository, so the scan the check run names is
- // confirmed to belong to the installation and repository the event came from before any finding is changed. The
- // findings are then triaged as Infisical's own triage would, and the check is run again, which passes once every
- // finding in it is skipped.
- const skipPullRequestFindings = async ({
- installationId,
- repository,
- checkRunId,
- externalId,
- action,
- sender
- }: {
- installationId: number;
- repository: Pick<Repository, "id" | "full_name">;
- checkRunId: number;
- externalId: string | null;
- action: string;
- sender: { id: number; login: string };
- }) => {
- const logDetails = `[installationId=${installationId}] [repository=${repository.full_name}] [checkRunId=${checkRunId}] [action=${action}] [sender=${sender.login}]`;
-
- if (!isPullRequestCheckSkipStatus(action)) {
- logger.warn(`secretScanningV2CheckRunEvent: GitHub - ignoring unknown check run action ${logDetails}`);
- return;
- }
-
- const scanId = z.string().uuid().safeParse(externalId);
- const previousScan = scanId.success ? await secretScanningV2DAL.scans.findById(scanId.data) : undefined;
- const metadata = GitHubPullRequestScanMetadataSchema.safeParse(previousScan?.metadata);
-
- if (!previousScan || previousScan.trigger !== SecretScanningScanTrigger.PullRequest || !metadata.success) {
- logger.info(
- `secretScanningV2CheckRunEvent: GitHub - ignoring skip, the pull request scan no longer exists ${logDetails}`
- );
- return;
- }
-
- const resource = await secretScanningV2DAL.resources.findById(previousScan.resourceId);
- const dataSource = resource ? await secretScanningV2DAL.dataSources.findById(resource.dataSourceId) : undefined;
-
- if (
- !resource ||
- !dataSource ||
- dataSource.type !== SecretScanningDataSource.GitHub ||
- dataSource.externalId !== String(installationId) ||
- resource.externalId !== String(repository.id)
- ) {
- logger.warn(
- `secretScanningV2CheckRunEvent: GitHub - ignoring skip, the scan does not belong to this repository ${logDetails} [scanId=${previousScan.id}]`
- );
- return;
- }
-
- const { pullRequestNumber, findingIds = [] } = metadata.data;
-
- const findings = findingIds.length
- ? await secretScanningV2DAL.findings.find({ resourceId: resource.id, $in: { id: findingIds } })
- : [];
- const findingsToSkip = findings.filter((finding) => !isPullRequestCheckSkipStatus(finding.status));
-
- if (findingsToSkip.length) {
- const triageComment = `${
- action === SecretScanningFindingStatus.FalsePositive ? "Marked as a false positive" : "Ignored"
- } from GitHub by @${sender.login} on pull request ${repository.full_name}#${pullRequestNumber}.`;
- const now = new Date();
-
- await secretScanningV2DAL.findings.update(
- { $in: { id: findingsToSkip.map((finding) => finding.id) } },
- { status: action, triageComment, triagedAt: now, triagedByUserId: null, resolvedAt: null }
- );
-
- await Promise.all(
- findingsToSkip.map((finding) =>
- auditLogService.createAuditLog({
- projectId: dataSource.projectId,
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- event: {
- type: EventType.SECRET_SCANNING_FINDING_UPDATE,
- metadata: { findingId: finding.id, status: action, triageComment }
- }
- })
- )
- );
-
- logger.info(
- `secretScanningV2CheckRunEvent: GitHub - skipped pull request findings ${logDetails} [scanId=${previousScan.id}] [findings=${findingsToSkip.length}]`
- );
- }
-
- await startPullRequestScan({
- installationId,
- repository,
- pullRequest: {
- number: pullRequestNumber,
- baseSha: metadata.data.baseSha,
- headSha: metadata.data.headSha
- },
- expectedResourceId: resource.id
- });
- };
-
- const processEvent = async (job: TQueueGitHubPullRequestEvent) => {
- const { installationId, repository } = job;
-
- switch (job.event) {
- case GitHubPullRequestEvent.PullRequest:
- return startPullRequestScan({ installationId, repository, pullRequest: job.pullRequest });
- case GitHubPullRequestEvent.CheckRunRerequested:
- return rerunPullRequestScan({
- installationId,
- repository,
- externalId: job.externalId,
- logDetails: `[installationId=${installationId}] [repository=${repository.full_name}] [checkRunId=${job.checkRunId}]`
- });
- case GitHubPullRequestEvent.CheckSuiteRerequested:
- return rerunCheckSuite({ installationId, repository, checkSuiteId: job.checkSuiteId });
- case GitHubPullRequestEvent.CheckRunRequestedAction:
- return skipPullRequestFindings({
- installationId,
- repository,
- checkRunId: job.checkRunId,
- externalId: job.externalId,
- action: job.action,
- sender: job.sender
- });
- default:
- logger.error(
- `secretScanningV2PullRequestEvent: GitHub - unhandled event [event=${(job as { event: string }).event}]`
- );
- }
- };
-
- return { processEvent };
-};
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.ts
index 011c2e9669..9dcfd0fe1a 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
@@ -32,6 +32,7 @@ import {
getGitHubRadarInstallationOctokit,
getPullRequestScanMetadata,
isGitHubPullRequestScanPayload,
+ processGitHubPullRequestEvent,
scanGitHubCommitsAndGetFindings,
scanGitHubPullRequest
} from "./github-secret-scanning-fns";
@@ -217,6 +218,7 @@ export const GitHubSecretScanningFactory = () => {
getDiffScanFindingsPayload,
getDiffScanReport,
getScanReport,
+ processEvent: processGitHubPullRequestEvent,
teardown,
setupWebhook,
validateConfigUpdate
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.ts
index 48afa231be..afb38644bc 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
@@ -1,8 +1,13 @@
+import { Repository } from "@octokit/webhooks-types";
import { ProbotOctokit } from "probot";
+import { z } from "zod";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import {
+ SecretScanningDataSource,
SecretScanningFindingSeverity,
- SecretScanningFindingStatus
+ SecretScanningFindingStatus,
+ SecretScanningScanTrigger
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import {
convertPatchLineToFileLineNumber,
@@ -14,15 +19,24 @@ import {
TFindingsPayload,
TQueueSecretScanningResourceDiffScan,
TSecretScanningDiffScanFindings,
+ TSecretScanningFactoryProcessEvent,
TSecretScanningScanReport
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-types";
import { scanContentAndGetFindings } from "@app/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-fns";
import { SecretMatch } from "@app/ee/services/secret-scanning/secret-scanning-queue/secret-scanning-queue-types";
import { getConfig } from "@app/lib/config/env";
+import { crypto } from "@app/lib/crypto";
import { chunkArray } from "@app/lib/fn/array";
import { logger } from "@app/lib/logger";
+import { ActorType } from "@app/services/auth/auth-type";
-import { TGitHubPullRequestScanMetadata, TGitHubPullRequestScanPayload } from "./github-secret-scanning-types";
+import { GitHubPullRequestEvent } from "./github-secret-scanning-enums";
+import { GitHubPullRequestScanMetadataSchema } from "./github-secret-scanning-schemas";
+import {
+ TGitHubPullRequestScanMetadata,
+ TGitHubPullRequestScanPayload,
+ TQueueGitHubPullRequestEvent
+} from "./github-secret-scanning-types";
export const GITHUB_PULL_REQUEST_CHECK_NAME = "Infisical Secret Scanning";
@@ -543,3 +557,328 @@ export const createPullRequestScanReport = ({
cancel: () => tryCompletePullRequestCheckRun({ ...target, result: PULL_REQUEST_SCAN_CANCELLED_CHECK_RUN_RESULT })
};
};
+
+// Runs in the secret scanning worker, so the webhook only has to enqueue the event.
+export const processGitHubPullRequestEvent: TSecretScanningFactoryProcessEvent<TQueueGitHubPullRequestEvent> = async ({
+ event,
+ secretScanningV2DAL,
+ auditLogService,
+ discoverResource,
+ queueReportedDiffScan
+}) => {
+ // Pull requests are checked only while the data source scans new commits. A repository the data source doesn't cover
+ // yet is discovered the same way a push discovers it, or skipped when discovery is off. If the check run cannot be
+ // created, usually because the installation has not accepted the Checks permission, there is nothing to report to
+ // and nothing is scanned.
+ const startPullRequestScan = async ({
+ installationId,
+ repository,
+ pullRequest,
+ expectedResourceId
+ }: {
+ installationId: number;
+ repository: Pick<Repository, "id" | "full_name">;
+ pullRequest: TGitHubPullRequestScanPayload["pullRequest"];
+ expectedResourceId?: string;
+ }) => {
+ const logDetails = `[installationId=${installationId}] [repository=${repository.full_name}] [pullRequest=${pullRequest.number}] [headSha=${pullRequest.headSha}]`;
+
+ const dataSource = await secretScanningV2DAL.dataSources.findOne({
+ externalId: String(installationId),
+ type: SecretScanningDataSource.GitHub
+ });
+
+ if (!dataSource) {
+ logger.error(`secretScanningV2PullRequestEvent: GitHub - Could not find data source ${logDetails}`);
+ return;
+ }
+
+ if (!dataSource.isScanNewCommitsEnabled) {
+ logger.info(
+ `secretScanningV2PullRequestEvent: GitHub - ignoring pull request, scanning new commits is disabled ${logDetails}`
+ );
+ return;
+ }
+
+ const existingResource = await secretScanningV2DAL.resources.findOne({
+ dataSourceId: dataSource.id,
+ externalId: String(repository.id)
+ });
+
+ if (!existingResource && !dataSource.isDiscoveryEnabled) {
+ logger.info(
+ `secretScanningV2PullRequestEvent: GitHub - ignoring pull request from unknown repository, discovery is disabled ${logDetails}`
+ );
+ return;
+ }
+
+ const resource =
+ existingResource ??
+ (await discoverResource({
+ dataSource,
+ resourcePayload: { name: repository.full_name, externalId: String(repository.id) },
+ trigger: SecretScanningScanTrigger.PullRequest
+ }));
+
+ if (!resource) return;
+
+ if (expectedResourceId && expectedResourceId !== resource.id) {
+ logger.warn(
+ `secretScanningV2PullRequestEvent: GitHub - ignoring re-run, the scan belongs to another resource ${logDetails} [expectedResourceId=${expectedResourceId}] [resourceId=${resource.id}]`
+ );
+ return;
+ }
+
+ const scanId = crypto.nativeCrypto.randomUUID();
+ const { SITE_URL } = getConfig();
+ const orgId = dataSource.connection?.orgId;
+
+ let checkRunId: number;
+ try {
+ checkRunId = await createPullRequestCheckRun({
+ installationId: String(installationId),
+ repositoryFullName: repository.full_name,
+ headSha: pullRequest.headSha,
+ scanId,
+ detailsUrl:
+ SITE_URL && orgId
+ ? `${SITE_URL}/organizations/${orgId}/secret-scanning/findings?resourceId=${resource.id}`
+ : undefined
+ });
+ } catch (error) {
+ logger.warn(
+ error,
+ `secretScanningV2PullRequestEvent: GitHub - could not create check run, skipping scan ${logDetails}`
+ );
+ return;
+ }
+
+ const payload: TGitHubPullRequestScanPayload = {
+ installationId: String(installationId),
+ repository: { id: repository.id, full_name: repository.full_name },
+ pullRequest,
+ checkRunId
+ };
+
+ await queueReportedDiffScan({
+ scanId,
+ dataSourceId: dataSource.id,
+ dataSourceType: SecretScanningDataSource.GitHub,
+ resourceId: resource.id,
+ trigger: SecretScanningScanTrigger.PullRequest,
+ metadata: getPullRequestScanMetadata(payload),
+ payload
+ });
+ };
+
+ // A re-run carries no pull request for forks, so the pull request comes from the scan the check run was created for.
+ const rerunPullRequestScan = async ({
+ installationId,
+ repository,
+ externalId,
+ logDetails
+ }: {
+ installationId: number;
+ repository: Pick<Repository, "id" | "full_name">;
+ externalId: string | null;
+ logDetails: string;
+ }) => {
+ const scanId = z.string().uuid().safeParse(externalId);
+
+ if (!scanId.success) {
+ logger.warn(`secretScanningV2CheckRunEvent: GitHub - check run has no scan ID ${logDetails}`);
+ return;
+ }
+
+ const previousScan = await secretScanningV2DAL.scans.findById(scanId.data);
+ const metadata = GitHubPullRequestScanMetadataSchema.safeParse(previousScan?.metadata);
+
+ if (!previousScan || previousScan.trigger !== SecretScanningScanTrigger.PullRequest || !metadata.success) {
+ logger.info(
+ `secretScanningV2CheckRunEvent: GitHub - ignoring re-run, the pull request scan no longer exists ${logDetails} [scanId=${scanId.data}]`
+ );
+ return;
+ }
+
+ await startPullRequestScan({
+ installationId,
+ repository,
+ pullRequest: {
+ number: metadata.data.pullRequestNumber,
+ baseSha: metadata.data.baseSha,
+ headSha: metadata.data.headSha
+ },
+ expectedResourceId: previousScan.resourceId
+ });
+ };
+
+ // "Re-run all checks" names only the suite, so the scan comes from the newest check run of ours in it.
+ const rerunCheckSuite = async ({
+ installationId,
+ repository,
+ checkSuiteId
+ }: {
+ installationId: number;
+ repository: Pick<Repository, "id" | "full_name">;
+ checkSuiteId: number;
+ }) => {
+ const logDetails = `[installationId=${installationId}] [repository=${repository.full_name}] [checkSuiteId=${checkSuiteId}]`;
+
+ let externalId: string | null;
+ try {
+ externalId = await getLatestPullRequestCheckRunExternalId({
+ installationId: String(installationId),
+ repositoryFullName: repository.full_name,
+ checkSuiteId
+ });
+ } catch (error) {
+ logger.warn(
+ error,
+ `secretScanningV2CheckSuiteEvent: GitHub - could not list the suite's check runs ${logDetails}`
+ );
+ return;
+ }
+
+ if (!externalId) {
+ logger.info(
+ `secretScanningV2CheckSuiteEvent: GitHub - ignoring re-run, the suite has no pull request check ${logDetails}`
+ );
+ return;
+ }
+
+ await rerunPullRequestScan({ installationId, repository, externalId, logDetails });
+ };
+
+ // GitHub shows the skip buttons to anyone with write access to the repository, so the scan the check run names is
+ // confirmed to belong to the installation and repository the event came from before any finding is changed. The
+ // findings are then triaged as Infisical's own triage would, and the check is run again, which passes once every
+ // finding in it is skipped.
+ const skipPullRequestFindings = async ({
+ installationId,
+ repository,
+ checkRunId,
+ externalId,
+ action,
+ sender
+ }: {
+ installationId: number;
+ repository: Pick<Repository, "id" | "full_name">;
+ checkRunId: number;
+ externalId: string | null;
+ action: string;
+ sender: { id: number; login: string };
+ }) => {
+ const logDetails = `[installationId=${installationId}] [repository=${repository.full_name}] [checkRunId=${checkRunId}] [action=${action}] [sender=${sender.login}]`;
+
+ if (!isPullRequestCheckSkipStatus(action)) {
+ logger.warn(`secretScanningV2CheckRunEvent: GitHub - ignoring unknown check run action ${logDetails}`);
+ return;
+ }
+
+ const scanId = z.string().uuid().safeParse(externalId);
+ const previousScan = scanId.success ? await secretScanningV2DAL.scans.findById(scanId.data) : undefined;
+ const metadata = GitHubPullRequestScanMetadataSchema.safeParse(previousScan?.metadata);
+
+ if (!previousScan || previousScan.trigger !== SecretScanningScanTrigger.PullRequest || !metadata.success) {
+ logger.info(
+ `secretScanningV2CheckRunEvent: GitHub - ignoring skip, the pull request scan no longer exists ${logDetails}`
+ );
+ return;
+ }
+
+ const resource = await secretScanningV2DAL.resources.findById(previousScan.resourceId);
+ const dataSource = resource ? await secretScanningV2DAL.dataSources.findById(resource.dataSourceId) : undefined;
+
+ if (
+ !resource ||
+ !dataSource ||
+ dataSource.type !== SecretScanningDataSource.GitHub ||
+ dataSource.externalId !== String(installationId) ||
+ resource.externalId !== String(repository.id)
+ ) {
+ logger.warn(
+ `secretScanningV2CheckRunEvent: GitHub - ignoring skip, the scan does not belong to this repository ${logDetails} [scanId=${previousScan.id}]`
+ );
+ return;
+ }
+
+ const { pullRequestNumber, findingIds = [] } = metadata.data;
+
+ const findings = findingIds.length
+ ? await secretScanningV2DAL.findings.find({ resourceId: resource.id, $in: { id: findingIds } })
+ : [];
+ const findingsToSkip = findings.filter((finding) => !isPullRequestCheckSkipStatus(finding.status));
+
+ if (findingsToSkip.length) {
+ const triageComment = `${
+ action === SecretScanningFindingStatus.FalsePositive ? "Marked as a false positive" : "Ignored"
+ } from GitHub by @${sender.login} on pull request ${repository.full_name}#${pullRequestNumber}.`;
+ const now = new Date();
+
+ await secretScanningV2DAL.findings.update(
+ { $in: { id: findingsToSkip.map((finding) => finding.id) } },
+ { status: action, triageComment, triagedAt: now, triagedByUserId: null, resolvedAt: null }
+ );
+
+ await Promise.all(
+ findingsToSkip.map((finding) =>
+ auditLogService.createAuditLog({
+ projectId: dataSource.projectId,
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ event: {
+ type: EventType.SECRET_SCANNING_FINDING_UPDATE,
+ metadata: { findingId: finding.id, status: action, triageComment }
+ }
+ })
+ )
+ );
+
+ logger.info(
+ `secretScanningV2CheckRunEvent: GitHub - skipped pull request findings ${logDetails} [scanId=${previousScan.id}] [findings=${findingsToSkip.length}]`
+ );
+ }
+
+ await startPullRequestScan({
+ installationId,
+ repository,
+ pullRequest: {
+ number: pullRequestNumber,
+ baseSha: metadata.data.baseSha,
+ headSha: metadata.data.headSha
+ },
+ expectedResourceId: resource.id
+ });
+ };
+
+ const { installationId, repository } = event;
+
+ switch (event.event) {
+ case GitHubPullRequestEvent.PullRequest:
+ return startPullRequestScan({ installationId, repository, pullRequest: event.pullRequest });
+ case GitHubPullRequestEvent.CheckRunRerequested:
+ return rerunPullRequestScan({
+ installationId,
+ repository,
+ externalId: event.externalId,
+ logDetails: `[installationId=${installationId}] [repository=${repository.full_name}] [checkRunId=${event.checkRunId}]`
+ });
+ case GitHubPullRequestEvent.CheckSuiteRerequested:
+ return rerunCheckSuite({ installationId, repository, checkSuiteId: event.checkSuiteId });
+ case GitHubPullRequestEvent.CheckRunRequestedAction:
+ return skipPullRequestFindings({
+ installationId,
+ repository,
+ checkRunId: event.checkRunId,
+ externalId: event.externalId,
+ action: event.action,
+ sender: event.sender
+ });
+ default:
+ logger.error(
+ `secretScanningV2PullRequestEvent: GitHub - unhandled event [event=${(event as { event: string }).event}]`
+ );
+ }
+};
diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-service.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-service.ts
index ff7f9d91c7..c77b51cc1b 100644
--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-service.ts
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-service.ts
@@ -75,7 +75,7 @@ export const githubSecretScanningService = (
});
};
- // The pull request events below only enqueue; github-secret-scanning-event-processor.ts processes them in the
+ // The pull request events below only enqueue; processGitHubPullRequestEvent processes them in the
// secret scanning worker, so the webhook responds before any GitHub API call or scan is made.
const handlePullRequestEvent = async (
payload: PullRequestOpenedEvent | PullRequestSynchronizeEvent | PullRequestReopenedEvent,
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-factory.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-factory.ts
index ccb0da4687..40e664d017 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-factory.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-factory.ts
@@ -1,16 +1,13 @@
import { BitbucketSecretScanningFactory } from "@app/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory";
-import { GitHubSecretScanningEventProcessor } from "@app/ee/services/secret-scanning-v2/github/github-secret-scanning-event-processor";
import { GitHubSecretScanningFactory } from "@app/ee/services/secret-scanning-v2/github/github-secret-scanning-factory";
import { GitLabSecretScanningFactory } from "@app/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory";
import { SecretScanningDataSource } from "./secret-scanning-v2-enums";
import {
- TQueueSecretScanningDataSourceEvent,
TQueueSecretScanningResourceDiffScan,
TSecretScanningDataSourceCredentials,
TSecretScanningDataSourceInput,
TSecretScanningDataSourceWithConnection,
- TSecretScanningEventProcessor,
TSecretScanningFactory
} from "./secret-scanning-v2-types";
@@ -26,12 +23,3 @@ export const SECRET_SCANNING_FACTORY_MAP: Record<SecretScanningDataSource, TSecr
[SecretScanningDataSource.Bitbucket]: BitbucketSecretScanningFactory as TSecretScanningFactoryImplementation,
[SecretScanningDataSource.GitLab]: GitLabSecretScanningFactory as TSecretScanningFactoryImplementation
};
-
-// Only providers that receive webhook events beyond pushes have an event processor.
-export const SECRET_SCANNING_EVENT_PROCESSOR_MAP: {
- [K in TQueueSecretScanningDataSourceEvent["dataSourceType"]]: TSecretScanningEventProcessor<
- Extract<TQueueSecretScanningDataSourceEvent, { dataSourceType: K }>["event"]
- >;
-} = {
- [SecretScanningDataSource.GitHub]: GitHubSecretScanningEventProcessor
-};
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 e6cc9c807c..ca7f9d0232 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
@@ -46,8 +46,9 @@ import {
SecretScanningScanTrigger,
SecretScanningScanType
} from "./secret-scanning-v2-enums";
-import { SECRET_SCANNING_EVENT_PROCESSOR_MAP, SECRET_SCANNING_FACTORY_MAP } from "./secret-scanning-v2-factory";
+import { SECRET_SCANNING_FACTORY_MAP } from "./secret-scanning-v2-factory";
import {
+ TFindingsPayload,
TQueueSecretScanningDataSourceEvent,
TQueueSecretScanningDataSourceFullScan,
TQueueSecretScanningResourceDiffScan,
@@ -55,7 +56,6 @@ import {
TQueueSecretScanningSendNotification,
TSecretScanningDataSourceWithConnection,
TSecretScanningDiscoverResource,
- TSecretScanningEventProcessorParams,
TSecretScanningFinding,
TSecretScanningQueueReportedDiffScan
} from "./secret-scanning-v2-types";
@@ -1322,15 +1322,21 @@ export const secretScanningV2QueueServiceFactory = ({
}
};
- const eventProcessorParams: TSecretScanningEventProcessorParams = {
- secretScanningV2DAL,
- auditLogService,
- discoverResource,
- queueReportedDiffScan
- };
-
const processDataSourceEvent = async ({ dataSourceType, event }: TQueueSecretScanningDataSourceEvent) => {
- await SECRET_SCANNING_EVENT_PROCESSOR_MAP[dataSourceType](eventProcessorParams).processEvent(event);
+ const factory = SECRET_SCANNING_FACTORY_MAP[dataSourceType]({ kmsService, appConnectionDAL });
+
+ if (!factory.processEvent) {
+ logger.error(`secretScanningV2Queue: Data source has no event processing [dataSourceType=${dataSourceType}]`);
+ return;
+ }
+
+ await factory.processEvent({
+ event,
+ secretScanningV2DAL,
+ auditLogService,
+ discoverResource,
+ queueReportedDiffScan
+ });
};
queueService.start(QueueName.SecretScanningV2, async (job) => {
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-types.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-types.ts
index 780bf14bde..df975021ee 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-types.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-types.ts
@@ -322,7 +322,8 @@ export type TSecretScanningFactory<
T extends TSecretScanningDataSourceWithConnection,
P extends TQueueSecretScanningResourceDiffScan["payload"],
I extends TSecretScanningDataSourceInput,
- C extends TSecretScanningDataSourceCredentials | undefined = undefined
+ C extends TSecretScanningDataSourceCredentials | undefined = undefined,
+ E extends TQueueSecretScanningDataSourceEvent["event"] = TQueueSecretScanningDataSourceEvent["event"]
> = (params: TSecretScanningFactoryParams) => {
listRawResources: TSecretScanningFactoryListRawResources<T>;
getFullScanPath: TSecretScanningFactoryGetFullScanPath<T>;
@@ -336,6 +337,8 @@ export type TSecretScanningFactory<
getDiffScanFindingsPayload: TSecretScanningFactoryGetDiffScanFindingsPayload<T, P>;
getDiffScanReport?: TSecretScanningFactoryGetDiffScanReport<P>;
getScanReport?: TSecretScanningFactoryGetScanReport;
+ // Processes webhook events beyond pushes, in the worker; only providers that receive them implement it.
+ processEvent?: TSecretScanningFactoryProcessEvent<E>;
};
export type TSecretScanningDiscoverResource = (params: {
@@ -354,18 +357,13 @@ export type TSecretScanningQueueReportedDiffScan = (
}
) => Promise<void>;
-export type TSecretScanningEventProcessorParams = {
+export type TSecretScanningFactoryProcessEvent<E extends TQueueSecretScanningDataSourceEvent["event"]> = (params: {
+ event: E;
secretScanningV2DAL: TSecretScanningV2DALFactory;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
discoverResource: TSecretScanningDiscoverResource;
queueReportedDiffScan: TSecretScanningQueueReportedDiffScan;
-};
-
-export type TSecretScanningEventProcessor<E extends TQueueSecretScanningDataSourceEvent["event"]> = (
- params: TSecretScanningEventProcessorParams
-) => {
- processEvent: (event: E) => Promise<void>;
-};
+}) => Promise<void>;
export type TFindingsPayload = Pick<TSecretScanningFindingsInsert, "details" | "fingerprint" | "severity" | "rule">[];
export type TGetFindingsPayload = Promise<TFindingsPayload>;