Skip to content

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

12.6 KB
Raw Blame
import { join } from "path";
import RE2 from "re2";

import { SecretScanningFindingSeverity } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-enums";
import {
  assertProviderRepositorySizeWithinLimit,
  cloneRepository,
  convertPatchLineToFileLineNumber,
  isDataSourceWebhookRequired,
  replaceNonChangesWithNewlines,
  toFindingDetails
} from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-fns";
import {
  TSecretScanningFactoryGetDiffScanFindingsPayload,
  TSecretScanningFactoryGetDiffScanResourcePayload,
  TSecretScanningFactoryGetFullScanPath,
  TSecretScanningFactoryInitialize,
  TSecretScanningFactoryListRawResources,
  TSecretScanningFactoryPostInitialization,
  TSecretScanningFactorySetupWebhook,
  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 { request } from "@app/lib/config/request";
import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { BasicRepositoryRegex } from "@app/lib/regex";
import {
  getBitbucketUser,
  listBitbucketRepositories,
  TBitbucketConnection
} from "@app/services/app-connection/bitbucket";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";

import {
  TBitbucketDataSourceCredentials,
  TBitbucketDataSourceInput,
  TBitbucketDataSourceWithConnection,
  TQueueBitbucketResourceDiffScan
} from "./bitbucket-secret-scanning-types";

const GitCommitShaRegex = new RE2(/^[a-f0-9]{7,40}$/);
const ExtractEmailRegex = new RE2(/<(.*)>/);

export const BitbucketSecretScanningFactory = () => {
  const initialize: TSecretScanningFactoryInitialize<
    TBitbucketDataSourceInput,
    TBitbucketConnection,
    TBitbucketDataSourceCredentials
  > = async ({ connection, payload }, callback) => {
    if (!isDataSourceWebhookRequired(payload)) return callback({});

    const cfg = getConfig();

    const { email, apiToken } = connection.credentials;
    const authHeader = `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`;

    const { data } = await request.post<{ uuid: string }>(
      `${IntegrationUrls.BITBUCKET_API_URL}/2.0/workspaces/${encodeURIComponent(payload.config.workspaceSlug)}/hooks`,
      {
        description: "Infisical webhook for push events",
        url: `${cfg.SITE_URL}/secret-scanning/webhooks/bitbucket`,
        active: false,
        events: ["repo:push"]
      },
      {
        headers: {
          Authorization: authHeader,
          Accept: "application/json"
        }
      }
    );

    return callback({
      credentials: { webhookId: data.uuid, webhookSecret: alphaNumericNanoId(64) }
    });
  };

  const postInitialization: TSecretScanningFactoryPostInitialization<
    TBitbucketDataSourceInput,
    TBitbucketConnection,
    TBitbucketDataSourceCredentials
  > = async ({ dataSourceId, credentials, connection, payload }) => {
    if (!credentials) return;

    const { email, apiToken } = connection.credentials;
    const { webhookId, webhookSecret } = credentials;

    const authHeader = `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`;

    const cfg = getConfig();
    const newWebhookUrl = `${cfg.SITE_URL}/secret-scanning/webhooks/bitbucket?dataSourceId=${dataSourceId}`;

    await request.put(
      `${IntegrationUrls.BITBUCKET_API_URL}/2.0/workspaces/${encodeURIComponent(payload.config.workspaceSlug)}/hooks/${encodeURIComponent(webhookId)}`,
      {
        description: "Infisical webhook for push events",
        url: newWebhookUrl,
        active: true,
        events: ["repo:push"],
        secret: webhookSecret
      },
      {
        headers: {
          Authorization: authHeader,
          Accept: "application/json"
        }
      }
    );
  };

  const teardown: TSecretScanningFactoryTeardown<
    TBitbucketDataSourceWithConnection,
    TBitbucketDataSourceCredentials
  > = async ({ credentials, dataSource }) => {
    if (!credentials) return;

    const {
      connection: {
        credentials: { email, apiToken }
      },
      config
    } = dataSource;
    const { webhookId } = credentials;

    const authHeader = `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`;

    try {
      await request.delete(
        `${IntegrationUrls.BITBUCKET_API_URL}/2.0/workspaces/${encodeURIComponent(config.workspaceSlug)}/hooks/${webhookId}`,
        {
          headers: {
            Authorization: authHeader,
            Accept: "application/json"
          }
        }
      );
    } catch (err) {
      logger.error(`teardown: Bitbucket - Failed to call delete on webhook [webhookId=${webhookId}]`);
    }
  };

  const listRawResources: TSecretScanningFactoryListRawResources<TBitbucketDataSourceWithConnection> = async (
    dataSource
  ) => {
    const {
      connection,
      config: { workspaceSlug }
    } = dataSource;

    const repos = await listBitbucketRepositories(connection, workspaceSlug);

    return repos.map(({ full_name, uuid }) => ({
      name: full_name,
      externalId: uuid
    }));
  };

  const getFullScanPath: TSecretScanningFactoryGetFullScanPath<TBitbucketDataSourceWithConnection> = async ({
    dataSource,
    resourceName,
    tempFolder
  }) => {
    const {
      connection: {
        credentials: { apiToken, email }
      }
    } = dataSource;

    const repoPath = join(tempFolder, "repo.git");

    if (!BasicRepositoryRegex.test(resourceName)) {
      throw new Error("Invalid Bitbucket repository name");
    }

    const { username } = await getBitbucketUser({ email, apiToken });

    // Checked before the clone: measuring afterwards means the network, wall clock and ephemeral
    // disk have already been spent. Bitbucket reports `size` in bytes.
    // `resourceName` is `workspace/repo`: the slash is a path separator here, so it must survive
    // into the URL. BasicRepositoryRegex above already constrains both segments to URL-safe
    // characters, which is what makes interpolating it directly safe.
    await assertProviderRepositorySizeWithinLimit(resourceName, async () => {
      const { data: repository } = await request.get<{ size?: number | null }>(
        `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${resourceName}`,
        {
          headers: {
            Authorization: `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`,
            Accept: "application/json"
          }
        }
      );

      return repository.size;
    });

    await cloneRepository({
      cloneUrl: `https://${encodeURIComponent(username)}:${apiToken}@bitbucket.org/${resourceName}.git`,
      repoPath
    });

    return repoPath;
  };

  const getDiffScanResourcePayload: TSecretScanningFactoryGetDiffScanResourcePayload<
    TQueueBitbucketResourceDiffScan["payload"]
  > = ({ repository }) => {
    return {
      name: repository.full_name,
      externalId: repository.uuid
    };
  };

  const getDiffScanFindingsPayload: TSecretScanningFactoryGetDiffScanFindingsPayload<
    TBitbucketDataSourceWithConnection,
    TQueueBitbucketResourceDiffScan["payload"]
  > = async ({ dataSource, payload, resourceName, configPath }) => {
    const {
      connection: {
        credentials: { apiToken, email }
      }
    } = dataSource;

    const { push, repository } = payload;

    const allFindings: SecretMatch[] = [];

    const authHeader = `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`;

    for (const change of push.changes) {
      for (const commit of change.commits) {
        if (!GitCommitShaRegex.test(commit.hash)) {
          throw new Error("Invalid commit hash");
        }

        // eslint-disable-next-line no-await-in-loop
        const { data: diffstat } = await request.get<{
          values: {
            status: "added" | "modified" | "removed" | "renamed";
            new?: { path: string };
            old?: { path: string };
          }[];
        }>(
          `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${encodeURIComponent(repository.full_name)}/diffstat/${commit.hash}`,
          {
            headers: {
              Authorization: authHeader,
              Accept: "application/json"
            }
          }
        );

        // eslint-disable-next-line no-continue
        if (!diffstat.values) continue;

        for (const file of diffstat.values) {
          if ((file.status === "added" || file.status === "modified") && file.new?.path) {
            const filePath = file.new.path;

            // eslint-disable-next-line no-await-in-loop
            const { data: patch } = await request.get<string>(
              `https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(repository.full_name)}/diff/${commit.hash}`,
              {
                params: {
                  path: filePath
                },
                headers: {
                  Authorization: authHeader
                },
                responseType: "text"
              }
            );

            // eslint-disable-next-line no-continue
            if (!patch) continue;

            // eslint-disable-next-line no-await-in-loop
            const findings = await scanContentAndGetFindings(replaceNonChangesWithNewlines(patch), configPath);

            const adjustedFindings = findings.map((finding) => {
              const startLine = convertPatchLineToFileLineNumber(patch, finding.StartLine);
              const endLine =
                finding.StartLine === finding.EndLine
                  ? startLine
                  : convertPatchLineToFileLineNumber(patch, finding.EndLine);
              const startColumn = finding.StartColumn - 1; // subtract 1 for +
              const endColumn = finding.EndColumn - 1; // subtract 1 for +
              const authorName = commit.author.user?.display_name || commit.author.raw.split(" <")[0];
              const emailMatch = commit.author.raw.match(ExtractEmailRegex);
              const authorEmail = emailMatch?.[1] ?? "";

              return {
                ...finding,
                StartLine: startLine,
                EndLine: endLine,
                StartColumn: startColumn,
                EndColumn: endColumn,
                File: filePath,
                Commit: commit.hash,
                Author: authorName,
                Email: authorEmail,
                Message: commit.message,
                Fingerprint: `${commit.hash}:${filePath}:${finding.RuleID}:${startLine}:${startColumn}`,
                Date: commit.date,
                Attributes: {
                  ...finding.Attributes,
                  url: `https://bitbucket.org/${resourceName}/src/${commit.hash}/${filePath}#lines-${startLine}`
                }
              };
            });

            allFindings.push(...adjustedFindings);
          }
        }
      }
    }

    return {
      findings: allFindings.map((finding) => ({
        details: toFindingDetails(finding),
        fingerprint: finding.Fingerprint,
        severity: SecretScanningFindingSeverity.High,
        rule: finding.RuleID
      }))
    };
  };

  const setupWebhook: TSecretScanningFactorySetupWebhook<
    TBitbucketDataSourceWithConnection,
    TBitbucketDataSourceCredentials
  > = async ({ dataSource: { id, connection, config } }) => {
    const { email, apiToken } = connection.credentials;
    const authHeader = `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`;
    const webhookSecret = alphaNumericNanoId(64);

    const { data } = await request.post<{ uuid: string }>(
      `${IntegrationUrls.BITBUCKET_API_URL}/2.0/workspaces/${encodeURIComponent(config.workspaceSlug)}/hooks`,
      {
        description: "Infisical webhook for push events",
        url: `${getConfig().SITE_URL}/secret-scanning/webhooks/bitbucket?dataSourceId=${id}`,
        active: true,
        events: ["repo:push"],
        secret: webhookSecret
      },
      {
        headers: {
          Authorization: authHeader,
          Accept: "application/json"
        }
      }
    );

    return { webhookId: data.uuid, webhookSecret };
  };

  const validateConfigUpdate: TSecretScanningFactoryValidateConfigUpdate<
    TBitbucketDataSourceInput["config"],
    TBitbucketDataSourceWithConnection
  > = async () => {
    // no validation required
  };

  return {
    initialize,
    postInitialization,
    listRawResources,
    getFullScanPath,
    getDiffScanResourcePayload,
    getDiffScanFindingsPayload,
    teardown,
    setupWebhook,
    validateConfigUpdate
  };
};