Skip to content

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

17.3 KB
Raw Blame
import { type ClickHouseClient } from "@clickhouse/client";
import RE2 from "re2";

import { TDbClient } from "@app/db";
import { IdentityAuthMethod, TableName, TAuditLogs } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ActorType } from "@app/services/auth/auth-type";

import { TPamAuditLogScope } from "./audit-log-dal";
import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, filterableSecretEvents } from "./audit-log-types";

type TAuditLogWithProjectName = TAuditLogs & { projectName: string | null };

type TClickHouseFindArg = {
  orgId: string;
  projectId?: string;
  environment?: string;
  userAgentType?: string;
  startDate: string;
  endDate: string;
  limit?: number;
  offset?: number;
  actorId?: string;
  actorType?: ActorType;
  secretPath?: string;
  secretKey?: string;
  eventType?: EventType[];
  excludeEventType?: EventType[];
  eventMetadata?: Record<string, string>;
  pamScope?: TPamAuditLogScope;
};

type TClickHouseCountByDateArg = {
  orgId: string;
  eventTypes: EventType[];
  startDate: string;
  endDate: string;
};

type TClickHouseDateVolumeRow = {
  date: string;
  count: number;
};

// count() is a UInt64, which ClickHouse quotes as a string in JSON output
type TClickHouseDateVolumeRawRow = Omit<TClickHouseDateVolumeRow, "count"> & { count: string };

type TClickHouseAuthMethodRow = {
  authMethod: IdentityAuthMethod;
  count: number;
};

type TClickHouseAuthMethodRawRow = Omit<TClickHouseAuthMethodRow, "count"> & { count: string };

type TClickHouseCountForProjectArg = TClickHouseCountByDateArg & { projectId: string };

// actorMetadata is stored as the JSON text the client sent, so its key order is not stable and
// grouping on the whole string would split one actor across rows. Only the keys insights reads
// are extracted and grouped on.
type TClickHouseProjectActorVolumeRawRow = {
  date: string;
  actor: string;
  userId: string;
  email: string;
  username: string;
  identityId: string;
  name: string;
  count: string;
};

type TClickHouseProjectAuthMethodRawRow = {
  actor: string;
  authMethod: string;
  count: string;
};

// JSONExtractString returns "" for a missing key. Dropping those gives callers the same shape a
// Postgres actorMetadata has, so their `||` fallbacks behave the same for both stores.
const compactActorMetadata = (metadata: Record<string, string>) =>
  Object.fromEntries(Object.entries(metadata).filter(([, value]) => value !== ""));

// Shape of a row returned from ClickHouse's JSONEachRow format
// actorMetadata and eventMetadata are String columns — they come back as raw JSON strings
type TClickHouseAuditLogRow = {
  id: string;
  actor: string;
  actorMetadata: string;
  ipAddress: string;
  eventType: string;
  eventMetadata: string;
  userAgent: string;
  userAgentType: string;
  createdAt: string;
  orgId: string;
  projectId: string;
  expiresAt?: string;
};

// Validate JSON path keys to prevent injection
const SAFE_KEY_RE = new RE2(/^[a-zA-Z0-9_]+$/);
const isSafeKey = (key: string): boolean => SAFE_KEY_RE.test(key);

export type TClickHouseAuditLogDALFactory = ReturnType<typeof clickhouseAuditLogDALFactory>;

