Skip to content

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

github PR scan

Matheus Nogueiraee0f05a95052
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index 59d352893f..98b77b1238 100644
--- a/backend/AGENTS.md
+++ b/backend/AGENTS.md
@@ -1233,6 +1233,8 @@ 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`. 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.
**Gateways: there is only one generation.** Gateway v1 (`ee/services/gateway`, `lib/gateway`, the QUIC
diff --git a/backend/src/db/migrations/20261028120000_secret-scanning-scan-trigger-metadata.ts b/backend/src/db/migrations/20261028120000_secret-scanning-scan-trigger-metadata.ts
new file mode 100644
index 0000000000..9d58fef2b3
--- /dev/null
+++ b/backend/src/db/migrations/20261028120000_secret-scanning-scan-trigger-metadata.ts
@@ -0,0 +1,27 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasTrigger = await knex.schema.hasColumn(TableName.SecretScanningScan, "trigger");
+ const hasMetadata = await knex.schema.hasColumn(TableName.SecretScanningScan, "metadata");
+
+ if (!hasTrigger || !hasMetadata) {
+ await knex.schema.alterTable(TableName.SecretScanningScan, (t) => {
+ if (!hasTrigger) t.string("trigger").nullable();
+ if (!hasMetadata) t.jsonb("metadata").nullable();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasTrigger = await knex.schema.hasColumn(TableName.SecretScanningScan, "trigger");
+ const hasMetadata = await knex.schema.hasColumn(TableName.SecretScanningScan, "metadata");
+
+ if (hasTrigger || hasMetadata) {
+ await knex.schema.alterTable(TableName.SecretScanningScan, (t) => {
+ if (hasTrigger) t.dropColumn("trigger");
+ if (hasMetadata) t.dropColumn("metadata");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/secret-scanning-scans.ts b/backend/src/db/schemas/secret-scanning-scans.ts
index ee280e8b2d..8c516589ff 100644
--- a/backend/src/db/schemas/secret-scanning-scans.ts
+++ b/backend/src/db/schemas/secret-scanning-scans.ts
@@ -19,7 +19,9 @@ export const SecretScanningScansSchema = z.object({
progressUpdatedAt: z.date().nullable().optional(),
lastScannedCommitDigest: z.string().nullable().optional(),
triggeredByUserId: z.string().uuid().nullable().optional(),
- completedAt: z.date().nullable().optional()
+ completedAt: z.date().nullable().optional(),
+ trigger: z.string().nullable().optional(),
+ metadata: z.unknown().nullable().optional()
});
export type TSecretScanningScans = z.infer<typeof SecretScanningScansSchema>;
diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-enums.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-enums.ts
new file mode 100644
index 0000000000..d3e169f155
--- /dev/null
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-enums.ts
@@ -0,0 +1,5 @@
+export enum GitHubPullRequestEvent {
+ PullRequest = "pull-request",
+ CheckRunRerequested = "check-run-rerequested",
+ CheckSuiteRerequested = "check-suite-rerequested"
+}
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 5312b04b95..ef1865e930 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,16 +1,10 @@
import { join } from "path";
import { ProbotOctokit } from "probot";
-import {
- SecretScanningDataSource,
- SecretScanningFindingSeverity
-} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
+import { SecretScanningDataSource } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import {
assertProviderRepositorySizeWithinLimit,
- cloneRepository,
- convertPatchLineToFileLineNumber,
- replaceNonChangesWithNewlines,
- toFindingDetails
+ cloneRepository
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-fns";
import {
TSecretScanningFactoryGetDiffScanFindingsPayload,
@@ -23,13 +17,17 @@ import {
TSecretScanningFactoryTeardown,
TSecretScanningFactoryValidateConfigUpdate
} 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 { BadRequestError } from "@app/lib/errors";
import { BasicRepositoryRegex } from "@app/lib/regex";
import { listGitHubRadarRepositories, TGitHubRadarConnection } from "@app/services/app-connection/github-radar";
+import {
+ getGitHubRadarInstallationOctokit,
+ isGitHubPullRequestScanPayload,
+ scanGitHubCommitsAndGetFindings,
+ scanGitHubPullRequest
+} from "./github-secret-scanning-fns";
import {
TGitHubDataSourceInput,
TGitHubDataSourceWithConnection,
@@ -152,86 +150,26 @@ export const GitHubSecretScanningFactory = () => {
TGitHubDataSourceWithConnection,
TQueueGitHubResourceDiffScan["payload"]
> = async ({ dataSource, payload, resourceName, configPath }) => {
- const appCfg = getConfig();
- const {
- connection: {
- credentials: { installationId }
- }
- } = dataSource;
-
- const octokit = new ProbotOctokit({
- auth: {
- appId: appCfg.INF_APP_CONNECTION_GITHUB_RADAR_APP_ID,
- privateKey: appCfg.INF_APP_CONNECTION_GITHUB_RADAR_APP_PRIVATE_KEY,
- installationId
- }
- });
+ if (isGitHubPullRequestScanPayload(payload)) {
+ const { findings } = await scanGitHubPullRequest({ payload, resourceName, configPath });
+ return findings;
+ }
const { commits, repository } = payload;
- const [owner, repo] = repository.full_name.split("/");
-
- const allFindings: SecretMatch[] = [];
-
- for (const commit of commits) {
- // eslint-disable-next-line no-await-in-loop
- const commitData = await octokit.repos.getCommit({
- owner,
- repo,
- ref: commit.id
- });
-
- // eslint-disable-next-line no-continue
- if (!commitData.data.files) continue;
-
- for (const file of commitData.data.files) {
- if ((file.status === "added" || file.status === "modified") && file.patch) {
- // eslint-disable-next-line
- const findings = await scanContentAndGetFindings(
- replaceNonChangesWithNewlines(`\n${file.patch}`),
- configPath
- );
-
- const adjustedFindings = findings.map((finding) => {
- const startLine = convertPatchLineToFileLineNumber(file.patch!, finding.StartLine);
- const endLine =
- finding.StartLine === finding.EndLine
- ? startLine
- : convertPatchLineToFileLineNumber(file.patch!, finding.EndLine);
- const startColumn = finding.StartColumn - 1; // subtract 1 for +
- const endColumn = finding.EndColumn - 1; // subtract 1 for +
-
- return {
- ...finding,
- StartLine: startLine,
- EndLine: endLine,
- StartColumn: startColumn,
- EndColumn: endColumn,
- File: file.filename,
- Commit: commit.id,
- Author: commit.author.name,
- Email: commit.author.email ?? "",
- Message: commit.message,
- Fingerprint: `${commit.id}:${file.filename}:${finding.RuleID}:${startLine}:${startColumn}`,
- Date: commit.timestamp,
- Attributes: {
- ...finding.Attributes,
- url: `https://github.com/${resourceName}/blob/${commit.id}/${file.filename}#L${startLine}`
- }
- };
- });
-
- allFindings.push(...adjustedFindings);
- }
- }
- }
-
- return allFindings.map((finding) => ({
- details: toFindingDetails(finding),
- fingerprint: finding.Fingerprint,
- severity: SecretScanningFindingSeverity.High,
- rule: finding.RuleID
- }));
+ return scanGitHubCommitsAndGetFindings({
+ octokit: getGitHubRadarInstallationOctokit(dataSource.connection.credentials.installationId),
+ repositoryFullName: repository.full_name,
+ resourceName,
+ commits: commits.map((commit) => ({
+ sha: commit.id,
+ authorName: commit.author.name,
+ authorEmail: commit.author.email ?? "",
+ date: commit.timestamp,
+ message: commit.message
+ })),
+ configPath
+ });
};
return {
diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.ts
new file mode 100644
index 0000000000..68be36d0ad
--- /dev/null
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.test.ts
@@ -0,0 +1,159 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { SecretScanningFindingSeverity } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
+import { TFindingsPayload } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-types";
+
+import {
+ completePullRequestCheckRun,
+ getPullRequestScanCheckRunResult,
+ isGitHubPullRequestScanPayload
+} from "./github-secret-scanning-fns";
+
+const checksUpdate = vi.fn();
+
+vi.mock("probot", () => ({
+ ProbotOctokit: vi.fn(() => ({ checks: { update: checksUpdate } }))
+}));
+
+vi.mock("@app/lib/config/env", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/lib/config/env")>()),
+ getConfig: () => ({
+ INF_APP_CONNECTION_GITHUB_RADAR_APP_ID: "1",
+ INF_APP_CONNECTION_GITHUB_RADAR_APP_PRIVATE_KEY: "key"
+ })
+}));
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
+
+const SECRET_VALUE = "ghp_secretvalue1234567890";
+
+const makeFinding = (index: number): TFindingsPayload[number] => ({
+ rule: "github-pat",
+ severity: SecretScanningFindingSeverity.High,
+ fingerprint: `abc123:config|${index}.ts:github-pat:${index + 1}:4`,
+ details: {
+ description: "GitHub Personal Access Token",
+ startLine: index + 1,
+ endLine: index + 1,
+ startColumn: 4,
+ endColumn: 30,
+ file: `config|${index}.ts`,
+ link: "",
+ symlinkFile: "",
+ commit: "abc123def4567890",
+ entropy: 4.2,
+ author: "Dev",
+ email: "[email protected]",
+ date: "2026-10-28T00:00:00Z",
+ message: `add token ${SECRET_VALUE}`,
+ tags: [],
+ ruleID: "github-pat",
+ fingerprint: `abc123:config|${index}.ts:github-pat:${index + 1}:4`
+ }
+});
+
+describe("isGitHubPullRequestScanPayload", () => {
+ test("tells a pull request scan from a push", () => {
+ expect(
+ isGitHubPullRequestScanPayload({
+ installationId: "1",
+ repository: { id: 1, full_name: "acme/api" },
+ pullRequest: { number: 7, baseSha: "base", headSha: "head" },
+ checkRunId: 99
+ })
+ ).toBe(true);
+
+ expect(isGitHubPullRequestScanPayload({ commits: [], repository: { id: 1, full_name: "acme/api" } } as never)).toBe(
+ false
+ );
+ });
+});
+
+describe("getPullRequestScanCheckRunResult", () => {
+ test("passes when every commit was scanned and nothing was found", () => {
+ const result = getPullRequestScanCheckRunResult({ findings: [], scannedCommitCount: 3, totalCommitCount: 3 });
+
+ expect(result.conclusion).toBe("success");
+ expect(result.summary).toContain("Scanned 3 commit(s)");
+ });
+
+ test("does not pass a pull request whose commits were only partly scanned", () => {
+ const result = getPullRequestScanCheckRunResult({
+ findings: [],
+ scannedCommitCount: 2000,
+ totalCommitCount: 2100
+ });
+
+ expect(result.conclusion).toBe("neutral");
+ expect(result.summary).toContain("has 2100 commits");
+ });
+
+ test("fails on any finding and never includes the secret", () => {
+ const result = getPullRequestScanCheckRunResult({
+ findings: [makeFinding(0), makeFinding(1)],
+ scannedCommitCount: 2,
+ totalCommitCount: 2
+ });
+
+ expect(result.conclusion).toBe("failure");
+ expect(result.title).toBe("2 secret(s) found");
+ expect(result.summary).toContain("| github-pat | config\\|0.ts | 1 | abc123d |");
+ expect(result.summary).not.toContain(SECRET_VALUE);
+ });
+
+ test("caps the summary table and says how many findings it shows", () => {
+ const findings = Array.from({ length: 60 }, (_, index) => makeFinding(index));
+ const result = getPullRequestScanCheckRunResult({ findings, scannedCommitCount: 1, totalCommitCount: 1 });
+
+ expect(result.summary).toContain("Showing 50 of 60 findings.");
+ expect(result.summary.match(/\| github-pat \|/g)).toHaveLength(50);
+ });
+});
+
+describe("completePullRequestCheckRun", () => {
+ beforeEach(() => {
+ checksUpdate.mockReset();
+ });
+
+ test("completes the check run and sends annotations in batches of 50", async () => {
+ const findings = Array.from({ length: 120 }, (_, index) => makeFinding(index));
+
+ await completePullRequestCheckRun({
+ installationId: "1",
+ repositoryFullName: "acme/api",
+ checkRunId: 99,
+ result: getPullRequestScanCheckRunResult({ findings, scannedCommitCount: 1, totalCommitCount: 1 })
+ });
+
+ expect(checksUpdate).toHaveBeenCalledTimes(3);
+
+ const [first, second, third] = checksUpdate.mock.calls.map(([params]) => params);
+
+ expect(first).toMatchObject({
+ owner: "acme",
+ repo: "api",
+ check_run_id: 99,
+ status: "completed",
+ conclusion: "failure"
+ });
+ expect(first.output.annotations).toHaveLength(50);
+ expect(second.output.annotations).toHaveLength(50);
+ expect(second.conclusion).toBeUndefined();
+ expect(third.output.annotations).toHaveLength(20);
+ expect(JSON.stringify(checksUpdate.mock.calls)).not.toContain(SECRET_VALUE);
+ });
+
+ test("completes a check run with no findings in a single update", async () => {
+ await completePullRequestCheckRun({
+ installationId: "1",
+ repositoryFullName: "acme/api",
+ checkRunId: 99,
+ result: getPullRequestScanCheckRunResult({ findings: [], scannedCommitCount: 1, totalCommitCount: 1 })
+ });
+
+ expect(checksUpdate).toHaveBeenCalledTimes(1);
+ expect(checksUpdate.mock.calls[0][0]).toMatchObject({ conclusion: "success", output: { annotations: [] } });
+ });
+});
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
new file mode 100644
index 0000000000..afbc136566
--- /dev/null
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-fns.ts
@@ -0,0 +1,441 @@
+import { ProbotOctokit } from "probot";
+
+import { SecretScanningFindingSeverity } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
+import {
+ convertPatchLineToFileLineNumber,
+ replaceNonChangesWithNewlines,
+ toFindingDetails
+} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-fns";
+import { GitRepositoryScanFindingDetailsSchema } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-schemas";
+import {
+ TFindingsPayload,
+ TQueueSecretScanningResourceDiffScan
+} 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 { chunkArray } from "@app/lib/fn/array";
+import { logger } from "@app/lib/logger";
+
+import { TGitHubPullRequestScanPayload } from "./github-secret-scanning-types";
+
+export const GITHUB_PULL_REQUEST_CHECK_NAME = "Infisical Secret Scanning";
+
+const COMPARE_COMMITS_PER_PAGE = 100;
+const COMPARE_COMMITS_MAX_PAGES = 20;
+// GitHub rejects a check run update carrying more than 50 annotations; more are sent as further updates.
+const CHECK_RUN_ANNOTATIONS_PER_REQUEST = 50;
+const CHECK_RUN_MAX_ANNOTATIONS = 500;
+const CHECK_RUN_MAX_SUMMARY_FINDINGS = 50;
+
+type TGitHubOctokit = InstanceType<typeof ProbotOctokit>;
+
+type TGitHubCommitToScan = {
+ sha: string;
+ authorName: string;
+ authorEmail: string;
+ date: string;
+ message: string;
+};
+
+type TPullRequestCheckRunTarget = {
+ installationId: string;
+ repositoryFullName: string;
+ checkRunId: number;
+};
+
+export type TPullRequestCheckRunResult = {
+ conclusion: "success" | "failure" | "neutral" | "cancelled" | "timed_out";
+ title: string;
+ summary: string;
+ findings?: TFindingsPayload;
+};
+
+export const getGitHubRadarInstallationOctokit = (installationId: string) => {
+ const appCfg = getConfig();
+
+ return new ProbotOctokit({
+ auth: {
+ appId: appCfg.INF_APP_CONNECTION_GITHUB_RADAR_APP_ID,
+ privateKey: appCfg.INF_APP_CONNECTION_GITHUB_RADAR_APP_PRIVATE_KEY,
+ installationId
+ }
+ });
+};
+
+const splitRepositoryFullName = (repositoryFullName: string) => {
+ const [owner, repo] = repositoryFullName.split("/");
+ return { owner, repo };
+};
+
+export const isGitHubPullRequestScanPayload = (
+ payload: TQueueSecretScanningResourceDiffScan["payload"]
+): payload is TGitHubPullRequestScanPayload => "pullRequest" in payload && "checkRunId" in payload;
+
+export const scanGitHubCommitsAndGetFindings = async ({
+ octokit,
+ repositoryFullName,
+ resourceName,
+ commits,
+ configPath
+}: {
+ octokit: TGitHubOctokit;
+ repositoryFullName: string;
+ resourceName: string;
+ commits: TGitHubCommitToScan[];
+ configPath?: string;
+}): Promise<TFindingsPayload> => {
+ const { owner, repo } = splitRepositoryFullName(repositoryFullName);
+
+ const allFindings: SecretMatch[] = [];
+
+ for (const commit of commits) {
+ // eslint-disable-next-line no-await-in-loop
+ const commitData = await octokit.repos.getCommit({
+ owner,
+ repo,
+ ref: commit.sha
+ });
+
+ // eslint-disable-next-line no-continue
+ if (!commitData.data.files) continue;
+
+ for (const file of commitData.data.files) {
+ if ((file.status === "added" || file.status === "modified") && file.patch) {
+ // eslint-disable-next-line
+ const findings = await scanContentAndGetFindings(replaceNonChangesWithNewlines(`\n${file.patch}`), configPath);
+
+ const adjustedFindings = findings.map((finding) => {
+ const startLine = convertPatchLineToFileLineNumber(file.patch!, finding.StartLine);
+ const endLine =
+ finding.StartLine === finding.EndLine
+ ? startLine
+ : convertPatchLineToFileLineNumber(file.patch!, finding.EndLine);
+ const startColumn = finding.StartColumn - 1; // subtract 1 for +
+ const endColumn = finding.EndColumn - 1; // subtract 1 for +
+
+ return {
+ ...finding,
+ StartLine: startLine,
+ EndLine: endLine,
+ StartColumn: startColumn,
+ EndColumn: endColumn,
+ File: file.filename,
+ Commit: commit.sha,
+ Author: commit.authorName,
+ Email: commit.authorEmail,
+ Message: commit.message,
+ Fingerprint: `${commit.sha}:${file.filename}:${finding.RuleID}:${startLine}:${startColumn}`,
+ Date: commit.date,
+ Attributes: {
+ ...finding.Attributes,
+ url: `https://github.com/${resourceName}/blob/${commit.sha}/${file.filename}#L${startLine}`
+ }
+ };
+ });
+
+ allFindings.push(...adjustedFindings);
+ }
+ }
+ }
+
+ return allFindings.map((finding) => ({
+ details: toFindingDetails(finding),
+ fingerprint: finding.Fingerprint,
+ severity: SecretScanningFindingSeverity.High,
+ rule: finding.RuleID
+ }));
+};
+
+// Compares against the exact head the check was created for, so commits pushed after it are left to their own check.
+const listPullRequestCommits = async (
+ octokit: TGitHubOctokit,
+ { repositoryFullName, baseSha, headSha }: { repositoryFullName: string; baseSha: string; headSha: string }
+) => {
+ const { owner, repo } = splitRepositoryFullName(repositoryFullName);
+
+ const commits: TGitHubCommitToScan[] = [];
+ let totalCommits = 0;
+
+ for (let page = 1; page <= COMPARE_COMMITS_MAX_PAGES; page += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const { data } = await octokit.repos.compareCommitsWithBasehead({
+ owner,
+ repo,
+ basehead: `${baseSha}...${headSha}`,
+ per_page: COMPARE_COMMITS_PER_PAGE,
+ page
+ });
+
+ totalCommits = data.total_commits;
+
+ commits.push(
+ ...data.commits.map((commit) => ({
+ sha: commit.sha,
+ authorName: commit.commit.author?.name ?? "",
+ authorEmail: commit.commit.author?.email ?? "",
+ date: commit.commit.author?.date ?? "",
+ message: commit.commit.message
+ }))
+ );
+
+ if (!data.commits.length || commits.length >= totalCommits) break;
+ }
+
+ if (commits.length < totalCommits) {
+ logger.warn(
+ `secretScanningV2PullRequestScan: GitHub - pull request commits truncated [repository=${repositoryFullName}] [headSha=${headSha}] [scannedCommits=${commits.length}] [totalCommits=${totalCommits}]`
+ );
+ }
+
+ return { commits, totalCommits };
+};
+
+export const scanGitHubPullRequest = async ({
+ payload,
+ resourceName,
+ configPath
+}: {
+ payload: TGitHubPullRequestScanPayload;
+ resourceName: string;
+ configPath?: string;
+}) => {
+ const octokit = getGitHubRadarInstallationOctokit(payload.installationId);
+
+ const { commits, totalCommits } = await listPullRequestCommits(octokit, {
+ repositoryFullName: payload.repository.full_name,
+ baseSha: payload.pullRequest.baseSha,
+ headSha: payload.pullRequest.headSha
+ });
+
+ const findings = await scanGitHubCommitsAndGetFindings({
+ octokit,
+ repositoryFullName: payload.repository.full_name,
+ resourceName,
+ commits,
+ configPath
+ });
+
+ return { findings, scannedCommitCount: commits.length, totalCommitCount: totalCommits };
+};
+
+export const createPullRequestCheckRun = async ({
+ installationId,
+ repositoryFullName,
+ headSha,
+ scanId,
+ detailsUrl
+}: {
+ installationId: string;
+ repositoryFullName: string;
+ headSha: string;
+ scanId: string;
+ detailsUrl?: string;
+}) => {
+ const octokit = getGitHubRadarInstallationOctokit(installationId);
+ const { owner, repo } = splitRepositoryFullName(repositoryFullName);
+
+ const { data } = await octokit.checks.create({
+ owner,
+ repo,
+ name: GITHUB_PULL_REQUEST_CHECK_NAME,
+ head_sha: headSha,
+ // Returned on every event for this check, which is how a re-run finds the scan it repeats.
+ external_id: scanId,
+ status: "queued",
+ ...(detailsUrl ? { details_url: detailsUrl } : {})
+ });
+
+ return data.id;
+};
+
+// A suite holds one App's check runs for one commit; `latest` returns only the newest run with our check's name.
+export const getLatestPullRequestCheckRunExternalId = async ({
+ installationId,
+ repositoryFullName,
+ checkSuiteId
+}: {
+ installationId: string;
+ repositoryFullName: string;
+ checkSuiteId: number;
+}) => {
+ const octokit = getGitHubRadarInstallationOctokit(installationId);
+ const { owner, repo } = splitRepositoryFullName(repositoryFullName);
+
+ const { data } = await octokit.checks.listForSuite({
+ owner,
+ repo,
+ check_suite_id: checkSuiteId,
+ check_name: GITHUB_PULL_REQUEST_CHECK_NAME,
+ filter: "latest"
+ });
+
+ return data.check_runs.length ? data.check_runs[0].external_id : null;
+};
+
+export const startPullRequestCheckRun = async ({
+ installationId,
+ repositoryFullName,
+ checkRunId
+}: TPullRequestCheckRunTarget) => {
+ const octokit = getGitHubRadarInstallationOctokit(installationId);
+ const { owner, repo } = splitRepositoryFullName(repositoryFullName);
+
+ await octokit.checks.update({
+ owner,
+ repo,
+ check_run_id: checkRunId,
+ status: "in_progress",
+ started_at: new Date().toISOString()
+ });
+};
+
+const FindingLocationSchema = GitRepositoryScanFindingDetailsSchema.pick({
+ file: true,
+ startLine: true,
+ endLine: true,
+ commit: true,
+ description: true
+});
+
+const getFindingLocations = (findings: TFindingsPayload) =>
+ findings.flatMap((finding) => {
+ const details = FindingLocationSchema.safeParse(finding.details);
+ return details.success ? [{ rule: finding.rule, ...details.data }] : [];
+ });
+
+const toCheckRunAnnotations = (findings: TFindingsPayload) =>
+ getFindingLocations(findings).map(({ rule, file, startLine, endLine, commit, description }) => ({
+ path: file,
+ start_line: startLine,
+ end_line: endLine,
+ annotation_level: "failure" as const,
+ title: `Secret detected: ${rule}`,
+ message: `${description}. Found in commit ${commit.slice(0, 7)}.`
+ }));
+
+const escapeMarkdownTableCell = (value: string) => value.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
+
+export const getPullRequestScanCheckRunResult = ({
+ findings,
+ scannedCommitCount,
+ totalCommitCount
+}: {
+ findings: TFindingsPayload;
+ scannedCommitCount: number;
+ totalCommitCount: number;
+}): TPullRequestCheckRunResult => {
+ const truncationNote =
+ scannedCommitCount < totalCommitCount
+ ? `This pull request has ${totalCommitCount} commits. Infisical scanned the first ${scannedCommitCount}; later commits were not scanned.`
+ : "";
+
+ if (!findings.length) {
+ if (truncationNote) {
+ return {
+ conclusion: "neutral",
+ title: "Scan incomplete",
+ summary: `No secrets found in the scanned commits. ${truncationNote}`
+ };
+ }
+
+ return {
+ conclusion: "success",
+ title: "No secrets found",
+ summary: `Scanned ${scannedCommitCount} commit(s) in this pull request. No secrets found.`
+ };
+ }
+
+ const table = [
+ "| Rule | File | Line | Commit |",
+ "| --- | --- | --- | --- |",
+ ...getFindingLocations(findings.slice(0, CHECK_RUN_MAX_SUMMARY_FINDINGS)).map(
+ ({ rule, file, startLine, commit }) =>
+ `| ${escapeMarkdownTableCell(rule)} | ${escapeMarkdownTableCell(file)} | ${startLine} | ${commit.slice(0, 7)} |`
+ )
+ ].join("\n");
+
+ const summary = [
+ `Found ${findings.length} secret(s) in the commits of this pull request. Rotate each secret, then remove it from the pull request's history.`,
+ "If a finding is a false positive, add it to the allowlist in your Infisical secret scanning configuration, then re-run this check.",
+ truncationNote,
+ table,
+ findings.length > CHECK_RUN_MAX_SUMMARY_FINDINGS
+ ? `Showing ${CHECK_RUN_MAX_SUMMARY_FINDINGS} of ${findings.length} findings.`
+ : ""
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+
+ return {
+ conclusion: "failure",
+ title: `${findings.length} secret(s) found`,
+ summary,
+ findings
+ };
+};
+
+// A scan that could not finish fails the check rather than passing it, so an outage never lets a secret through.
+export const getPullRequestScanFailedCheckRunResult = (
+ reason: string,
+ conclusion: "failure" | "timed_out" = "failure"
+): TPullRequestCheckRunResult => ({
+ conclusion,
+ title: "Scan failed",
+ summary: `Infisical could not scan this pull request: ${reason} Re-run this check to try again.`
+});
+
+export const PULL_REQUEST_SCAN_CANCELLED_CHECK_RUN_RESULT: TPullRequestCheckRunResult = {
+ conclusion: "cancelled",
+ title: "Scan cancelled",
+ summary:
+ "This repository is no longer part of an Infisical secret scanning data source, so the pull request was not scanned."
+};
+
+export const completePullRequestCheckRun = async ({
+ installationId,
+ repositoryFullName,
+ checkRunId,
+ result
+}: TPullRequestCheckRunTarget & { result: TPullRequestCheckRunResult }) => {
+ const octokit = getGitHubRadarInstallationOctokit(installationId);
+ const { owner, repo } = splitRepositoryFullName(repositoryFullName);
+
+ const annotations = toCheckRunAnnotations((result.findings ?? []).slice(0, CHECK_RUN_MAX_ANNOTATIONS));
+ const [firstBatch = [], ...remainingBatches] = chunkArray(annotations, CHECK_RUN_ANNOTATIONS_PER_REQUEST);
+
+ await octokit.checks.update({
+ owner,
+ repo,
+ check_run_id: checkRunId,
+ status: "completed",
+ conclusion: result.conclusion,
+ completed_at: new Date().toISOString(),
+ output: { title: result.title, summary: result.summary, annotations: firstBatch }
+ });
+
+ // Annotations sent in later updates are appended to the ones already on the check run.
+ for (const batch of remainingBatches) {
+ // eslint-disable-next-line no-await-in-loop
+ await octokit.checks.update({
+ owner,
+ repo,
+ check_run_id: checkRunId,
+ output: { title: result.title, summary: result.summary, annotations: batch }
+ });
+ }
+};
+
+// The scan's outcome is already saved, so a check run that cannot be updated is logged rather than failing the scan.
+export const tryCompletePullRequestCheckRun = async (
+ params: TPullRequestCheckRunTarget & { result: TPullRequestCheckRunResult }
+) => {
+ try {
+ await completePullRequestCheckRun(params);
+ } catch (error) {
+ logger.error(
+ error,
+ `secretScanningV2PullRequestScan: GitHub - failed to complete check run [repository=${params.repositoryFullName}] [checkRunId=${params.checkRunId}] [conclusion=${params.result.conclusion}]`
+ );
+ }
+};
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-pull-request-events.ts
new file mode 100644
index 0000000000..fbc8077825
--- /dev/null
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-pull-request-events.ts
@@ -0,0 +1,241 @@
+import { Repository } from "@octokit/webhooks-types";
+import { z } from "zod";
+
+import { TSecretScanningDataSources, TSecretScanningResources, TSecretScanningResourcesInsert } from "@app/db/schemas";
+import { TSecretScanningV2DALFactory } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-dal";
+import {
+ SecretScanningDataSource,
+ SecretScanningScanTrigger
+} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
+import { getConfig } from "@app/lib/config/env";
+import { crypto } from "@app/lib/crypto";
+import { logger } from "@app/lib/logger";
+
+import { GitHubPullRequestEvent } from "./github-secret-scanning-enums";
+import { createPullRequestCheckRun, getLatestPullRequestCheckRunExternalId } from "./github-secret-scanning-fns";
+import { GitHubPullRequestScanMetadataSchema } from "./github-secret-scanning-schemas";
+import { TGitHubPullRequestScanPayload, TQueueGitHubPullRequestEvent } from "./github-secret-scanning-types";
+
+type TGitHubPullRequestEventsFactoryDep = {
+ secretScanningV2DAL: TSecretScanningV2DALFactory;
+ 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 = ({
+ secretScanningV2DAL,
+ discoverResource,
+ queuePullRequestScan
+}: TGitHubPullRequestEventsFactoryDep) => {
+ // 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;
+ }
+
+ await queuePullRequestScan({
+ scanId,
+ dataSourceId: dataSource.id,
+ resourceId: resource.id,
+ payload: {
+ installationId: String(installationId),
+ repository: { id: repository.id, full_name: repository.full_name },
+ pullRequest,
+ checkRunId
+ }
+ });
+ };
+
+ // 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 });
+ };
+
+ const processPullRequestEvent = 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 });
+ default:
+ logger.error(
+ `secretScanningV2PullRequestEvent: GitHub - unhandled event [event=${(job as { event: string }).event}]`
+ );
+ }
+ };
+
+ return { processPullRequestEvent };
+};
diff --git a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-schemas.ts b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-schemas.ts
index 14a4a0c984..910d004c1e 100644
--- a/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-schemas.ts
+++ b/backend/src/ee/services/secret-scanning-v2/github/github-secret-scanning-schemas.ts
@@ -65,3 +65,10 @@ export const GitHubFindingSchema = BaseSecretScanningFindingSchema.extend({
dataSourceType: z.literal(SecretScanningDataSource.GitHub),
details: GitRepositoryScanFindingDetailsSchema
});
+
+export const GitHubPullRequestScanMetadataSchema = z.object({
+ pullRequestNumber: z.number().int().positive(),
+ baseSha: z.string(),
+ headSha: z.string(),
+ checkRunId: z.number().int().positive()
+});
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 b029ec621d..ba8bd40e58 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
@@ -1,13 +1,26 @@
-import { PushEvent } from "@octokit/webhooks-types";
+import {
+ CheckRunRerequestedEvent,
+ CheckSuiteRerequestedEvent,
+ PullRequestOpenedEvent,
+ PullRequestReopenedEvent,
+ PullRequestSynchronizeEvent,
+ PushEvent
+} from "@octokit/webhooks-types";
import { TSecretScanningV2DALFactory } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-dal";
import { SecretScanningDataSource } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import { TSecretScanningV2QueueServiceFactory } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-queue";
+import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
+import { GitHubPullRequestEvent } from "./github-secret-scanning-enums";
+
export const githubSecretScanningService = (
secretScanningV2DAL: TSecretScanningV2DALFactory,
- secretScanningV2Queue: Pick<TSecretScanningV2QueueServiceFactory, "handleResourcePushEvent">
+ secretScanningV2Queue: Pick<
+ TSecretScanningV2QueueServiceFactory,
+ "handleResourcePushEvent" | "queueGitHubPullRequestEvent"
+ >
) => {
const handleInstallationDeletedEvent = async (installationId: number) => {
const dataSource = await secretScanningV2DAL.dataSources.findOne({
@@ -60,8 +73,88 @@ export const githubSecretScanningService = (
});
};
+ // The pull request events below only enqueue; github-secret-scanning-pull-request-events.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,
+ deliveryId: string
+ ) => {
+ const { installation, repository, pull_request: pullRequest } = payload;
+
+ if (!installation) {
+ logger.warn(
+ `secretScanningV2PullRequestEvent: GitHub - Insufficient data [repository=${repository.full_name}] [pullRequest=${pullRequest.number}]`
+ );
+ return;
+ }
+
+ await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ {
+ event: GitHubPullRequestEvent.PullRequest,
+ installationId: installation.id,
+ repository: { id: repository.id, full_name: repository.full_name },
+ pullRequest: {
+ number: pullRequest.number,
+ baseSha: pullRequest.base.sha,
+ headSha: pullRequest.head.sha
+ }
+ },
+ deliveryId
+ );
+ };
+
+ const handleCheckRunRerequestedEvent = async (payload: CheckRunRerequestedEvent, deliveryId: string) => {
+ const { check_run: checkRun, installation, repository } = payload;
+
+ if (!installation) {
+ logger.warn(
+ `secretScanningV2CheckRunEvent: GitHub - Insufficient data [repository=${repository.full_name}] [checkRunId=${checkRun.id}]`
+ );
+ return;
+ }
+
+ if (String(checkRun.app.id) !== getConfig().INF_APP_CONNECTION_GITHUB_RADAR_APP_ID) return;
+
+ await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ {
+ event: GitHubPullRequestEvent.CheckRunRerequested,
+ installationId: installation.id,
+ repository: { id: repository.id, full_name: repository.full_name },
+ checkRunId: checkRun.id,
+ externalId: checkRun.external_id
+ },
+ deliveryId
+ );
+ };
+
+ const handleCheckSuiteRerequestedEvent = async (payload: CheckSuiteRerequestedEvent, deliveryId: string) => {
+ const { check_suite: checkSuite, installation, repository } = payload;
+
+ if (!installation) {
+ logger.warn(
+ `secretScanningV2CheckSuiteEvent: GitHub - Insufficient data [repository=${repository.full_name}] [checkSuiteId=${checkSuite.id}]`
+ );
+ return;
+ }
+
+ if (String(checkSuite.app.id) !== getConfig().INF_APP_CONNECTION_GITHUB_RADAR_APP_ID) return;
+
+ await secretScanningV2Queue.queueGitHubPullRequestEvent(
+ {
+ event: GitHubPullRequestEvent.CheckSuiteRerequested,
+ installationId: installation.id,
+ repository: { id: repository.id, full_name: repository.full_name },
+ checkSuiteId: checkSuite.id
+ },
+ deliveryId
+ );
+ };
+
return {
handlePushEvent,
+ handlePullRequestEvent,
+ handleCheckRunRerequestedEvent,
+ handleCheckSuiteRerequestedEvent,
handleInstallationDeletedEvent
};
};
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 90b910d448..70ff4ba1e3 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
@@ -1,14 +1,16 @@
-import { PushEvent } from "@octokit/webhooks-types";
+import { PushEvent, Repository } from "@octokit/webhooks-types";
import { z } from "zod";
import { SecretScanningDataSource } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import { TGitHubRadarConnection } from "@app/services/app-connection/github-radar";
+import { GitHubPullRequestEvent } from "./github-secret-scanning-enums";
import {
CreateGitHubDataSourceSchema,
GitHubDataSourceListItemSchema,
GitHubDataSourceSchema,
- GitHubFindingSchema
+ GitHubFindingSchema,
+ GitHubPullRequestScanMetadataSchema
} from "./github-secret-scanning-schemas";
export type TGitHubDataSource = z.infer<typeof GitHubDataSourceSchema>;
@@ -23,10 +25,34 @@ export type TGitHubDataSourceWithConnection = TGitHubDataSource & {
connection: TGitHubRadarConnection;
};
+export type TGitHubPullRequestScanMetadata = z.infer<typeof GitHubPullRequestScanMetadataSchema>;
+
+// Carries everything needed to report on the check run, so a scan whose data source was deleted can still close it.
+export type TGitHubPullRequestScanPayload = {
+ installationId: string;
+ repository: Pick<Repository, "id" | "full_name">;
+ pullRequest: {
+ number: number;
+ baseSha: string;
+ headSha: string;
+ };
+ checkRunId: number;
+};
+
export type TQueueGitHubResourceDiffScan = {
dataSourceType: SecretScanningDataSource.GitHub;
- payload: PushEvent;
+ payload: PushEvent | TGitHubPullRequestScanPayload;
dataSourceId: string;
resourceId: string;
scanId: string;
};
+
+// Webhook events are reduced to what processing them needs, so the queue never holds GitHub's full payload.
+export type TQueueGitHubPullRequestEvent = {
+ installationId: number;
+ repository: Pick<Repository, "id" | "full_name">;
+} & (
+ | { event: GitHubPullRequestEvent.PullRequest; pullRequest: TGitHubPullRequestScanPayload["pullRequest"] }
+ | { event: GitHubPullRequestEvent.CheckRunRerequested; checkRunId: number; externalId: string | null }
+ | { event: GitHubPullRequestEvent.CheckSuiteRerequested; checkSuiteId: number }
+);
diff --git a/backend/src/ee/services/secret-scanning-v2/github/index.ts b/backend/src/ee/services/secret-scanning-v2/github/index.ts
index b8bc755a6d..628658bb71 100644
--- a/backend/src/ee/services/secret-scanning-v2/github/index.ts
+++ b/backend/src/ee/services/secret-scanning-v2/github/index.ts
@@ -1,3 +1,4 @@
export * from "./github-secret-scanning-constants";
+export * from "./github-secret-scanning-enums";
export * from "./github-secret-scanning-schemas";
export * from "./github-secret-scanning-types";
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-enums.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-enums.ts
index dc62ecf2c6..4ac2966a68 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-enums.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-enums.ts
@@ -16,6 +16,13 @@ export enum SecretScanningScanType {
Realtime = "realtime"
}
+export enum SecretScanningScanTrigger {
+ Manual = "manual",
+ ResourcesAdded = "resources-added",
+ Push = "push",
+ PullRequest = "pull-request"
+}
+
export enum SecretScanningFindingStatus {
Resolved = "resolved",
Unresolved = "unresolved",
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 d12448fc73..fce7cdc243 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,6 +7,23 @@ 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,
@@ -40,7 +57,12 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-serv
import { PostHogEventTypes, TSecretScanningScanCompletedEvent } from "@app/services/telemetry/telemetry-types";
import { TSecretScanningV2DALFactory } from "./secret-scanning-v2-dal";
-import { SecretScanningDataSource, SecretScanningScanStatus, SecretScanningScanType } from "./secret-scanning-v2-enums";
+import {
+ SecretScanningDataSource,
+ SecretScanningScanStatus,
+ SecretScanningScanTrigger,
+ SecretScanningScanType
+} from "./secret-scanning-v2-enums";
import { SECRET_SCANNING_FACTORY_MAP } from "./secret-scanning-v2-factory";
import {
TFindingsPayload,
@@ -84,6 +106,9 @@ 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 DUPLICATE_FULL_SCAN_STATUS_MESSAGE =
"Another scan of this resource was already in progress, so this scan was not started.";
@@ -207,14 +232,16 @@ export const secretScanningV2QueueServiceFactory = ({
const queueDataSourceFullScan = async (
dataSource: TSecretScanningDataSourceWithConnection,
{
+ trigger,
resourceExternalId,
triggeredByUserId,
shouldScanResource
}: {
+ trigger: SecretScanningScanTrigger.Manual | SecretScanningScanTrigger.ResourcesAdded;
resourceExternalId?: string;
triggeredByUserId?: string;
shouldScanResource?: (resource: Pick<TSecretScanningResourcesInsert, "externalId" | "name">) => boolean;
- } = {}
+ }
) => {
try {
const { type } = dataSource;
@@ -288,6 +315,7 @@ export const secretScanningV2QueueServiceFactory = ({
resourcesToScan.map((resource) => ({
resourceId: resource.id,
type: SecretScanningScanType.Historical,
+ trigger,
triggeredByUserId: triggeredByUserId ?? null
})),
tx
@@ -696,7 +724,8 @@ export const secretScanningV2QueueServiceFactory = ({
const scan = await secretScanningV2DAL.scans.create(
{
resourceId: resource.id,
- type: SecretScanningScanType.Realtime
+ type: SecretScanningScanType.Realtime,
+ trigger: SecretScanningScanTrigger.Push
},
tx
);
@@ -752,6 +781,19 @@ export const secretScanningV2QueueServiceFactory = ({
const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [jobId=${job.id}] retryCount=[${retryCount}/${retryLimit}]`;
+ const pullRequestScan = isGitHubPullRequestScanPayload(payload) ? payload : undefined;
+
+ const reportPullRequestCheck = async (result: TPullRequestCheckRunResult) => {
+ if (!pullRequestScan) return;
+
+ await tryCompletePullRequestCheckRun({
+ installationId: pullRequestScan.installationId,
+ repositoryFullName: pullRequestScan.repository.full_name,
+ checkRunId: pullRequestScan.checkRunId,
+ result
+ });
+ };
+
// Primary for the same reason as the full scan: a lagging replica would drop a just-queued scan.
const primary = secretScanningV2DAL.primaryNode();
const dataSource = await secretScanningV2DAL.dataSources.findById(dataSourceId, primary);
@@ -759,6 +801,7 @@ 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);
return;
}
@@ -783,6 +826,18 @@ 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}`);
+ }
+ }
+
let connection: TAppConnection | null = null;
if (dataSource.connection) connection = await decryptAppConnection(dataSource.connection, kmsService);
@@ -797,15 +852,30 @@ export const secretScanningV2QueueServiceFactory = ({
await writeTextToFile(configPath, config.content);
}
- const findingsPayload = await factory.getDiffScanFindingsPayload({
- dataSource: {
- ...dataSource,
- connection
- } as TSecretScanningDataSourceWithConnection,
- resourceName: resource.name,
- payload,
- configPath
- });
+ let findingsPayload: TFindingsPayload;
+ let pullRequestCheckResult: TPullRequestCheckRunResult | undefined;
+
+ if (pullRequestScan) {
+ const { findings, scannedCommitCount, totalCommitCount } = await scanGitHubPullRequest({
+ payload: pullRequestScan,
+ resourceName: resource.name,
+ configPath
+ });
+
+ findingsPayload = findings;
+ // Judged on every finding in the pull request's commits, including ones an earlier push scan already saved.
+ pullRequestCheckResult = getPullRequestScanCheckRunResult({ findings, scannedCommitCount, totalCommitCount });
+ } else {
+ findingsPayload = 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[] = [];
@@ -843,6 +913,8 @@ export const secretScanningV2QueueServiceFactory = ({
return;
}
+ if (pullRequestCheckResult) await reportPullRequestCheck(pullRequestCheckResult);
+
const newFindings = allFindings.filter((finding) => finding.scanId === scanId);
sendScanTelemetry(dataSource, {
@@ -901,6 +973,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);
return;
}
@@ -910,6 +983,8 @@ export const secretScanningV2QueueServiceFactory = ({
const failed = await markScanAsFailed({ scanId, statusMessage: errorMessage });
if (failed) {
+ await reportPullRequestCheck(getPullRequestScanFailedCheckRunResult(errorMessage));
+
await queueService.queue(
QueueName.SecretScanningV2,
QueueJobs.SecretScanningV2SendNotification,
@@ -1081,6 +1156,20 @@ 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 queueService.queue(
QueueName.SecretScanningV2,
QueueJobs.SecretScanningV2SendNotification,
@@ -1176,40 +1265,41 @@ export const secretScanningV2QueueServiceFactory = ({
{ concurrency: 2 }
);
- queueService.start(QueueName.SecretScanningV2, async (job) => {
- // We are keeping this for now because once deployed, the queue might still have
- // full scan and diff scan messages in it and need to be processed.
- if (job.name === QueueJobs.SecretScanningV2FullScan) {
- await handleFullScan(job as Parameters<typeof handleFullScan>[0]);
- } else if (job.name === QueueJobs.SecretScanningV2DiffScan) {
- await handleDiffScan(job as Parameters<typeof handleDiffScan>[0]);
- } else if (job.name === QueueJobs.SecretScanningV2SendNotification) {
- await handleSendNotification(job as Parameters<typeof handleSendNotification>[0]);
- }
- });
-
const queueResourceFullScan = async ({
dataSourceId,
- resourcePayload
+ resourcePayload,
+ trigger
}: {
dataSourceId: string;
resourcePayload: Pick<TSecretScanningResourcesInsert, "externalId" | "name">;
+ trigger: SecretScanningScanTrigger.Push | SecretScanningScanTrigger.PullRequest;
}) => {
try {
- const scan = await secretScanningV2DAL.resources.transaction(async (tx) => {
- const [resource] = await secretScanningV2DAL.resources.upsert(
+ const { resource, scan } = await secretScanningV2DAL.resources.transaction(async (tx) => {
+ const [upsertedResource] = await secretScanningV2DAL.resources.upsert(
[{ ...resourcePayload, dataSourceId }],
["externalId", "dataSourceId"],
tx
);
- return secretScanningV2DAL.scans.create(
- { resourceId: resource.id, type: SecretScanningScanType.Historical },
+ const createdScan = await secretScanningV2DAL.scans.create(
+ { resourceId: upsertedResource.id, type: SecretScanningScanType.Historical, trigger },
tx
);
+
+ return { resource: upsertedResource, scan: createdScan };
});
- await enqueueFullScanJob(scan, dataSourceId);
+ try {
+ await enqueueFullScanJob(scan, dataSourceId);
+ } catch (error) {
+ logger.error(
+ error,
+ `secretScanningV2Queue: Failed to submit full scan for discovered resource, leaving it for redelivery [scanId=${scan.id}] [dataSourceId=${dataSourceId}] [resourceExternalId=${resourcePayload.externalId}]`
+ );
+ }
+
+ return resource;
} catch (error) {
logger.error(
error,
@@ -1218,6 +1308,126 @@ 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;
+ }) => {
+ if (dataSource.isHistoricalScanEnabled) {
+ return queueResourceFullScan({ dataSourceId: dataSource.id, resourcePayload, trigger });
+ }
+
+ const [resource] = await secretScanningV2DAL.resources.upsert(
+ [{ ...resourcePayload, dataSourceId: dataSource.id }],
+ ["externalId", "dataSourceId"]
+ );
+
+ return resource;
+ };
+
+ /**
+ * 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.
+ */
+ const queuePullRequestScan = async ({
+ scanId,
+ dataSourceId,
+ resourceId,
+ payload
+ }: {
+ scanId: string;
+ dataSourceId: string;
+ resourceId: string;
+ payload: TGitHubPullRequestScanPayload;
+ }) => {
+ const logDetails = `[dataSourceId=${dataSourceId}] [scanId=${scanId}] [resourceId=${resourceId}] [checkRunId=${payload.checkRunId}]`;
+
+ try {
+ await secretScanningV2DAL.scans.create({
+ // @ts-expect-error id is generated before the insert because the check run 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
+ });
+
+ await queueService.queue(
+ QueueName.SecretScanningV2RealtimeScan,
+ QueueJobs.SecretScanningV2DiffScan,
+ {
+ payload,
+ dataSourceId,
+ dataSourceType: SecretScanningDataSource.GitHub,
+ scanId,
+ resourceId
+ },
+ {
+ jobId: scanId,
+ removeOnFail: true
+ }
+ );
+ } catch (error) {
+ logger.error(error, `secretScanningV2Queue: Failed to queue pull request 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}`);
+ }
+
+ await tryCompletePullRequestCheckRun({
+ installationId: payload.installationId,
+ repositoryFullName: payload.repository.full_name,
+ checkRunId: payload.checkRunId,
+ result: getPullRequestScanFailedCheckRunResult(statusMessage)
+ });
+ }
+ };
+
+ const githubPullRequestEvents = githubPullRequestEventsFactory({
+ secretScanningV2DAL,
+ discoverResource,
+ queuePullRequestScan
+ });
+
+ queueService.start(QueueName.SecretScanningV2, async (job) => {
+ // We are keeping this for now because once deployed, the queue might still have
+ // full scan and diff scan messages in it and need to be processed.
+ if (job.name === QueueJobs.SecretScanningV2FullScan) {
+ await handleFullScan(job as Parameters<typeof handleFullScan>[0]);
+ } else if (job.name === QueueJobs.SecretScanningV2DiffScan) {
+ 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);
+ }
+ });
+
+ // 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 }
+ });
+ };
+
// A push from a repository with no resource row means it was added after setup, so discovery decides
// whether it joins the data source. Pushes to known repositories are scanned only when new commits are.
const handleResourcePushEvent = async ({
@@ -1264,7 +1474,11 @@ export const secretScanningV2QueueServiceFactory = ({
// The historical scan covers the pushed commits too, so it replaces the diff scan.
if (dataSource.isHistoricalScanEnabled) {
- await queueResourceFullScan({ dataSourceId: dataSource.id, resourcePayload });
+ await queueResourceFullScan({
+ dataSourceId: dataSource.id,
+ resourcePayload,
+ trigger: SecretScanningScanTrigger.Push
+ });
return;
}
@@ -1282,6 +1496,7 @@ export const secretScanningV2QueueServiceFactory = ({
return {
queueDataSourceFullScan,
queueResourceDiffScan,
+ queueGitHubPullRequestEvent,
handleResourcePushEvent
};
};
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-schemas.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-schemas.ts
index baedfb0103..13ec7ef586 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-schemas.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-schemas.ts
@@ -6,7 +6,10 @@ import {
SecretScanningResourcesSchema,
SecretScanningScansSchema
} from "@app/db/schemas";
-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 { SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-maps";
import { SecretScanningDataSources } from "@app/lib/api-docs";
import { slugSchema } from "@app/server/lib/schemas";
@@ -127,5 +130,9 @@ export const SecretScanningResourceSchema = SecretScanningResourcesSchema;
export const SecretScanningScanSchema = SecretScanningScansSchema.omit({
lastScannedCommit: true,
lastScannedCommitDigest: true,
- progressUpdatedAt: true
+ progressUpdatedAt: true,
+ metadata: true
+}).extend({
+ // Null for scans created before the trigger was recorded.
+ trigger: z.nativeEnum(SecretScanningScanTrigger).nullable().optional()
});
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 b133911a92..6555814959 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
@@ -14,7 +14,8 @@ import { githubSecretScanningService } from "@app/ee/services/secret-scanning-v2
import { GitLabDataSourceScope } from "@app/ee/services/secret-scanning-v2/gitlab/gitlab-secret-scanning-enums";
import {
SecretScanningDataSource,
- SecretScanningFindingStatus
+ SecretScanningFindingStatus,
+ SecretScanningScanTrigger
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import { SECRET_SCANNING_FACTORY_MAP } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-factory";
import {
@@ -85,7 +86,7 @@ export type TSecretScanningV2ServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
secretScanningV2Queue: Pick<
TSecretScanningV2QueueServiceFactory,
- "queueDataSourceFullScan" | "queueResourceDiffScan" | "handleResourcePushEvent"
+ "queueDataSourceFullScan" | "queueResourceDiffScan" | "queueGitHubPullRequestEvent" | "handleResourcePushEvent"
>;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "acquireLock">;
@@ -730,6 +731,7 @@ export const secretScanningV2ServiceFactory = ({
connection
} as TSecretScanningDataSourceWithConnection,
{
+ trigger: SecretScanningScanTrigger.Manual,
resourceExternalId,
triggeredByUserId: actor.type === ActorType.USER ? actor.id : undefined
}
@@ -884,6 +886,7 @@ export const secretScanningV2ServiceFactory = ({
try {
await secretScanningV2Queue.queueDataSourceFullScan(dataSourceWithConnection, {
+ trigger: SecretScanningScanTrigger.ResourcesAdded,
triggeredByUserId: actor.type === ActorType.USER ? actor.id : undefined,
shouldScanResource: (resource) => newExternalIds.has(resource.externalId)
});
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 4d2cc6342c..cae6f6ef39 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -17,6 +17,7 @@ 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 {
TQueueSecretScanningDataSourceFullScan,
TQueueSecretScanningResourceDiffScan,
@@ -189,6 +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",
CaOrderCertificateForSubscriber = "ca-order-certificate-for-subscriber",
CaIssueCertificateFromProfile = "ca-issue-certificate-from-profile",
PkiSubscriberDailyAutoRenewal = "pki-subscriber-daily-auto-renewal",
@@ -495,6 +497,10 @@ export type TQueueJobTypes = {
| {
name: QueueJobs.SecretScanningV2SendNotification;
payload: TQueueSecretScanningSendNotification;
+ }
+ | {
+ name: QueueJobs.SecretScanningV2GitHubPullRequestEvent;
+ payload: TQueueGitHubPullRequestEvent;
};
[QueueName.SecretScanningV2FullScan]: {
name: QueueJobs.SecretScanningV2FullScan;
diff --git a/backend/src/server/plugins/secret-scanner-v2.ts b/backend/src/server/plugins/secret-scanner-v2.ts
index 697fa027ab..58e6fe5659 100644
--- a/backend/src/server/plugins/secret-scanner-v2.ts
+++ b/backend/src/server/plugins/secret-scanner-v2.ts
@@ -31,6 +31,18 @@ export const registerSecretScanningV2Webhooks = async (server: FastifyZodProvide
const { payload } = context;
await server.services.secretScanningV2.github.handlePushEvent(payload as PushEvent);
});
+
+ app.on(["pull_request.opened", "pull_request.synchronize", "pull_request.reopened"], async (context) => {
+ await server.services.secretScanningV2.github.handlePullRequestEvent(context.payload, context.id);
+ });
+
+ app.on("check_run.rerequested", async (context) => {
+ await server.services.secretScanningV2.github.handleCheckRunRerequestedEvent(context.payload, context.id);
+ });
+
+ app.on("check_suite.rerequested", async (context) => {
+ await server.services.secretScanningV2.github.handleCheckSuiteRerequestedEvent(context.payload, context.id);
+ });
};
const probot = new Probot({
diff --git a/docs/documentation/platform/secret-scanning/github.mdx b/docs/documentation/platform/secret-scanning/github.mdx
index 4d1107f6b0..d72a2b0f28 100644
--- a/docs/documentation/platform/secret-scanning/github.mdx
+++ b/docs/documentation/platform/secret-scanning/github.mdx
@@ -56,3 +56,19 @@ To scan your GitHub repositories for leaked secrets, create a GitHub [data sourc
![Findings Page](/images/platform/secret-scanning/github/github-data-source-step-8.png)
</Step>
</Steps>
+
+## Pull request checks
+
+If **Scan New Commits** is on for a GitHub data source, Infisical scans the commits of each pull request opened against a repository in the data source. Infisical reports the result as a check named **Infisical Secret Scanning** on the pull request, and scans the pull request again each time someone pushes to it.
+
+- If Infisical finds a secret in any commit of the pull request, the check fails and marks the file and line of each secret
+- If Infisical can't finish the scan, the check fails, and you can re-run the check from the pull request
+- If Infisical finds no secrets, the check passes
+
+To stop a pull request that contains a secret from being merged, [require the check in a branch protection rule](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-status-checks-before-merging).
+
+If a finding is a false positive, add it to the allowlist in your [scanning configuration](/documentation/platform/secret-scanning/configuration), then re-run the check.
+
+<Note>
+ If your GitHub organization installed the app for your [GitHub Radar Connection](/integrations/app-connections/github-radar) before pull request checks were available, an organization owner has to accept the app's new permissions in GitHub before Infisical can check pull requests.
+</Note>
diff --git a/docs/integrations/app-connections/github-radar.mdx b/docs/integrations/app-connections/github-radar.mdx
index e6f3f5393d..ff16aa25d7 100644
--- a/docs/integrations/app-connections/github-radar.mdx
+++ b/docs/integrations/app-connections/github-radar.mdx
@@ -45,13 +45,18 @@ Infisical supports GitHub App installation for creating a GitHub Radar Connectio
![github radar app webhook](/images/app-connections/github-radar/self-hosted-github-radar-step-3.png)
Set the following repository permissions:
+ - **Checks**: `Read and write`
- **Contents**: `Read-only`
- **Metadata**: `Read-only`
+ - **Pull requests**: `Read-only`
![github radar app permissions 1](/images/app-connections/github-radar/self-hosted-github-radar-step-4.png)
![github radar app permissions 2](/images/app-connections/github-radar/self-hosted-github-radar-step-5.png)
Subscribe to the following events:
+ - **Check run**
+ - **Check suite**
+ - **Pull request**
- **Push**
![github radar app events](/images/app-connections/github-radar/self-hosted-github-radar-step-6.png)