Skip to content

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

11.1 KB
Raw Blame
import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";
import { EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";

import { alertEventConsumerFactory } from "./alert-event-consumer";
import { AlertTriggerType } from "./alert-types";

vi.mock("@app/lib/logger", () => ({
  logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
  initLogger: () => {}
}));

const ORG_ID = "11111111-1111-1111-1111-111111111111";
const EVENT_TYPE = "approval.workflow.request_opened";

const makeAlert = (id: string) =>
  ({ id, resourceType: "approval.workflow", orgId: ORG_ID, eventType: EVENT_TYPE }) as never;

const makePayload = (overrides?: Record<string, unknown>) => ({
  orgId: ORG_ID,
  projectId: null,
  resourceType: "approval.workflow",
  resourceId: "policy-1",
  targetIds: ["req-1"],
  ...overrides
});

const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({
  specversion: "1.0",
  id: "event-1",
  source: "urn:infisical:approval",
  type: EVENT_TYPE,
  time: new Date().toISOString(),
  data: makePayload(),
  isFinalAttempt: false,
  ...overrides
});

const buildConsumer = (opts?: {
  alerts?: unknown[];
  results?: AlertDispatchOutcome[];
  eventKeys?: string[];
  findAlerts?: (filter: { resourceType: string; resourceId?: string | null; eventType: string }) => Promise<unknown[]>;
  sourcedEvents?: { resourceType: string; eventKey: string }[];
}) => {
  const runs: {
    alertId: string;
    eventId: string;
    eventType: string;
    targetIds: string[];
    payload?: Record<string, unknown>;
  }[] = [];
  const results = opts?.results ?? [AlertDispatchOutcome.DeliverySuccess];
  let runIdx = 0;
  let lookups = 0;
  const eventKeys = opts?.eventKeys ?? [EVENT_TYPE];
  const consumer = alertEventConsumerFactory({
    alertDAL: {
      findEnabledForEvent: async (filter) => {
        lookups += 1;
        if (opts?.findAlerts) return (await opts.findAlerts(filter)) as never;
        return (opts?.alerts ?? [makeAlert("alert-1")]) as never;
      }
    },
    alertEngine: {
      runAlertForEvent: async (
        alert: { id: string },
        input: { eventId: string; eventType: string; targetIds: string[]; payload: Record<string, unknown> }
      ) => {
        runs.push({
          alertId: alert.id,
          eventId: input.eventId,
          eventType: input.eventType,
          targetIds: input.targetIds,
          payload: input.payload
        });
        const result = results[Math.min(runIdx, results.length - 1)];
        runIdx += 1;
        return result;
      }
    } as never,
    alertProviderRegistry: {
      eventTriggeredKeys: () => new Set(eventKeys),
      findEventsBySource: () => opts?.sourcedEvents ?? [],
      get: (resourceType: string) =>
        resourceType === "approval.workflow"
          ? ({ events: eventKeys.map((key) => ({ key, triggerType: AlertTriggerType.Event })) } as never)
          : undefined
    }
  });

  return { consumer, runs, getLookups: () => lookups };
};

describe("alert event consumer", () => {
  test("subscribes only to event keys a registered provider declares as event-triggered", () => {
    const { consumer } = buildConsumer();

    expect(consumer.subscribesTo(EVENT_TYPE)).toBe(true);
    expect(consumer.subscribesTo("identity.authentication.expiry")).toBe(false);
  });

  test("delivers the event's targets and marks it delivered", async () => {
    const { consumer, runs } = buildConsumer();

    const [result] = await consumer.handle([makeEvent()]);

    expect(result.status).toBe(EventResultStatus.Delivered);
    expect(runs[0].targetIds).toEqual(["req-1"]);
    // The provider sees everything the emitter wrote, not only the ids the consumer validated.
    expect(runs[0].payload).toEqual(makePayload());
  });

  test("accepts a scope-wide event that carries no resource", async () => {
    const { consumer, runs } = buildConsumer();

    const [result] = await consumer.handle([makeEvent({ data: makePayload({ resourceId: null }) })]);

    expect(result.status).toBe(EventResultStatus.Delivered);
    expect(runs[0].targetIds).toEqual(["req-1"]);
  });

  test("also runs the resource-less alerts of every event sourced from this event, each under its own event", async () => {
    const lookupsSeen: { resourceType: string; resourceId?: string | null; eventType: string }[] = [];
    const { consumer, runs } = buildConsumer({
      sourcedEvents: [{ resourceType: "approval.org", eventKey: "approval.org.request_opened" }],
      findAlerts: async (filter) => {
        lookupsSeen.push(filter);
        return [
          {
            id: filter.resourceType === "approval.org" ? "sourced-alert" : "bound-alert",
            resourceType: filter.resourceType,
            orgId: ORG_ID,
            eventType: filter.eventType
          }
        ];
      }
    });

    const [result] = await consumer.handle([makeEvent()]);

    expect(result.status).toBe(EventResultStatus.Delivered);
    expect(lookupsSeen).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ resourceType: "approval.workflow", resourceId: "policy-1", eventType: EVENT_TYPE }),
        expect.objectContaining({
          resourceType: "approval.org",
          resourceId: null,
          eventType: "approval.org.request_opened"
        })
      ])
    );
    expect(runs.map((run) => [run.alertId, run.eventType])).toEqual(
      expect.arrayContaining([
        ["bound-alert", EVENT_TYPE],
        ["sourced-alert", "approval.org.request_opened"]
      ])
    );
  });

  // The event id is stable across attempts, so it's the only key a retry can use to find what already
  // went out.
  test("hands the engine the event id so a retry can skip channels that already delivered", async () => {
    const { consumer, runs } = buildConsumer();

    await consumer.handle([makeEvent({ id: "550e8400-e29b-41d4-a716-446655440000" })]);

    expect(runs[0].eventId).toBe("550e8400-e29b-41d4-a716-446655440000");
  });

  // The alert was deleted or disabled before the worker ran, so nobody is owed a notification. That's
  // done, not something to retry forever.
  test("marks the event delivered when no alert matches any more", async () => {
    const { consumer, runs } = buildConsumer({ alerts: [] });

    const [result] = await consumer.handle([makeEvent()]);

    expect(result.status).toBe(EventResultStatus.Delivered);
    expect(runs).toHaveLength(0);
  });

  test("retries the event when a channel fails", async () => {
    const { consumer } = buildConsumer({ results: [AlertDispatchOutcome.DeliveryPartial] });

    const [result] = await consumer.handle([makeEvent()]);

    expect(result.status).toBe(EventResultStatus.Retry);
    expect(result.error).toContain(AlertDispatchOutcome.DeliveryPartial);
  });

  // Retrying can't fix a payload the consumer can't read, so don't burn every attempt on it first.
  test("fails terminally on an unreadable payload", async () => {
    const { consumer } = buildConsumer();

    const [result] = await consumer.handle([makeEvent({ data: makePayload({ targetIds: [] }) })]);

    expect(result.status).toBe(EventResultStatus.Failed);
    expect(result.error).toContain("Unreadable alert event payload");
  });

  test("runs every matching alert in a scope", async () => {
    const { consumer, runs } = buildConsumer({
      alerts: [makeAlert("alert-project"), makeAlert("alert-org")],
      results: [AlertDispatchOutcome.DeliverySuccess, AlertDispatchOutcome.DeliverySuccess]
    });

    const [result] = await consumer.handle([makeEvent()]);

    expect(runs.map((run) => run.alertId)).toEqual(["alert-project", "alert-org"]);
    expect(result.status).toBe(EventResultStatus.Delivered);
  });

  // Marking a mismatched pair delivered would hide the broken emit site. Failing terminally and naming
  // both is what surfaces it.
  test("fails terminally when no provider declares the event for that resource type", async () => {
    const { consumer, runs, getLookups } = buildConsumer();

    const [result] = await consumer.handle([makeEvent({ data: makePayload({ resourceType: "pki.certificate" }) })]);

    expect(result.status).toBe(EventResultStatus.Failed);
    expect(result.error).toContain("pki.certificate");
    expect(result.error).toContain("approval.workflow.request_opened");
    expect(runs).toHaveLength(0);
    expect(getLookups()).toBe(0);
  });

  // Throwing out of handle() retries the whole batch and re-notifies events that already delivered, so
  // one event's failure has to stay its own.
  test("retries only the event whose lookup threw", async () => {
    let calls = 0;
    const { consumer, runs } = buildConsumer({
      eventKeys: [EVENT_TYPE, "approval.workflow.request_closed", "approval.workflow.request_reopened"],
      findAlerts: async () => {
        calls += 1;
        if (calls === 2) throw new Error("connection reset");
        return [makeAlert(`alert-${calls}`)];
      }
    });

    const results = await consumer.handle([
      makeEvent({ id: "event-1", type: EVENT_TYPE }),
      makeEvent({ id: "event-2", type: "approval.workflow.request_closed" }),
      makeEvent({ id: "event-3", type: "approval.workflow.request_reopened" })
    ]);

    expect(results.map((result) => result.status)).toEqual([
      EventResultStatus.Delivered,
      EventResultStatus.Retry,
      EventResultStatus.Delivered
    ]);
    expect(results[1].error).toBe("connection reset");
    expect(runs.map((run) => run.alertId)).toEqual(["alert-1", "alert-3"]);
  });

  test("resolves the matching alerts once per resource and event type within a batch", async () => {
    const { consumer, getLookups } = buildConsumer();

    await consumer.handle([
      makeEvent({ id: "event-1", data: makePayload({ targetIds: ["req-1"] }) }),
      makeEvent({ id: "event-2", data: makePayload({ targetIds: ["req-2"] }) }),
      makeEvent({ id: "event-3", data: makePayload({ targetIds: ["req-3"] }) })
    ]);

    expect(getLookups()).toBe(1);
  });

  // The lookup is filtered by resource, so two resources in one org must not share a result: the second
  // would otherwise be delivered to the first resource's recipients.
  test("does not reuse one resource's alerts for another resource in the same batch", async () => {
    const { consumer, getLookups } = buildConsumer();

    await consumer.handle([
      makeEvent({ id: "event-1", data: makePayload({ resourceId: "policy-1", targetIds: ["req-1"] }) }),
      makeEvent({ id: "event-2", data: makePayload({ resourceId: "policy-2", targetIds: ["req-2"] }) }),
      makeEvent({ id: "event-3", data: makePayload({ resourceId: "policy-1", targetIds: ["req-3"] }) })
    ]);

    expect(getLookups()).toBe(2);
  });

  // Handling events concurrently would fan a whole batch out at once and deliver one resource's events
  // out of order.
  test("handles events serially, in the order given", async () => {
    const { consumer, runs } = buildConsumer();

    const results = await consumer.handle([
      makeEvent({ id: "event-1", data: makePayload({ targetIds: ["req-1"] }) }),
      makeEvent({ id: "event-2", data: makePayload({ targetIds: ["req-2"] }) })
    ]);

    expect(results.map((result) => result.id)).toEqual(["event-1", "event-2"]);
    expect(runs.map((run) => run.targetIds)).toEqual([["req-1"], ["req-2"]]);
  });
});