Skip to content

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

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

import { TDbClient } from "@app/db";
import { TableName, TPkiSigners } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn/string";
import { ormify, selectAllTableCols } from "@app/lib/knex";

export type TSignerWithCertificate = TPkiSigners & {
  certificateCommonName: string | null;
  certificateSerialNumber: string | null;
  certificateNotAfter: Date | null;
  certificateNotBefore: Date | null;
  certificateKeyAlgorithm: string | null;
  certificateKeySource: string | null;
  certificateHsmConnectorId: string | null;
  certificateStatus: string | null;
  certificateCaId: string | null;
  approvalPolicyName: string | null;
};

export type TSignerWithCertificateSummary = TPkiSigners & {
  certificateCommonName: string | null;
  certificateSerialNumber: string | null;
  certificateNotAfter: Date | null;
  certificateStatus: string | null;
  approvalPolicyName: string | null;
};

export type TSignerDALFactory = ReturnType<typeof signerDALFactory>;

export const signerDALFactory = (db: TDbClient) => {
  const orm = ormify(db, TableName.PkiSigners);

  const findByIdWithCertificate = async (signerId: string, tx?: Knex): Promise<TSignerWithCertificate | undefined> => {
    try {
      const result = await (tx || db.replicaNode())(TableName.PkiSigners)
        .leftJoin(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)
        .leftJoin(
          TableName.ApprovalPolicies,
          `${TableName.PkiSigners}.approvalPolicyId`,
          `${TableName.ApprovalPolicies}.id`
        )
        .select(selectAllTableCols(TableName.PkiSigners))
        .select(
          db.ref("commonName").withSchema(TableName.Certificate).as("certificateCommonName"),
          db.ref("serialNumber").withSchema(TableName.Certificate).as("certificateSerialNumber"),
          db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"),
          db.ref("notBefore").withSchema(TableName.Certificate).as("certificateNotBefore"),
          db.ref("keyAlgorithm").withSchema(TableName.Certificate).as("certificateKeyAlgorithm"),
          db.ref("keySource").withSchema(TableName.Certificate).as("certificateKeySource"),
          db.ref("hsmConnectorId").withSchema(TableName.Certificate).as("certificateHsmConnectorId"),
          db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),
          db.ref("caId").withSchema(TableName.Certificate).as("certificateCaId"),
          db.ref("name").withSchema(TableName.ApprovalPolicies).as("approvalPolicyName")
        )
        .where(`${TableName.PkiSigners}.id`, signerId)
        .first();

      return result as TSignerWithCertificate | undefined;
    } catch (error) {
      throw new DatabaseError({ error, name: "FindSignerByIdWithCertificate" });
    }
  };

  const findByProjectId = async (
    projectId: string,
    {
      offset = 0,
      limit = 25,
      search,
      signerIds
    }: {
      offset?: number;
      limit?: number;
      search?: string;
      signerIds?: string[];
    },
    tx?: Knex
  ) => {
    try {
      let query: Knex.QueryBuilder = (tx || db.replicaNode())(TableName.PkiSigners)
        .leftJoin(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)
        .leftJoin(
          TableName.ApprovalPolicies,
          `${TableName.PkiSigners}.approvalPolicyId`,
          `${TableName.ApprovalPolicies}.id`
        )
        .select(selectAllTableCols(TableName.PkiSigners))
        .select(
          db.ref("commonName").withSchema(TableName.Certificate).as("certificateCommonName"),
          db.ref("serialNumber").withSchema(TableName.Certificate).as("certificateSerialNumber"),
          db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"),
          db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),
          db.ref("name").withSchema(TableName.ApprovalPolicies).as("approvalPolicyName")
        )
        .where(`${TableName.PkiSigners}.projectId`, projectId);

      if (signerIds) {
        query = query.whereIn(`${TableName.PkiSigners}.id`, signerIds);
      }

      if (search) {
        const sanitizedSearch = `%${sanitizeSqlLikeString(search)}%`;
        query = query.where((qb) => {
          void qb
            .whereILike(`${TableName.PkiSigners}.name`, sanitizedSearch)
            .orWhereILike(`${TableName.Certificate}.commonName`, sanitizedSearch);
        });
      }

      return (await query
        .orderBy(`${TableName.PkiSigners}.createdAt`, "desc")
        .offset(offset)
        .limit(limit)) as TSignerWithCertificateSummary[];
    } catch (error) {
      throw new DatabaseError({ error, name: "FindSignersByProjectId" });
    }
  };

  const countByProjectId = async (projectId: string, search?: string, signerIds?: string[], tx?: Knex) => {
    try {
      let query: Knex.QueryBuilder = (tx || db.replicaNode())(TableName.PkiSigners).where(
        `${TableName.PkiSigners}.projectId`,
        projectId
      );

      if (signerIds) {
        query = query.whereIn(`${TableName.PkiSigners}.id`, signerIds);
      }

      if (search) {
        const sanitizedSearch = `%${sanitizeSqlLikeString(search)}%`;
        query = query
          .leftJoin(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)
          .where((qb) => {
            void qb
              .whereILike(`${TableName.PkiSigners}.name`, sanitizedSearch)
              .orWhereILike(`${TableName.Certificate}.commonName`, sanitizedSearch);
          });
      }

      const countResult = (await query.count("* as count")) as { count: string | number }[];
      return Number(countResult[0].count);
    } catch (error) {
      throw new DatabaseError({ error, name: "CountSignersByProjectId" });
    }
  };

  const findByStatusWithCertificate = async (status: string, tx?: Knex): Promise<TSignerWithCertificate[]> => {
    try {
      const result = await (tx || db.replicaNode())(TableName.PkiSigners)
        .leftJoin(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)
        .leftJoin(
          TableName.ApprovalPolicies,
          `${TableName.PkiSigners}.approvalPolicyId`,
          `${TableName.ApprovalPolicies}.id`
        )
        .select(selectAllTableCols(TableName.PkiSigners))
        .select(
          db.ref("commonName").withSchema(TableName.Certificate).as("certificateCommonName"),
          db.ref("serialNumber").withSchema(TableName.Certificate).as("certificateSerialNumber"),
          db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"),
          db.ref("notBefore").withSchema(TableName.Certificate).as("certificateNotBefore"),
          db.ref("keyAlgorithm").withSchema(TableName.Certificate).as("certificateKeyAlgorithm"),
          db.ref("keySource").withSchema(TableName.Certificate).as("certificateKeySource"),
          db.ref("hsmConnectorId").withSchema(TableName.Certificate).as("certificateHsmConnectorId"),
          db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"),
          db.ref("caId").withSchema(TableName.Certificate).as("certificateCaId"),
          db.ref("name").withSchema(TableName.ApprovalPolicies).as("approvalPolicyName")
        )
        .where(`${TableName.PkiSigners}.status`, status);

      return result as TSignerWithCertificate[];
    } catch (error) {
      throw new DatabaseError({ error, name: "FindSignersByStatusWithCertificate" });
    }
  };

  const findByIdForUpdate = async (signerId: string, tx: Knex): Promise<TPkiSigners | undefined> => {
    try {
      return (await tx(TableName.PkiSigners).where({ id: signerId }).forUpdate().first()) as TPkiSigners | undefined;
    } catch (error) {
      throw new DatabaseError({ error, name: "FindSignerByIdForUpdate" });
    }
  };

  const findOneInOrgByCurrentHsmPublicKey = async (
    projectId: string,
    hsmPublicKeySpki: Buffer,
    excludeSignerId: string | undefined,
    tx?: Knex
  ): Promise<TPkiSigners | undefined> => {
    try {
      const conn = tx || db.replicaNode();
      let query = conn(TableName.PkiSigners)
        .join(TableName.Certificate, `${TableName.PkiSigners}.certificateId`, `${TableName.Certificate}.id`)
        .join(TableName.Project, `${TableName.PkiSigners}.projectId`, `${TableName.Project}.id`)
        .where(`${TableName.Project}.orgId`, conn(TableName.Project).select("orgId").where("id", projectId))
        .where(`${TableName.Certificate}.hsmPublicKeySpki`, hsmPublicKeySpki)
        .select(selectAllTableCols(TableName.PkiSigners));
      if (excludeSignerId) {
        query = query.whereNot(`${TableName.PkiSigners}.id`, excludeSignerId);
      }
      return (await query.first()) as TPkiSigners | undefined;
    } catch (error) {
      throw new DatabaseError({ error, name: "FindSignerInOrgByCurrentHsmPublicKey" });
    }
  };

  return {
    ...orm,
    findByIdWithCertificate,
    findByStatusWithCertificate,
    findByProjectId,
    countByProjectId,
    findOneInOrgByCurrentHsmPublicKey,
    findByIdForUpdate
  };
};