Skip to content

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

13.2 KB
Raw Blame
import { Knex } from "knex";

import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { TSecretSyncs } from "@app/db/schemas/secret-syncs";
import { DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, prependTableNameToFindFilter, selectAllTableCols } from "@app/lib/knex";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";

export type TSecretSyncDALFactory = ReturnType<typeof secretSyncDALFactory>;

type SecretSyncFindFilter = Parameters<typeof buildFindFilter<TSecretSyncs>>[0];

// Resolving a folder path loads every folder in the sync's environment. Callers that don't need the
// path pass includeFolderPath: false, and the row omits `folder`. `folder: null` means the path was
// resolved and the folder is gone, which secret loading treats as "folder no longer exists".
type TFolderPathOptions<IncludeFolderPath extends boolean = true> = {
  includeFolderPath?: IncludeFolderPath;
};

const baseSecretSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: SecretSyncFindFilter; tx?: Knex }) => {
  const query = (tx || db.replicaNode())(TableName.SecretSync)
    .leftJoin(TableName.SecretFolder, `${TableName.SecretSync}.folderId`, `${TableName.SecretFolder}.id`)
    .leftJoin(TableName.Environment, function joinActiveEnvForFolder() {
      this.on(`${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`).andOnNull(
        `${TableName.Environment}.deleteAfter`
      );
    })
    .join(TableName.AppConnection, `${TableName.SecretSync}.connectionId`, `${TableName.AppConnection}.id`)
    .join(TableName.Project, `${TableName.SecretSync}.projectId`, `${TableName.Project}.id`)
    .whereNull(`${TableName.Project}.deleteAfter`)
    .select(selectAllTableCols(TableName.SecretSync))
    .select(
      // environment
      db.ref("name").withSchema(TableName.Environment).as("envName"),
      db.ref("id").withSchema(TableName.Environment).as("envId"),
      db.ref("slug").withSchema(TableName.Environment).as("envSlug"),
      // entire connection
      db.ref("name").withSchema(TableName.AppConnection).as("connectionName"),
      db.ref("method").withSchema(TableName.AppConnection).as("connectionMethod"),
      db.ref("app").withSchema(TableName.AppConnection).as("connectionApp"),
      db.ref("orgId").withSchema(TableName.AppConnection).as("connectionOrgId"),
      db.ref("encryptedCredentials").withSchema(TableName.AppConnection).as("connectionEncryptedCredentials"),
      db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),
      db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),
      db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),
      db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("connectionGatewayPoolId"),
      db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),
      db.ref("isAutoRotationEnabled").withSchema(TableName.AppConnection).as("connectionIsAutoRotationEnabled"),
      db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),
      db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),
      db
        .ref("isPlatformManagedCredentials")
        .withSchema(TableName.AppConnection)
        .as("connectionIsPlatformManagedCredentials")
    );

  if (filter) {
    /* eslint-disable @typescript-eslint/no-misused-promises */
    void query.where(buildFindFilter(prependTableNameToFindFilter(TableName.SecretSync, filter)));
  }

  return query;
};

const expandSecretSync = (
  secretSync: Awaited<ReturnType<typeof baseSecretSyncQuery>>[number],
  folder?: Awaited<ReturnType<TSecretFolderDALFactory["findSecretPathByFolderIds"]>>[number]
) => {
  const {
    envId,
    envName,
    envSlug,
    connectionApp,
    connectionName,
    connectionId,
    connectionOrgId,
    connectionEncryptedCredentials,
    connectionMethod,
    connectionDescription,
    connectionCreatedAt,
    connectionUpdatedAt,
    connectionVersion,
    connectionIsPlatformManagedCredentials,
    connectionGatewayId,
    connectionGatewayPoolId,
    connectionProjectId,
    connectionIsAutoRotationEnabled,
    ...el
  } = secretSync;

  return {
    ...el,
    connectionId,
    environment: envId ? { id: envId, name: envName, slug: envSlug } : null,
    connection: {
      app: connectionApp,
      id: connectionId,
      name: connectionName,
      orgId: connectionOrgId,
      encryptedCredentials: connectionEncryptedCredentials,
      method: connectionMethod,
      description: connectionDescription,
      createdAt: connectionCreatedAt,
      updatedAt: connectionUpdatedAt,
      version: connectionVersion,
      isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,
      gatewayId: connectionGatewayId,
      gatewayPoolId: connectionGatewayPoolId,
      projectId: connectionProjectId,
      isAutoRotationEnabled: connectionIsAutoRotationEnabled
    },
    folder: folder
      ? {
          id: folder.id,
          path: folder.path
        }
      : null
  };
};