export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient, db: TDbClient, tableName: string) => {
  const find = async (arg: TClickHouseFindArg): Promise<TAuditLogWithProjectName[]> => {
    const conditions: string[] = [];
    const params: Record<string, unknown> = {};

    // Required: orgId filter (matches the primary key prefix)
    conditions.push("orgId = {orgId:UUID}");
    params.orgId = arg.orgId;

    // Date range filter – pass as DateTime64(6) so ClickHouse can compare
    // directly against the createdAt column without implicit string conversion.
    // Strip the trailing 'Z' because ClickHouse's DateTime64 parser doesn't accept it.
    conditions.push("createdAt >= {startDate:DateTime64(6)}");
    params.startDate = arg.startDate.replace("Z", "");
    conditions.push("createdAt < {endDate:DateTime64(6)}");
    params.endDate = arg.endDate.replace("Z", "");

    // Optional: project filter
    if (arg.projectId) {
      conditions.push("projectId = {projectId:String}");
      params.projectId = arg.projectId;
    }

    // Optional: user agent type filter
    if (arg.userAgentType) {
      conditions.push("userAgentType = {userAgentType:String}");
      params.userAgentType = arg.userAgentType;
    }

    // Optional: actor type filter
    if (arg.actorType) {
      conditions.push("actor = {actorType:String}");
      params.actorType = arg.actorType;
    }

    // Optional: actor ID filter - queries the actorMetadata JSON field
    if (arg.actorId) {
      const metadataKey = arg.actorType
        ? ACTOR_TYPE_TO_METADATA_ID_KEY[arg.actorType]
        : ACTOR_TYPE_TO_METADATA_ID_KEY[ActorType.USER];
      if (metadataKey) {
        conditions.push("JSONExtractString(actorMetadata, {actorMetaKey:String}) = {actorId:String}");
        params.actorMetaKey = metadataKey;
        params.actorId = arg.actorId;
      }
    }

    // Optional: event type filter
    if (arg.eventType?.length) {
      conditions.push("eventType IN ({eventTypes:Array(String)})");
      params.eventTypes = arg.eventType;
    }

    if (arg.excludeEventType?.length) {
      conditions.push("eventType NOT IN ({excludeEventTypes:Array(String)})");
      params.excludeEventTypes = arg.excludeEventType;
    }

    // Optional: eventMetadata dynamic key/value filters
    if (arg.eventMetadata && Object.keys(arg.eventMetadata).length) {
      let metaIdx = 0;
      for (const [key, value] of Object.entries(arg.eventMetadata)) {
        if (!isSafeKey(key)) {
          logger.warn({ key }, "Skipping unsafe eventMetadata filter key in ClickHouse query");
          // eslint-disable-next-line no-continue
          continue;
        }
        const keyParamName = `metaKey${metaIdx}`;
        const valParamName = `metaVal${metaIdx}`;
        conditions.push(`JSONExtractString(eventMetadata, {${keyParamName}:String}) = {${valParamName}:String}`);
        params[keyParamName] = key;
        params[valParamName] = value;
        metaIdx += 1;
      }
    }

    // PAM resource scoping: account logs by accountId, folder logs by folderId, and resource-less
    // (product-level) logs only for product admins
    if (arg.pamScope) {
      const scopeClauses: string[] = [];
      if (arg.pamScope.accountIds.length) {
        scopeClauses.push("JSONExtractString(eventMetadata, 'accountId') IN ({pamAccountIds:Array(String)})");
        params.pamAccountIds = arg.pamScope.accountIds;
      }
      if (arg.pamScope.folderIds.length) {
        scopeClauses.push(
          "(JSONHas(eventMetadata, 'folderId') AND NOT JSONHas(eventMetadata, 'accountId') AND JSONExtractString(eventMetadata, 'folderId') IN ({pamFolderIds:Array(String)}))"
        );
        params.pamFolderIds = arg.pamScope.folderIds;
      }
      if (arg.pamScope.includeProductLevel) {
        scopeClauses.push("(NOT JSONHas(eventMetadata, 'accountId') AND NOT JSONHas(eventMetadata, 'folderId'))");
      }
      conditions.push(scopeClauses.length ? `(${scopeClauses.join(" OR ")})` : "1 = 0");
    }

    // Secret-specific filters (environment, secretPath, secretKey)
    const eventIsSecretType =
      !arg.eventType?.length || arg.eventType.some((event) => filterableSecretEvents.includes(event));

    if (arg.projectId && eventIsSecretType) {
      if (arg.environment) {
        conditions.push("JSONExtractString(eventMetadata, 'environment') = {envFilter:String}");
        params.envFilter = arg.environment;
      }

      if (arg.secretPath) {
        conditions.push("JSONExtractString(eventMetadata, 'secretPath') = {secretPathFilter:String}");
        params.secretPathFilter = arg.secretPath;
      }

      if (arg.secretKey) {
        // Match secretKey at top level in eventMetadata OR inside the eventMetadata.secrets[] array.
        // The top-level check covers single-secret events, e.g.:
        //   { "secretKey": "MY_SECRET", "environment": "prod", ... }
        // The arrayExists check covers batch/multi-secret events, e.g.:
        //   { "secrets": [{ "secretKey": "MY_SECRET" }, { "secretKey": "OTHER" }], ... }
        conditions.push(
          `(${[
            "JSONExtractString(eventMetadata, 'secretKey') = {secretKeyFilter:String}",
            "arrayExists(x -> JSONExtractString(x, 'secretKey') = {secretKeyFilter:String}, JSONExtractArrayRaw(eventMetadata, 'secrets'))"
          ].join(" OR ")})`
        );
        params.secretKeyFilter = arg.secretKey;
      }
    }

    const whereClause = conditions.join(" AND ");

    const query = `
      SELECT
        id, actor, actorMetadata, ipAddress, eventType, eventMetadata,
        userAgent, userAgentType, orgId, projectId, expiresAt, createdAt
      FROM ${tableName}
      WHERE ${whereClause}
      ORDER BY createdAt DESC
      LIMIT {limit:UInt32}
      OFFSET {offset:UInt32}
    `;

    params.limit = arg.limit ?? 20;
    params.offset = arg.offset ?? 0;

    try {
      const result = await clickhouseClient.query({
        query,
        query_params: params,
        format: "JSONEachRow"
      });

      const rows = await result.json<TClickHouseAuditLogRow>();

      // Batch-fetch project names from Postgres for any results that have a projectId
      const projectIds = [...new Set(rows.map((r) => r.projectId).filter(Boolean))];
      let projectNameMap: Record<string, string> = {};

      if (projectIds.length > 0) {
        const projects = await db(TableName.Project).whereIn("id", projectIds).select("id", "name");
        projectNameMap = Object.fromEntries(projects.map((p: { id: string; name: string }) => [p.id, p.name]));
      }

      return rows.map((row) => ({
        id: row.id,
        actor: row.actor,
        actorMetadata: (row.actorMetadata ? JSON.parse(row.actorMetadata) : {}) as TAuditLogs["actorMetadata"],
        ipAddress: row.ipAddress || null,
        eventType: row.eventType,
        eventMetadata: (row.eventMetadata ? JSON.parse(row.eventMetadata) : null) as TAuditLogs["eventMetadata"],
        userAgent: row.userAgent || null,
        userAgentType: row.userAgentType || null,
        createdAt: new Date(row.createdAt),
        orgId: row.orgId || null,
        projectId: row.projectId || null,
        projectName: projectNameMap[row.projectId] ?? null,
        expiresAt: row.expiresAt ? new Date(row.expiresAt) : null
      })) as TAuditLogWithProjectName[];
    } catch (error) {
      logger.error(error, "Failed to query audit logs from ClickHouse");
      throw new DatabaseError({ error });
    }
  };

  // createdAt is stored without a timezone, so the bounds and toDate() are pinned to UTC. Otherwise
  // they follow the server's timezone and disagree with the UTC day buckets insights builds.
  const countByDateForOrg = async ({
    orgId,
    eventTypes,
    startDate,
    endDate
  }: TClickHouseCountByDateArg): Promise<TClickHouseDateVolumeRow[]> => {
    const query = `
      SELECT
        toDate(createdAt, 'UTC') AS date,
        count() AS count
      FROM ${tableName}
      WHERE orgId = {orgId:UUID}
        AND createdAt >= {startDate:DateTime64(6, 'UTC')}
        AND createdAt < {endDate:DateTime64(6, 'UTC')}
        AND eventType IN ({eventTypes:Array(String)})
      GROUP BY date
    `;

    try {
      const result = await clickhouseClient.query({
        query,
        query_params: {
          orgId,
          // ClickHouse's DateTime64 parser rejects the trailing 'Z'
          startDate: startDate.replace("Z", ""),
          endDate: endDate.replace("Z", ""),
          eventTypes
        },
        clickhouse_settings: {
          max_execution_time: 10
        },
        format: "JSONEachRow"
      });

      const rows = await result.json<TClickHouseDateVolumeRawRow>();

      return rows.map((row) => ({ ...row, count: Number(row.count) }));
    } catch (error) {
      logger.error(error, `Failed to aggregate audit logs by date from ClickHouse [orgId=${orgId}]`);
      throw new DatabaseError({ error });
    }
  };

  const countByIdentityAuthMethodForOrg = async ({
    orgId,
    eventTypes,
    startDate,
    endDate
  }: TClickHouseCountByDateArg): Promise<TClickHouseAuthMethodRow[]> => {
    const query = `
      SELECT
        JSONExtractString(actorMetadata, 'authMethod') AS authMethod,
        count() AS count
      FROM ${tableName}
      WHERE orgId = {orgId:UUID}
        AND createdAt >= {startDate:DateTime64(6, 'UTC')}
        AND createdAt < {endDate:DateTime64(6, 'UTC')}
        AND eventType IN ({eventTypes:Array(String)})
        AND actor = {actorType:String}
      GROUP BY authMethod
      HAVING authMethod IN ({authMethods:Array(String)})
    `;

    try {
      const result = await clickhouseClient.query({
        query,
        query_params: {
          orgId,
          // ClickHouse's DateTime64 parser rejects the trailing 'Z'
          startDate: startDate.replace("Z", ""),
          endDate: endDate.replace("Z", ""),
          eventTypes,
          actorType: ActorType.IDENTITY,
          authMethods: Object.values(IdentityAuthMethod)
        },
        clickhouse_settings: {
          max_execution_time: 10
        },
        format: "JSONEachRow"
      });

      const rows = await result.json<TClickHouseAuthMethodRawRow>();

      return rows.map((row) => ({ ...row, count: Number(row.count) }));
    } catch (error) {
      logger.error(error, `Failed to aggregate audit logs by identity auth method from ClickHouse [orgId=${orgId}]`);
      throw new DatabaseError({ error });
    }
  };

  // FINAL collapses rows a retried batch inserted twice (same id), which ReplacingMergeTree otherwise
  // removes only at some later merge. The primary key confines it to this project's time range.
  const countByDateAndActorForProject = async ({
    orgId,
    projectId,
    eventTypes,
    startDate,
    endDate
  }: TClickHouseCountForProjectArg): Promise<
    { date: string; actor: string; actorMetadata: Record<string, string>; count: number }[]
  > => {
    const query = `
      SELECT
        toDate(createdAt, 'UTC') AS date,
        actor,
        JSONExtractString(actorMetadata, 'userId') AS userId,
        JSONExtractString(actorMetadata, 'email') AS email,
        JSONExtractString(actorMetadata, 'username') AS username,
        JSONExtractString(actorMetadata, 'identityId') AS identityId,
        JSONExtractString(actorMetadata, 'name') AS name,
        count() AS count
      FROM ${tableName} FINAL
      WHERE orgId = {orgId:UUID}
        AND projectId = {projectId:String}
        AND createdAt >= {startDate:DateTime64(6, 'UTC')}
        AND createdAt < {endDate:DateTime64(6, 'UTC')}
        AND eventType IN ({eventTypes:Array(String)})
      GROUP BY date, actor, userId, email, username, identityId, name
    `;

    try {
      const result = await clickhouseClient.query({
        query,
        query_params: {
          orgId,
          projectId,
          // ClickHouse's DateTime64 parser rejects the trailing 'Z'
          startDate: startDate.replace("Z", ""),
          endDate: endDate.replace("Z", ""),
          eventTypes
        },
        clickhouse_settings: {
          max_execution_time: 10
        },
        format: "JSONEachRow"
      });

      const rows = await result.json<TClickHouseProjectActorVolumeRawRow>();

      return rows.map(({ date, actor, count, ...actorMetadata }) => ({
        date,
        actor,
        actorMetadata: compactActorMetadata(actorMetadata),
        count: Number(count)
      }));
    } catch (error) {
      logger.error(
        error,
        `Failed to aggregate audit logs by date and actor from ClickHouse [orgId=${orgId}] [projectId=${projectId}]`
      );
      throw new DatabaseError({ error });
    }
  };

  const countByAuthMethodForProject = async ({
    orgId,
    projectId,
    eventTypes,
    startDate,
    endDate
  }: TClickHouseCountForProjectArg): Promise<
    { actor: string; actorMetadata: Record<string, string>; count: number }[]
  > => {
    const query = `
      SELECT
        actor,
        JSONExtractString(actorMetadata, 'authMethod') AS authMethod,
        count() AS count
      FROM ${tableName} FINAL
      WHERE orgId = {orgId:UUID}
        AND projectId = {projectId:String}
        AND createdAt >= {startDate:DateTime64(6, 'UTC')}
        AND createdAt < {endDate:DateTime64(6, 'UTC')}
        AND eventType IN ({eventTypes:Array(String)})
      GROUP BY actor, authMethod
    `;

    try {
      const result = await clickhouseClient.query({
        query,
        query_params: {
          orgId,
          projectId,
          // ClickHouse's DateTime64 parser rejects the trailing 'Z'
          startDate: startDate.replace("Z", ""),
          endDate: endDate.replace("Z", ""),
          eventTypes
        },
        clickhouse_settings: {
          max_execution_time: 10
        },
        format: "JSONEachRow"
      });

      const rows = await result.json<TClickHouseProjectAuthMethodRawRow>();

      return rows.map(({ actor, authMethod, count }) => ({
        actor,
        actorMetadata: compactActorMetadata({ authMethod }),
        count: Number(count)
      }));
    } catch (error) {
      logger.error(
        error,
        `Failed to aggregate audit logs by auth method from ClickHouse [orgId=${orgId}] [projectId=${projectId}]`
      );
      throw new DatabaseError({ error });
    }
  };

  return {
    find,
    countByDateForOrg,
    countByIdentityAuthMethodForOrg,
    countByDateAndActorForProject,
    countByAuthMethodForProject
  };
};