Skip to content

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

make generic path more generic

Matheus Nogueira04fd441d62cb
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index 9a9bbf76db..b95a685767 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. The `pull_request`, `check_run.rerequested` and `check_suite.rerequested` webhook handlers in `github-secret-scanning-service.ts` only enqueue a reduced `TQueueGitHubPullRequestEvent` on the `secret-scanning-v2` queue (job ID from the GitHub delivery ID, 3 attempts); `github-secret-scanning-pull-request-events.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'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).
**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/bitbucket/bitbucket-secret-scanning-factory.ts b/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.ts
index 6c434a0233..3c9eaa3823 100644
--- a/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.ts
+++ b/backend/src/ee/services/secret-scanning-v2/bitbucket/bitbucket-secret-scanning-factory.ts
@@ -318,12 +318,14 @@ export const BitbucketSecretScanningFactory = () => {
}
}
- return allFindings.map((finding) => ({
- details: toFindingDetails(finding),
- fingerprint: finding.Fingerprint,
- severity: SecretScanningFindingSeverity.High,
- rule: finding.RuleID
- }));
+ return {
+ findings: allFindings.map((finding) => ({
+ details: toFindingDetails(finding),
+ fingerprint: finding.Fingerprint,
+ severity: SecretScanningFindingSeverity.High,
+ rule: finding.RuleID
+ }))
+ };
};
const setupWebhook: TSecretScanningFactorySetupWebhook<
diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-pull-request-events.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-event-processor.ts
similarity index 89%
rename from backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-pull-request-events.ts
rename to backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-event-processor.ts
index 28dc63c1ce..4da1402116 100644
--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-pull-request-events.ts
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-event-processor.ts
@@ -1,14 +1,13 @@
import { Repository } from "@octokit/webhooks-types";
import { z } from "zod";
-import { TSecretScanningDataSources, TSecretScanningResources, TSecretScanningResourcesInsert } from "@app/db/schemas";
-import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
-import { TSecretScanningV2DALFactory } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-dal";
+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";
@@ -18,34 +17,19 @@ 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";
-type TGitHubPullRequestEventsFactoryDep = {
- secretScanningV2DAL: TSecretScanningV2DALFactory;
- auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
- discoverResource: (params: {
- dataSource: Pick<TSecretScanningDataSources, "id" | "isHistoricalScanEnabled">;
- resourcePayload: Pick<TSecretScanningResourcesInsert, "externalId" | "name">;
- trigger: SecretScanningScanTrigger.PullRequest;
- }) => Promise<TSecretScanningResources | undefined>;
- queuePullRequestScan: (params: {
- scanId: string;
- dataSourceId: string;
- resourceId: string;
- payload: TGitHubPullRequestScanPayload;
- }) => Promise<void>;
-};
-
// Runs in the secret scanning worker, so the webhook only has to enqueue the event.
-export const githubPullRequestEventsFactory = ({
+export const GitHubSecretScanningEventProcessor: TSecretScanningEventProcessor<TQueueGitHubPullRequestEvent> = ({
secretScanningV2DAL,
auditLogService,
discoverResource,
- queuePullRequestScan
-}: TGitHubPullRequestEventsFactoryDep) => {
+ 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
@@ -133,16 +117,21 @@ export const githubPullRequestEventsFactory = ({
return;
}
- await queuePullRequestScan({
+ 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,
- payload: {
- installationId: String(installationId),
- repository: { id: repository.id, full_name: repository.full_name },
- pullRequest,
- checkRunId
- }
+ trigger: SecretScanningScanTrigger.PullRequest,
+ metadata: getPullRequestScanMetadata(payload),
+ payload
});
};
@@ -328,7 +317,7 @@ export const githubPullRequestEventsFactory = ({
});
};
- const processPullRequestEvent = async (job: TQueueGitHubPullRequestEvent) => {
+ const processEvent = async (job: TQueueGitHubPullRequestEvent) => {
const { installationId, repository } = job;
switch (job.event) {
@@ -359,5 +348,5 @@ export const githubPullRequestEventsFactory = ({
}
};
- return { processPullRequestEvent };
+ 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 ef1865e930..011c2e9669 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
@@ -1,15 +1,20 @@
import { join } from "path";
import { ProbotOctokit } from "probot";
-import { SecretScanningDataSource } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
+import {
+ SecretScanningDataSource,
+ SecretScanningScanTrigger
+} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import {
assertProviderRepositorySizeWithinLimit,
cloneRepository
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-fns";
import {
TSecretScanningFactoryGetDiffScanFindingsPayload,
+ TSecretScanningFactoryGetDiffScanReport,
TSecretScanningFactoryGetDiffScanResourcePayload,
TSecretScanningFactoryGetFullScanPath,
+ TSecretScanningFactoryGetScanReport,
TSecretScanningFactoryInitialize,
TSecretScanningFactoryListRawResources,
TSecretScanningFactoryPostInitialization,
@@ -23,11 +28,14 @@ import { BasicRepositoryRegex } from "@app/lib/regex";
import { listGitHubRadarRepositories, TGitHubRadarConnection } from "@app/services/app-connection/github-radar";
import {
+ createPullRequestScanReport,
getGitHubRadarInstallationOctokit,
+ getPullRequestScanMetadata,
isGitHubPullRequestScanPayload,
scanGitHubCommitsAndGetFindings,
scanGitHubPullRequest
} from "./github-secret-scanning-fns";
+import { GitHubPullRequestScanMetadataSchema } from "./github-secret-scanning-schemas";
import {
TGitHubDataSourceInput,
TGitHubDataSourceWithConnection,
@@ -151,13 +159,12 @@ export const GitHubSecretScanningFactory = () => {
TQueueGitHubResourceDiffScan["payload"]
> = async ({ dataSource, payload, resourceName, configPath }) => {
if (isGitHubPullRequestScanPayload(payload)) {
- const { findings } = await scanGitHubPullRequest({ payload, resourceName, configPath });
- return findings;
+ return scanGitHubPullRequest({ payload, resourceName, configPath });
}
const { commits, repository } = payload;
- return scanGitHubCommitsAndGetFindings({
+ const findings = await scanGitHubCommitsAndGetFindings({
octokit: getGitHubRadarInstallationOctokit(dataSource.connection.credentials.installationId),
repositoryFullName: repository.full_name,
resourceName,
@@ -170,6 +177,35 @@ export const GitHubSecretScanningFactory = () => {
})),
configPath
});
+
+ return { findings };
+ };
+
+ // Pull request scans report to the check run they were created for; pushes report nowhere.
+ const getDiffScanReport: TSecretScanningFactoryGetDiffScanReport<TQueueGitHubResourceDiffScan["payload"]> = (
+ payload
+ ) => {
+ if (!isGitHubPullRequestScanPayload(payload)) return undefined;
+
+ return createPullRequestScanReport({
+ installationId: payload.installationId,
+ repositoryFullName: payload.repository.full_name,
+ metadata: getPullRequestScanMetadata(payload)
+ });
+ };
+
+ const getScanReport: TSecretScanningFactoryGetScanReport = ({ scan, dataSource, resourceName }) => {
+ if (scan.trigger !== SecretScanningScanTrigger.PullRequest || !dataSource.externalId) return undefined;
+
+ const metadata = GitHubPullRequestScanMetadataSchema.safeParse(scan.metadata);
+ if (!metadata.success) return undefined;
+
+ return createPullRequestScanReport({
+ // A GitHub data source's external ID is its installation ID.
+ installationId: dataSource.externalId,
+ repositoryFullName: resourceName,
+ metadata: metadata.data
+ });
};
return {
@@ -179,6 +215,8 @@ export const GitHubSecretScanningFactory = () => {
getFullScanPath,
getDiffScanResourcePayload,
getDiffScanFindingsPayload,
+ getDiffScanReport,
+ getScanReport,
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 bdf97f91db..48afa231be 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
@@ -12,7 +12,9 @@ import {
import { GitRepositoryScanFindingDetailsSchema } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-schemas";
import {
TFindingsPayload,
- TQueueSecretScanningResourceDiffScan
+ TQueueSecretScanningResourceDiffScan,
+ TSecretScanningDiffScanFindings,
+ 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";
@@ -20,7 +22,7 @@ import { getConfig } from "@app/lib/config/env";
import { chunkArray } from "@app/lib/fn/array";
import { logger } from "@app/lib/logger";
-import { TGitHubPullRequestScanPayload } from "./github-secret-scanning-types";
+import { TGitHubPullRequestScanMetadata, TGitHubPullRequestScanPayload } from "./github-secret-scanning-types";
export const GITHUB_PULL_REQUEST_CHECK_NAME = "Infisical Secret Scanning";
@@ -223,7 +225,7 @@ export const scanGitHubPullRequest = async ({
payload: TGitHubPullRequestScanPayload;
resourceName: string;
configPath?: string;
-}) => {
+}): Promise<TSecretScanningDiffScanFindings> => {
const octokit = getGitHubRadarInstallationOctokit(payload.installationId);
const { commits, totalCommits } = await listPullRequestCommits(octokit, {
@@ -240,7 +242,7 @@ export const scanGitHubPullRequest = async ({
configPath
});
- return { findings, scannedCommitCount: commits.length, totalCommitCount: totalCommits };
+ return { findings, details: { scannedCommitCount: commits.length, totalCommitCount: totalCommits } };
};
export const createPullRequestCheckRun = async ({
@@ -490,3 +492,54 @@ export const tryCompletePullRequestCheckRun = async (
);
}
};
+
+export const getPullRequestScanMetadata = (payload: TGitHubPullRequestScanPayload): TGitHubPullRequestScanMetadata => ({
+ pullRequestNumber: payload.pullRequest.number,
+ baseSha: payload.pullRequest.baseSha,
+ headSha: payload.pullRequest.headSha,
+ checkRunId: payload.checkRunId
+});
+
+// The scan's finding IDs are kept so a skip from the check run can triage exactly the findings it failed on.
+export const createPullRequestScanReport = ({
+ installationId,
+ repositoryFullName,
+ metadata
+}: {
+ installationId: string;
+ repositoryFullName: string;
+ metadata: TGitHubPullRequestScanMetadata;
+}): TSecretScanningScanReport => {
+ const target = { installationId, repositoryFullName, checkRunId: metadata.checkRunId };
+
+ return {
+ start: async () => {
+ try {
+ await startPullRequestCheckRun(target);
+ } catch (error) {
+ logger.warn(
+ error,
+ `secretScanningV2PullRequestScan: GitHub - failed to mark check run in progress [repository=${repositoryFullName}] [checkRunId=${metadata.checkRunId}]`
+ );
+ }
+ },
+ getCompletedScanMetadata: ({ findings }) =>
+ ({ ...metadata, findingIds: findings.map((finding) => finding.id) }) satisfies TGitHubPullRequestScanMetadata,
+ // Judged on every finding in the pull request's commits, including ones an earlier push scan saved first.
+ complete: ({ findings, details }) =>
+ tryCompletePullRequestCheckRun({
+ ...target,
+ result: getPullRequestScanCheckRunResult({
+ findings,
+ scannedCommitCount: details?.scannedCommitCount ?? 0,
+ totalCommitCount: details?.totalCommitCount ?? 0
+ })
+ }),
+ fail: ({ reason, isTimedOut }) =>
+ tryCompletePullRequestCheckRun({
+ ...target,
+ result: getPullRequestScanFailedCheckRunResult(reason, isTimedOut ? "timed_out" : "failure")
+ }),
+ cancel: () => tryCompletePullRequestCheckRun({ ...target, result: PULL_REQUEST_SCAN_CANCELLED_CHECK_RUN_RESULT })
+ };
+};
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 ea04e18b88..ff7f9d91c7 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
@@ -15,14 +15,15 @@ import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { GitHubPullRequestEvent } from "./github-secret-scanning-enums";
+import { TQueueGitHubPullRequestEvent } from "./github-secret-scanning-types";
export const githubSecretScanningService = (
secretScanningV2DAL: TSecretScanningV2DALFactory,
- secretScanningV2Queue: Pick<
- TSecretScanningV2QueueServiceFactory,
- "handleResourcePushEvent" | "queueGitHubPullRequestEvent"
- >
+ secretScanningV2Queue: Pick<TSecretScanningV2QueueServiceFactory, "handleResourcePushEvent" | "queueDataSourceEvent">
) => {
+ const queuePullRequestEvent = (event: TQueueGitHubPullRequestEvent, deliveryId: string) =>
+ secretScanningV2Queue.queueDataSourceEvent({ dataSourceType: SecretScanningDataSource.GitHub, event }, deliveryId);
+
const handleInstallationDeletedEvent = async (installationId: number) => {
const dataSource = await secretScanningV2DAL.dataSources.findOne({
externalId: String(installationId),
@@ -74,7 +75,7 @@ export const githubSecretScanningService = (
});
};
- // The pull request events below only enqueue; github-secret-scanning-pull-request-events.ts processes them in the
+ // The pull request events below only enqueue; github-secret-scanning-event-processor.ts 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,
@@ -89,7 +90,7 @@ export const githubSecretScanningService = (
return;
}
- await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ await queuePullRequestEvent(
{
event: GitHubPullRequestEvent.PullRequest,
installationId: installation.id,
@@ -116,7 +117,7 @@ export const githubSecretScanningService = (
if (String(checkRun.app.id) !== getConfig().INF_APP_CONNECTION_GITHUB_RADAR_APP_ID) return;
- await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ await queuePullRequestEvent(
{
event: GitHubPullRequestEvent.CheckRunRerequested,
installationId: installation.id,
@@ -140,7 +141,7 @@ export const githubSecretScanningService = (
if (String(checkSuite.app.id) !== getConfig().INF_APP_CONNECTION_GITHUB_RADAR_APP_ID) return;
- await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ await queuePullRequestEvent(
{
event: GitHubPullRequestEvent.CheckSuiteRerequested,
installationId: installation.id,
@@ -163,7 +164,7 @@ export const githubSecretScanningService = (
if (String(checkRun.app.id) !== getConfig().INF_APP_CONNECTION_GITHUB_RADAR_APP_ID) return;
- await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ await queuePullRequestEvent(
{
event: GitHubPullRequestEvent.CheckRunRequestedAction,
installationId: installation.id,
diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-types.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-types.ts
index c05806de9a..2dc905e016 100644
--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-types.ts
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-types.ts
@@ -47,6 +47,11 @@ export type TQueueGitHubResourceDiffScan = {
scanId: string;
};
+export type TGitHubDiffScanDetails = {
+ scannedCommitCount: number;
+ totalCommitCount: number;
+};
+
// Webhook events are reduced to what processing them needs, so the queue never holds GitHub's full payload.
export type TQueueGitHubPullRequestEvent = {
installationId: number;
@@ -63,3 +68,8 @@ export type TQueueGitHubPullRequestEvent = {
sender: { id: number; login: string };
}
);
+
+export type TQueueGitHubDataSourceEvent = {
+ dataSourceType: SecretScanningDataSource.GitHub;
+ event: TQueueGitHubPullRequestEvent;
+};
diff --git a/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts b/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts
index d07947c221..6e9ff27204 100644
--- a/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts
+++ b/backend/src/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-factory.ts
@@ -439,12 +439,14 @@ export const GitLabSecretScanningFactory = ({ appConnectionDAL, kmsService }: TS
}
}
- return allFindings.map((finding) => ({
- details: toFindingDetails(finding),
- fingerprint: finding.Fingerprint,
- severity: SecretScanningFindingSeverity.High,
- rule: finding.RuleID
- }));
+ return {
+ findings: allFindings.map((finding) => ({
+ details: toFindingDetails(finding),
+ fingerprint: finding.Fingerprint,
+ severity: SecretScanningFindingSeverity.High,
+ rule: finding.RuleID
+ }))
+ };
};
const validateConfigUpdate: TSecretScanningFactoryValidateConfigUpdate<
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 40e664d017..ccb0da4687 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,13 +1,16 @@
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";
@@ -23,3 +26,12 @@ 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 d2e5d5dc42..e6cc9c807c 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
@@ -7,23 +7,6 @@ import {
TSecretScanningResourcesInsert
} from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
-import {
- GitHubPullRequestScanMetadataSchema,
- TGitHubPullRequestScanMetadata,
- TGitHubPullRequestScanPayload,
- TQueueGitHubPullRequestEvent
-} from "@app/ee/services/secret-scanning-v2/github";
-import {
- getPullRequestScanCheckRunResult,
- getPullRequestScanFailedCheckRunResult,
- isGitHubPullRequestScanPayload,
- PULL_REQUEST_SCAN_CANCELLED_CHECK_RUN_RESULT,
- scanGitHubPullRequest,
- startPullRequestCheckRun,
- TPullRequestCheckRunResult,
- tryCompletePullRequestCheckRun
-} from "@app/ee/services/secret-scanning-v2/github/github-secret-scanning-fns";
-import { githubPullRequestEventsFactory } from "@app/ee/services/secret-scanning-v2/github/github-secret-scanning-pull-request-events";
import {
assertClonedRepositoryWithinSizeLimit,
parseScanErrorMessage,
@@ -63,15 +46,18 @@ import {
SecretScanningScanTrigger,
SecretScanningScanType
} from "./secret-scanning-v2-enums";
-import { SECRET_SCANNING_FACTORY_MAP } from "./secret-scanning-v2-factory";
+import { SECRET_SCANNING_EVENT_PROCESSOR_MAP, SECRET_SCANNING_FACTORY_MAP } from "./secret-scanning-v2-factory";
import {
- TFindingsPayload,
+ TQueueSecretScanningDataSourceEvent,
TQueueSecretScanningDataSourceFullScan,
TQueueSecretScanningResourceDiffScan,
TQueueSecretScanningResourceDiffScanPayload,
TQueueSecretScanningSendNotification,
TSecretScanningDataSourceWithConnection,
- TSecretScanningFinding
+ TSecretScanningDiscoverResource,
+ TSecretScanningEventProcessorParams,
+ TSecretScanningFinding,
+ TSecretScanningQueueReportedDiffScan
} from "./secret-scanning-v2-types";
type TSecretRotationV2QueueServiceFactoryDep = {
@@ -106,8 +92,8 @@ const FULL_SCAN_ATTEMPTS = 3;
const FULL_SCAN_MAX_STALLED_COUNT = 2;
const FULL_SCAN_RETRY_DELAY = ms("1m");
-const GITHUB_PULL_REQUEST_EVENT_ATTEMPTS = 3;
-const GITHUB_PULL_REQUEST_EVENT_RETRY_DELAY = ms("30s");
+const DATA_SOURCE_EVENT_ATTEMPTS = 3;
+const DATA_SOURCE_EVENT_RETRY_DELAY = ms("30s");
const DUPLICATE_FULL_SCAN_STATUS_MESSAGE =
"Another scan of this resource was already in progress, so this scan was not started.";
@@ -774,25 +760,19 @@ export const secretScanningV2QueueServiceFactory = ({
attemptsMade: number;
opts: { attempts?: number };
}) => {
- const { payload, dataSourceId, resourceId, scanId } = job.data;
+ const { payload, dataSourceId, dataSourceType, resourceId, scanId } = job.data;
const retryCount = job.attemptsMade + 1;
const retryLimit = job.opts.attempts || 1;
const startedAt = Date.now();
const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
- const pullRequestScan = isGitHubPullRequestScanPayload(payload) ? payload : undefined;
+ const factory = SECRET_SCANNING_FACTORY_MAP[dataSourceType]({
+ kmsService,
+ appConnectionDAL
+ });
- const reportPullRequestCheck = async (result: TPullRequestCheckRunResult) => {
- if (!pullRequestScan) return;
-
- await tryCompletePullRequestCheckRun({
- installationId: pullRequestScan.installationId,
- repositoryFullName: pullRequestScan.repository.full_name,
- checkRunId: pullRequestScan.checkRunId,
- result
- });
- };
+ 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();
@@ -801,15 +781,10 @@ export const secretScanningV2QueueServiceFactory = ({
if (!dataSource || !resource) {
logger.info(`secretScanningV2Queue: Diff Scan aborted, scan no longer exists ${logDetails}`);
- await reportPullRequestCheck(PULL_REQUEST_SCAN_CANCELLED_CHECK_RUN_RESULT);
+ await report?.cancel();
return;
}
- const factory = SECRET_SCANNING_FACTORY_MAP[dataSource.type as SecretScanningDataSource]({
- kmsService,
- appConnectionDAL
- });
-
const tempFolder = await createTempFolder();
logger.info(
@@ -826,17 +801,7 @@ export const secretScanningV2QueueServiceFactory = ({
return;
}
- if (pullRequestScan) {
- try {
- await startPullRequestCheckRun({
- installationId: pullRequestScan.installationId,
- repositoryFullName: pullRequestScan.repository.full_name,
- checkRunId: pullRequestScan.checkRunId
- });
- } catch (error) {
- logger.warn(error, `secretScanningV2Queue: Failed to mark pull request check run in progress ${logDetails}`);
- }
- }
+ await report?.start();
let connection: TAppConnection | null = null;
if (dataSource.connection) connection = await decryptAppConnection(dataSource.connection, kmsService);
@@ -852,29 +817,15 @@ export const secretScanningV2QueueServiceFactory = ({
await writeTextToFile(configPath, config.content);
}
- let findingsPayload: TFindingsPayload;
- let pullRequestCommitCounts: { scannedCommitCount: number; totalCommitCount: number } | undefined;
-
- if (pullRequestScan) {
- const { findings, scannedCommitCount, totalCommitCount } = await scanGitHubPullRequest({
- payload: pullRequestScan,
- resourceName: resource.name,
- configPath
- });
-
- findingsPayload = findings;
- pullRequestCommitCounts = { scannedCommitCount, totalCommitCount };
- } else {
- findingsPayload = await factory.getDiffScanFindingsPayload({
- dataSource: {
- ...dataSource,
- connection
- } as TSecretScanningDataSourceWithConnection,
- resourceName: resource.name,
- payload,
- configPath
- });
- }
+ const { findings: findingsPayload, details } = await factory.getDiffScanFindingsPayload({
+ dataSource: {
+ ...dataSource,
+ connection
+ } as TSecretScanningDataSourceWithConnection,
+ resourceName: resource.name,
+ payload,
+ configPath
+ });
const { allFindings, closedOutByThisRun } = await secretScanningV2DAL.findings.transaction(async (tx) => {
let findings: TSecretScanningFindings[] = [];
@@ -898,17 +849,7 @@ export const secretScanningV2QueueServiceFactory = ({
{
status: SecretScanningScanStatus.Completed,
completedAt: new Date(),
- ...(pullRequestScan
- ? {
- metadata: {
- pullRequestNumber: pullRequestScan.pullRequest.number,
- baseSha: pullRequestScan.pullRequest.baseSha,
- headSha: pullRequestScan.pullRequest.headSha,
- checkRunId: pullRequestScan.checkRunId,
- findingIds: findings.map((finding) => finding.id)
- } satisfies TGitHubPullRequestScanMetadata
- }
- : {})
+ ...(report ? { metadata: report.getCompletedScanMetadata({ findings, details }) } : {})
},
tx
);
@@ -923,13 +864,8 @@ export const secretScanningV2QueueServiceFactory = ({
return;
}
- // Judged on every finding in the pull request's commits, including ones an earlier push scan saved first; the
- // upsert returns those rows with the status they were triaged to, so skipped findings don't fail the check.
- if (pullRequestCommitCounts) {
- await reportPullRequestCheck(
- getPullRequestScanCheckRunResult({ findings: allFindings, ...pullRequestCommitCounts })
- );
- }
+ // The upsert returns findings an earlier scan saved first too, with the status each was triaged to.
+ await report?.complete({ findings: allFindings, details });
const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
@@ -989,7 +925,7 @@ export const secretScanningV2QueueServiceFactory = ({
} catch (error) {
if (!(await secretScanningV2DAL.scans.findById(scanId, secretScanningV2DAL.primaryNode()))) {
logger.info(`secretScanningV2Queue: Diff Scan aborted, scan was deleted while running ${logDetails}`);
- await reportPullRequestCheck(PULL_REQUEST_SCAN_CANCELLED_CHECK_RUN_RESULT);
+ await report?.cancel();
return;
}
@@ -999,7 +935,7 @@ export const secretScanningV2QueueServiceFactory = ({
const failed = await markScanAsFailed({ scanId, statusMessage: errorMessage });
if (failed) {
- await reportPullRequestCheck(getPullRequestScanFailedCheckRunResult(errorMessage));
+ await report?.fail({ reason: errorMessage });
await queueService.queue(
QueueName.SecretScanningV2,
@@ -1172,19 +1108,9 @@ export const secretScanningV2QueueServiceFactory = ({
if (!dataSource) return;
- if (scan.trigger === SecretScanningScanTrigger.PullRequest && dataSource.externalId) {
- const metadata = GitHubPullRequestScanMetadataSchema.safeParse(scan.metadata);
-
- if (metadata.success) {
- await tryCompletePullRequestCheckRun({
- // A GitHub data source's external ID is its installation ID.
- installationId: dataSource.externalId,
- repositoryFullName: scan.resourceName,
- checkRunId: metadata.data.checkRunId,
- result: getPullRequestScanFailedCheckRunResult(STUCK_SCAN_STATUS_MESSAGE, "timed_out")
- });
- }
- }
+ 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 });
await queueService.queue(
QueueName.SecretScanningV2,
@@ -1325,15 +1251,7 @@ export const secretScanningV2QueueServiceFactory = ({
};
// Adds a resource discovered from a webhook, and scans its history when the data source scans new resources' history.
- const discoverResource = async ({
- dataSource,
- resourcePayload,
- trigger
- }: {
- dataSource: Pick<TSecretScanningDataSources, "id" | "isHistoricalScanEnabled">;
- resourcePayload: Pick<TSecretScanningResourcesInsert, "externalId" | "name">;
- trigger: SecretScanningScanTrigger.Push | SecretScanningScanTrigger.PullRequest;
- }) => {
+ const discoverResource: TSecretScanningDiscoverResource = async ({ dataSource, resourcePayload, trigger }) => {
if (dataSource.isHistoricalScanEnabled) {
return queueResourceFullScan({ dataSourceId: dataSource.id, resourcePayload, trigger });
}
@@ -1347,36 +1265,29 @@ export const secretScanningV2QueueServiceFactory = ({
};
/**
- * The check run is created first, so the scan is inserted with the ID the check run already carries and with the
- * check run's ID in its metadata. Nothing redelivers a realtime scan whose job was never submitted, so if either
- * step fails the scan is failed and the check run closed here, rather than left queued.
+ * For a scan reported back to where it was requested: the report is created first, so the scan is inserted with the
+ * ID the report already carries. Nothing redelivers a realtime scan whose job was never submitted, so if either step
+ * fails the scan is failed and its report closed here, rather than left queued.
*/
- const queuePullRequestScan = async ({
+ const queueReportedDiffScan: TSecretScanningQueueReportedDiffScan = async ({
scanId,
dataSourceId,
+ dataSourceType,
resourceId,
+ trigger,
+ metadata,
payload
- }: {
- scanId: string;
- dataSourceId: string;
- resourceId: string;
- payload: TGitHubPullRequestScanPayload;
}) => {
- const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [checkRunId=${payload.checkRunId}]`;
+ const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [trigger=${trigger}]`;
try {
await secretScanningV2DAL.scans.create({
- // @ts-expect-error id is generated before the insert because the check run was created with it
+ // @ts-expect-error id is generated before the insert because the report was created with it
id: scanId,
resourceId,
type: SecretScanningScanType.Realtime,
- trigger: SecretScanningScanTrigger.PullRequest,
- metadata: {
- pullRequestNumber: payload.pullRequest.number,
- baseSha: payload.pullRequest.baseSha,
- headSha: payload.pullRequest.headSha,
- checkRunId: payload.checkRunId
- } satisfies TGitHubPullRequestScanMetadata
+ trigger,
+ metadata
});
await queueService.queue(
@@ -1385,41 +1296,42 @@ export const secretScanningV2QueueServiceFactory = ({
{
payload,
dataSourceId,
- dataSourceType: SecretScanningDataSource.GitHub,
+ dataSourceType,
scanId,
resourceId
- },
+ } as TQueueSecretScanningResourceDiffScan,
{
jobId: scanId,
removeOnFail: true
}
);
} catch (error) {
- logger.error(error, `secretScanningV2Queue: Failed to queue pull request scan ${logDetails}`);
+ logger.error(error, `secretScanningV2Queue: Failed to queue reported diff scan ${logDetails}`);
const statusMessage = "The scan could not be started.";
try {
await markScanAsFailed({ scanId, statusMessage });
} catch (markError) {
- logger.error(markError, `secretScanningV2Queue: Failed to mark pull request scan as failed ${logDetails}`);
+ logger.error(markError, `secretScanningV2Queue: Failed to mark reported diff scan as failed ${logDetails}`);
}
- await tryCompletePullRequestCheckRun({
- installationId: payload.installationId,
- repositoryFullName: payload.repository.full_name,
- checkRunId: payload.checkRunId,
- result: getPullRequestScanFailedCheckRunResult(statusMessage)
- });
+ await SECRET_SCANNING_FACTORY_MAP[dataSourceType]({ kmsService, appConnectionDAL })
+ .getDiffScanReport?.(payload)
+ ?.fail({ reason: statusMessage });
}
};
- const githubPullRequestEvents = githubPullRequestEventsFactory({
+ const eventProcessorParams: TSecretScanningEventProcessorParams = {
secretScanningV2DAL,
auditLogService,
discoverResource,
- queuePullRequestScan
- });
+ queueReportedDiffScan
+ };
+
+ const processDataSourceEvent = async ({ dataSourceType, event }: TQueueSecretScanningDataSourceEvent) => {
+ await SECRET_SCANNING_EVENT_PROCESSOR_MAP[dataSourceType](eventProcessorParams).processEvent(event);
+ };
queueService.start(QueueName.SecretScanningV2, async (job) => {
// We are keeping this for now because once deployed, the queue might still have
@@ -1430,18 +1342,18 @@ export const secretScanningV2QueueServiceFactory = ({
await handleDiffScan(job as Parameters<typeof handleDiffScan>[0]);
} else if (job.name === QueueJobs.SecretScanningV2SendNotification) {
await handleSendNotification(job as Parameters<typeof handleSendNotification>[0]);
- } else if (job.name === QueueJobs.SecretScanningV2GitHubPullRequestEvent) {
- await githubPullRequestEvents.processPullRequestEvent(job.data as TQueueGitHubPullRequestEvent);
+ } else if (job.name === QueueJobs.SecretScanningV2DataSourceEvent) {
+ await processDataSourceEvent(job.data as TQueueSecretScanningDataSourceEvent);
}
});
- // Keyed by GitHub's delivery ID, so a redelivered webhook isn't processed twice while the first is pending. Work
- // before the check run is created is safe to repeat, and nothing after it throws, so a failed attempt is retried.
- const queueGitHubPullRequestEvent = async (payload: TQueueGitHubPullRequestEvent, deliveryId: string) => {
- await queueService.queue(QueueName.SecretScanningV2, QueueJobs.SecretScanningV2GitHubPullRequestEvent, payload, {
- jobId: `secret-scanning-github-pull-request-event-${deliveryId}`,
- attempts: GITHUB_PULL_REQUEST_EVENT_ATTEMPTS,
- backoff: { type: "fixed", delay: GITHUB_PULL_REQUEST_EVENT_RETRY_DELAY }
+ // Keyed by the provider's delivery ID, so a redelivered webhook isn't processed twice while the first is pending.
+ // Processors must be safe to retry up to the point they create something at the provider.
+ const queueDataSourceEvent = async (payload: TQueueSecretScanningDataSourceEvent, deliveryId: string) => {
+ await queueService.queue(QueueName.SecretScanningV2, QueueJobs.SecretScanningV2DataSourceEvent, payload, {
+ jobId: `secret-scanning-data-source-event-${payload.dataSourceType}-${deliveryId}`,
+ attempts: DATA_SOURCE_EVENT_ATTEMPTS,
+ backoff: { type: "fixed", delay: DATA_SOURCE_EVENT_RETRY_DELAY }
});
};
@@ -1513,7 +1425,7 @@ export const secretScanningV2QueueServiceFactory = ({
return {
queueDataSourceFullScan,
queueResourceDiffScan,
- queueGitHubPullRequestEvent,
+ queueDataSourceEvent,
handleResourcePushEvent
};
};
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts
index 6555814959..eaa9acd0e5 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts
@@ -86,7 +86,7 @@ export type TSecretScanningV2ServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
secretScanningV2Queue: Pick<
TSecretScanningV2QueueServiceFactory,
- "queueDataSourceFullScan" | "queueResourceDiffScan" | "queueGitHubPullRequestEvent" | "handleResourcePushEvent"
+ "queueDataSourceFullScan" | "queueResourceDiffScan" | "queueDataSourceEvent" | "handleResourcePushEvent"
>;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "acquireLock">;
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 aae4669645..780bf14bde 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
@@ -1,9 +1,12 @@
import {
TSecretScanningDataSources,
+ TSecretScanningFindings,
TSecretScanningFindingsInsert,
TSecretScanningResources,
+ TSecretScanningResourcesInsert,
TSecretScanningScans
} from "@app/db/schemas";
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import {
TBitbucketDataSource,
TBitbucketDataSourceCredentials,
@@ -18,7 +21,9 @@ import {
TGitHubDataSourceInput,
TGitHubDataSourceListItem,
TGitHubDataSourceWithConnection,
+ TGitHubDiffScanDetails,
TGitHubFinding,
+ TQueueGitHubDataSourceEvent,
TQueueGitHubResourceDiffScan
} from "@app/ee/services/secret-scanning-v2/github";
import {
@@ -34,7 +39,8 @@ import { TSecretScanningV2DALFactory } from "@app/ee/services/secret-scanning-v2
import {
SecretScanningDataSource,
SecretScanningFindingStatus,
- SecretScanningScanStatus
+ SecretScanningScanStatus,
+ SecretScanningScanTrigger
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -167,6 +173,9 @@ export type TQueueSecretScanningResourceDiffScanPayload = {
scanId: string;
};
+// Webhook events a provider processes in the background, beyond the pushes every provider scans.
+export type TQueueSecretScanningDataSourceEvent = TQueueGitHubDataSourceEvent;
+
export type TQueueSecretScanningSendNotification = {
dataSource: TSecretScanningDataSources;
resourceName: string;
@@ -201,10 +210,54 @@ export type TSecretScanningFactoryGetFullScanPath<T extends TSecretScanningDataS
tempFolder: string;
}) => Promise<string>;
+// What a provider learned about the scanned changes beyond the findings, for the scan's report.
+export type TSecretScanningDiffScanDetails = TGitHubDiffScanDetails;
+
+export type TSecretScanningDiffScanFindings = {
+ findings: TFindingsPayload;
+ details?: TSecretScanningDiffScanDetails;
+};
+
export type TSecretScanningFactoryGetDiffScanFindingsPayload<
T extends TSecretScanningDataSourceWithConnection,
P extends TQueueSecretScanningResourceDiffScan["payload"]
-> = (parameters: { dataSource: T; resourceName: string; payload: P; configPath?: string }) => Promise<TFindingsPayload>;
+> = (parameters: {
+ dataSource: T;
+ resourceName: string;
+ payload: P;
+ configPath?: string;
+}) => Promise<TSecretScanningDiffScanFindings>;
+
+/**
+ * Reports a scan back to where it was requested, such as a check run on a GitHub pull request. Every method is called
+ * after the scan's own state is saved and must not throw, since a provider outage can't change the scan's outcome.
+ */
+export type TSecretScanningScanReport = {
+ start: () => Promise<void>;
+ // Saved on the completed scan, in the transaction that saves its findings.
+ getCompletedScanMetadata: (params: TSecretScanningScanReportCompletion) => unknown;
+ // `findings` are every finding the scan matched, with the status each was triaged to.
+ complete: (params: TSecretScanningScanReportCompletion) => Promise<void>;
+ fail: (params: { reason: string; isTimedOut?: boolean }) => Promise<void>;
+ cancel: () => Promise<void>;
+};
+
+export type TSecretScanningScanReportCompletion = {
+ findings: TSecretScanningFindings[];
+ details?: TSecretScanningDiffScanDetails;
+};
+
+// Built from the job payload, so a scan whose data source was deleted can still close its report.
+export type TSecretScanningFactoryGetDiffScanReport<P extends TQueueSecretScanningResourceDiffScan["payload"]> = (
+ payload: P
+) => TSecretScanningScanReport | undefined;
+
+// Built from the saved scan, for a scan whose worker died before it could close its report.
+export type TSecretScanningFactoryGetScanReport = (params: {
+ scan: Pick<TSecretScanningScans, "trigger" | "metadata">;
+ dataSource: Pick<TSecretScanningDataSources, "externalId">;
+ resourceName: string;
+}) => TSecretScanningScanReport | undefined;
export type TSecretScanningDataSourceRaw = NonNullable<
Awaited<ReturnType<TSecretScanningV2DALFactory["dataSources"]["findById"]>>
@@ -281,6 +334,37 @@ export type TSecretScanningFactory<
validateConfigUpdate: TSecretScanningFactoryValidateConfigUpdate<I["config"], T>;
getDiffScanResourcePayload: TSecretScanningFactoryGetDiffScanResourcePayload<P>;
getDiffScanFindingsPayload: TSecretScanningFactoryGetDiffScanFindingsPayload<T, P>;
+ getDiffScanReport?: TSecretScanningFactoryGetDiffScanReport<P>;
+ getScanReport?: TSecretScanningFactoryGetScanReport;
+};
+
+export type TSecretScanningDiscoverResource = (params: {
+ dataSource: Pick<TSecretScanningDataSources, "id" | "isHistoricalScanEnabled">;
+ resourcePayload: Pick<TSecretScanningResourcesInsert, "externalId" | "name">;
+ trigger: SecretScanningScanTrigger.Push | SecretScanningScanTrigger.PullRequest;
+}) => Promise<TSecretScanningResources | undefined>;
+
+export type TSecretScanningQueueReportedDiffScan = (
+ params: Pick<TQueueSecretScanningResourceDiffScan, "dataSourceType" | "payload"> & {
+ scanId: string;
+ dataSourceId: string;
+ resourceId: string;
+ trigger: SecretScanningScanTrigger;
+ metadata: unknown;
+ }
+) => Promise<void>;
+
+export type TSecretScanningEventProcessorParams = {
+ secretScanningV2DAL: TSecretScanningV2DALFactory;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ discoverResource: TSecretScanningDiscoverResource;
+ queueReportedDiffScan: TSecretScanningQueueReportedDiffScan;
+};
+
+export type TSecretScanningEventProcessor<E extends TQueueSecretScanningDataSourceEvent["event"]> = (
+ params: TSecretScanningEventProcessorParams
+) => {
+ processEvent: (event: E) => Promise<void>;
};
export type TFindingsPayload = Pick<TSecretScanningFindingsInsert, "details" | "fingerprint" | "severity" | "rule">[];
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index cae6f6ef39..133fa32b9d 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -17,8 +17,8 @@ import {
TSecretRotationRotateSecretsJobPayload,
TSecretRotationSendNotificationJobPayload
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
-import { TQueueGitHubPullRequestEvent } from "@app/ee/services/secret-scanning-v2/github/github-secret-scanning-types";
import {
+ TQueueSecretScanningDataSourceEvent,
TQueueSecretScanningDataSourceFullScan,
TQueueSecretScanningResourceDiffScan,
TQueueSecretScanningResourceDiffScanPayload,
@@ -190,7 +190,7 @@ export enum QueueJobs {
// name carry it, and the drain branch on QueueName.SecretScanningV2 matches on it.
SecretScanningV2DiffScan = "secret-scanning-v2-diff-scan",
SecretScanningV2SendNotification = "secret-scanning-v2-notification",
- SecretScanningV2GitHubPullRequestEvent = "secret-scanning-v2-github-pull-request-event",
+ SecretScanningV2DataSourceEvent = "secret-scanning-v2-data-source-event",
CaOrderCertificateForSubscriber = "ca-order-certificate-for-subscriber",
CaIssueCertificateFromProfile = "ca-issue-certificate-from-profile",
PkiSubscriberDailyAutoRenewal = "pki-subscriber-daily-auto-renewal",
@@ -499,8 +499,8 @@ export type TQueueJobTypes = {
payload: TQueueSecretScanningSendNotification;
}
| {
- name: QueueJobs.SecretScanningV2GitHubPullRequestEvent;
- payload: TQueueGitHubPullRequestEvent;
+ name: QueueJobs.SecretScanningV2DataSourceEvent;
+ payload: TQueueSecretScanningDataSourceEvent;
};
[QueueName.SecretScanningV2FullScan]: {
name: QueueJobs.SecretScanningV2FullScan;