export type TSecretSyncWithFolder = ReturnType<typeof expandSecretSync>;
type TSecretSyncWithoutFolder = Omit<TSecretSyncWithFolder, "folder">;
type TSecretSyncForFolderOption<IncludeFolderPath extends boolean> = IncludeFolderPath extends false
  ? TSecretSyncWithoutFolder
  : TSecretSyncWithFolder;

const withoutFolder = ({ folder, ...rest }: TSecretSyncWithFolder): TSecretSyncWithoutFolder => rest;

const applyFolderOption = <IncludeFolderPath extends boolean>(
  expanded: TSecretSyncWithFolder,
  includeFolderPath: IncludeFolderPath
): TSecretSyncForFolderOption<IncludeFolderPath> =>
  (includeFolderPath ? expanded : withoutFolder(expanded)) as TSecretSyncForFolderOption<IncludeFolderPath>;

export const secretSyncDALFactory = (
  db: TDbClient,
  folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">
) => {
  const secretSyncOrm = ormify(db, TableName.SecretSync);

  const findById = async <IncludeFolderPath extends boolean = true>(
    id: string,
    tx?: Knex,
    { includeFolderPath = true as IncludeFolderPath }: TFolderPathOptions<IncludeFolderPath> = {}
  ): Promise<TSecretSyncForFolderOption<IncludeFolderPath> | undefined> => {
    try {
      const secretSync = await baseSecretSyncQuery({
        filter: { id },
        db,
        tx
      }).first();

      if (secretSync) {
        // TODO (scott): replace with cached folder path once implemented
        const [folderWithPath] =
          includeFolderPath && secretSync.folderId
            ? await folderDAL.findSecretPathByFolderIds(secretSync.projectId, [secretSync.folderId])
            : [];
        return applyFolderOption(expandSecretSync(secretSync, folderWithPath), includeFolderPath);
      }
    } catch (error) {
      throw new DatabaseError({ error, name: "Find by ID - Secret Sync" });
    }
  };

  const create = async (data: Parameters<(typeof secretSyncOrm)["create"]>[0]) => {
    const secretSync = (await secretSyncOrm.transaction(async (tx) => {
      const sync = await secretSyncOrm.create(data, tx);

      return baseSecretSyncQuery({
        filter: { id: sync.id },
        db,
        tx
      }).first();
    }))!;

    // TODO (scott): replace with cached folder path once implemented
    const [folderWithPath] = secretSync.folderId
      ? await folderDAL.findSecretPathByFolderIds(secretSync.projectId, [secretSync.folderId])
      : [];
    return expandSecretSync(secretSync, folderWithPath);
  };

  const updateById = async <IncludeFolderPath extends boolean = true>(
    syncId: string,
    data: Parameters<(typeof secretSyncOrm)["updateById"]>[1],
    { includeFolderPath = true as IncludeFolderPath }: TFolderPathOptions<IncludeFolderPath> = {}
  ): Promise<TSecretSyncForFolderOption<IncludeFolderPath>> => {
    const secretSync = (await secretSyncOrm.transaction(async (tx) => {
      const sync = await secretSyncOrm.updateById(syncId, data, tx);

      return baseSecretSyncQuery({
        filter: { id: sync.id },
        db,
        tx
      }).first();
    }))!;

    // TODO (scott): replace with cached folder path once implemented
    const [folderWithPath] =
      includeFolderPath && secretSync.folderId
        ? await folderDAL.findSecretPathByFolderIds(secretSync.projectId, [secretSync.folderId])
        : [];
    return applyFolderOption(expandSecretSync(secretSync, folderWithPath), includeFolderPath);
  };

  const findOne = async (filter: Parameters<(typeof secretSyncOrm)["findOne"]>[0], tx?: Knex) => {
    try {
      const secretSync = await baseSecretSyncQuery({ filter, db, tx }).first();

      if (secretSync) {
        // TODO (scott): replace with cached folder path once implemented
        const [folderWithPath] = secretSync.folderId
          ? await folderDAL.findSecretPathByFolderIds(secretSync.projectId, [secretSync.folderId])
          : [];
        return expandSecretSync(secretSync, folderWithPath);
      }
    } catch (error) {
      throw new DatabaseError({ error, name: "Find One - Secret Sync" });
    }
  };

  const find = async <IncludeFolderPath extends boolean = true>(
    filter: Parameters<(typeof secretSyncOrm)["find"]>[0],
    tx?: Knex,
    { includeFolderPath = true as IncludeFolderPath }: TFolderPathOptions<IncludeFolderPath> = {}
  ): Promise<TSecretSyncForFolderOption<IncludeFolderPath>[]> => {
    try {
      const secretSyncs = await baseSecretSyncQuery({ filter, db, tx });

      if (!secretSyncs.length) return [];

      const folderRecord: Record<
        string,
        Awaited<ReturnType<TSecretFolderDALFactory["findSecretPathByFolderIds"]>>[number]
      > = {};

      if (includeFolderPath) {
        const foldersWithPath = await folderDAL.findSecretPathByFolderIds(
          secretSyncs[0].projectId,
          secretSyncs.filter((sync) => Boolean(sync.folderId)).map((sync) => sync.folderId!)
        );

        // TODO (scott): replace with cached folder path once implemented
        foldersWithPath.forEach((folder) => {
          if (folder) folderRecord[folder.id] = folder;
        });
      }

      return secretSyncs.map((secretSync) =>
        applyFolderOption(
          expandSecretSync(secretSync, secretSync.folderId ? folderRecord[secretSync.folderId] : undefined),
          includeFolderPath
        )
      );
    } catch (error) {
      throw new DatabaseError({ error, name: "Find - Secret Sync" });
    }
  };

  const findConnectionId = async (id: string, tx?: Knex) => {
    try {
      const secretSync = await (tx || db.replicaNode())(TableName.SecretSync)
        .where({ id })
        .select("connectionId")
        .first<{ connectionId: string } | undefined>();

      return secretSync?.connectionId;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find Connection ID - Secret Sync" });
    }
  };

  const updateAndReturnIds = async (
    filter: Parameters<(typeof secretSyncOrm)["find"]>[0],
    data: Parameters<(typeof secretSyncOrm)["update"]>[1],
    tx?: Knex
  ): Promise<string[]> => {
    try {
      // A sync of a project pending deletion keeps its status, so the daily retry still finds it once restored.
      const rows = await (tx || db)(TableName.SecretSync)
        .where(buildFindFilter(filter))
        .whereNotIn("projectId", db(TableName.Project).whereNotNull("deleteAfter").select("id"))
        .update(data)
        .returning("id");
      return rows.map((r) => r.id);
    } catch (error) {
      throw new DatabaseError({ error, name: "Update And Return IDs - Secret Sync" });
    }
  };

  // Total secret syncs across all of the org's projects (excluding soft-deleted projects), used to
  // enforce the plan's secretSyncLimit at creation time.
  const countByOrgId = async (orgId: string, tx?: Knex) => {
    try {
      const doc = await (tx || db.replicaNode())(TableName.SecretSync)
        .join(TableName.Project, `${TableName.SecretSync}.projectId`, `${TableName.Project}.id`)
        .where(`${TableName.Project}.orgId`, orgId)
        .whereNull(`${TableName.Project}.deleteAfter`)
        .count();
      return Number(doc?.[0]?.count ?? 0);
    } catch (error) {
      throw new DatabaseError({ error, name: "Count By Org ID - Secret Sync" });
    }
  };

  const countByProjectId = async (projectId: string, tx?: Knex) => {
    try {
      const doc = await (tx || db.replicaNode())(TableName.SecretSync).where({ projectId }).count();
      return Number(doc?.[0]?.count ?? 0);
    } catch (error) {
      throw new DatabaseError({ error, name: "Count By Project ID - Secret Sync" });
    }
  };

  const findByDestinationAndOrgId = async (destination: string, orgId: string, tx?: Knex) => {
    try {
      const response = await (tx || db.replicaNode())(TableName.SecretSync)
        .join(TableName.Project, `${TableName.SecretSync}.projectId`, `${TableName.Project}.id`)
        .where(`${TableName.SecretSync}.destination`, destination)
        .where(`${TableName.Project}.orgId`, orgId)
        .select(selectAllTableCols(TableName.SecretSync));

      return response;
    } catch (error) {
      throw new DatabaseError({ error, name: "Find By Destination And Org ID - Secret Sync" });
    }
  };

  return {
    ...secretSyncOrm,
    findById,
    findOne,
    find,
    create,
    updateById,
    findConnectionId,
    updateAndReturnIds,
    countByOrgId,
    countByProjectId,
    findByDestinationAndOrgId
  };
};