Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(alerts): refuse alert saves that overlap another save
Calvin5d13d22d71cc
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.tsindex 1dde1b1f71..a59754d55b 100644--- a/backend/src/services/alert/alert-dal.ts+++ b/backend/src/services/alert/alert-dal.ts@@ -10,10 +10,7 @@ import { AlertPrincipalType, AlertTriggerType } from "./alert-types";export type TAlertDALFactory = ReturnType<typeof alertDALFactory>;-export type TAlertWithChannels = {- id: string;- name: string;- resourceId: string | null;+export type TAlertWithChannels = TAlerts & {channels: { id: string; name: string; channelType: string; enabled: boolean }[];};@@ -107,9 +104,13 @@ export const alertDALFactory = (db: TDbClient) => {}};- const findActiveById = async (id: string, tx?: Knex): Promise<TAlerts | undefined> => {+ const findActiveById = async (+ id: string,+ { readFromPrimary = false }: { readFromPrimary?: boolean } = {},+ tx?: Knex+ ): Promise<TAlerts | undefined> => {try {- const alert = await (tx || db.replicaNode())(TableName.Alert)+ const alert = await (tx || (readFromPrimary ? db : db.replicaNode()))(TableName.Alert).leftJoin(TableName.Project, `${TableName.Alert}.projectId`, `${TableName.Project}.id`).where(`${TableName.Alert}.id`, id).whereNull(`${TableName.Project}.deleteAfter`)@@ -122,6 +123,29 @@ export const alertDALFactory = (db: TDbClient) => {}};+ const findByIdForUpdate = async (id: string, tx: Knex): Promise<TAlerts | undefined> => {+ try {+ const alert = await tx(TableName.Alert).where({ id }).forUpdate().first();+ return alert as TAlerts | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "FindByIdForUpdate" });+ }+ };++ // Bumps updatedAt (the alert's version) for a save that changed only its channels.+ const touchById = async (id: string, tx: Knex): Promise<TAlerts> => {+ try {+ // Typed as the row because the table's update type excludes updatedAt. The trigger sets it either way.+ const [alert] = await tx<TAlerts>(TableName.Alert)+ .where({ id })+ .update({ updatedAt: tx.fn.now() })+ .returning("*");+ return alert as TAlerts;+ } catch (error) {+ throw new DatabaseError({ error, name: "TouchById" });+ }+ };+const findActiveByScope = async (filter: {orgId: string;@@ -259,10 +283,8 @@ export const alertDALFactory = (db: TDbClient) => {`${TableName.AlertChannelMembership}.channelId`,`${TableName.AlertChannel}.id`)+ .select(selectAllTableCols(TableName.Alert)).select(- db.ref("id").withSchema(TableName.Alert),- db.ref("name").withSchema(TableName.Alert),- db.ref("resourceId").withSchema(TableName.Alert),db.ref("id").withSchema(TableName.AlertChannel).as("channelId"),db.ref("name").withSchema(TableName.AlertChannel).as("channelName"),db.ref("channelType").withSchema(TableName.AlertChannel),@@ -273,7 +295,7 @@ export const alertDALFactory = (db: TDbClient) => {return sqlNestRelationships({data: rows,key: "id",- parentMapper: ({ id, name, resourceId }) => ({ id, name, resourceId: resourceId ?? null }),+ parentMapper: ({ channelId, channelName, channelType, channelEnabled, ...alert }) => alert as TAlerts,childrenMapper: [{key: "channelId",@@ -328,6 +350,8 @@ export const alertDALFactory = (db: TDbClient) => {findEnabledByResourceType,findEnabledForEvent,findActiveById,+ findByIdForUpdate,+ touchById,findActiveByScope,findByChannelId,findScopedDuplicatediff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex 43e511abda..e0c101f834 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -124,6 +124,11 @@ const buildService = (opts?: {return row;},findActiveById: async (id: string) => alerts.get(id),+ findByIdForUpdate: async (id: string) => alerts.get(id),+ touchById: async (id: string) => {+ alerts.set(id, { ...alerts.get(id), updatedAt: new Date() });+ return alerts.get(id);+ },findWithChannelsForResources: async ({resourceType,resourceIds@@ -134,9 +139,7 @@ const buildService = (opts?: {[...alerts.values()].filter((row) => row.resourceType === resourceType && resourceIds.includes(row.resourceId as string)).map((row) => ({- id: row.id,- name: row.name,- resourceId: row.resourceId,+ ...row,channels: (memberships.get(row.id as string) ?? []).map((channelId) => {const channel = channels.get(channelId) as TChannelRow;return { id: channel.id, name: channel.name, channelType: channel.channelType, enabled: channel.enabled };@@ -150,7 +153,8 @@ const buildService = (opts?: {updateById: async (id: string, data: Record<string, unknown>) => {// Mirror knex, which throws "Empty .update() call detected!" on an empty patch.if (Object.keys(data).length === 0) throw new Error("Empty .update() call detected!");- alerts.set(id, { ...alerts.get(id), ...data });+ // Mirror the table's update trigger, which bumps updatedAt on every write.+ alerts.set(id, { ...alerts.get(id), ...data, updatedAt: new Date() });return alerts.get(id);},deleteById: async (id: string) => alerts.delete(id),@@ -668,6 +672,19 @@ describe("alert service", () => {expect.objectContaining({ id: webhookBefore.id, name: "webhook-ch" })]);});++ test("refuses a save prepared before another save was applied", async () => {+ const { service, alerts, channels } = buildService();+ await service.createAlert({ ...validCreate, eventType: "test.resource.opened", condition: null });+ alerts.set("alert-1", { ...alerts.get("alert-1"), updatedAt: new Date(0) });++ const first = await service.prepareAlertForResource(resourceAlert(["user-2"]));+ const second = await service.prepareAlertForResource(resourceAlert(["user-3"]));+ await service.applyPreparedAlert(first, tx);++ await expect(service.applyPreparedAlert(second, tx)).rejects.toThrow("changed while you were saving");+ expect([...channels.values()][0].recipients).toEqual([expect.objectContaining({ principalId: "user-2" })]);+ });});test("update rejects an empty channel list", async () => {diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.tsindex ebdf37ec90..a987eabee1 100644--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@ -4,7 +4,7 @@ import { z } from "zod";import { TableName, TAlertChannels, TAlerts, TAlertsInsert } from "@app/db/schemas";import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";import { DatabaseErrorCode } from "@app/lib/error-codes";-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";+import { BadRequestError, ConflictError, DatabaseError, NotFoundError } from "@app/lib/errors";import { TGenericPermission } from "@app/lib/types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -341,10 +341,7 @@ export const alertServiceFactory = ({return { plan, provider, cipher };};- const $prepareUpdate = async (dto: TUpdateAlertDTO) => {- const alert = await alertDAL.findActiveById(dto.alertId);- if (!alert) throw new NotFoundError({ message: `Alert with ID '${dto.alertId}' not found` });-+ const $prepareUpdate = async (alert: TAlerts, dto: TUpdateAlertDTO) => {const provider = $getProvider(alert.resourceType);await $assertAlertPermission(provider,@@ -487,8 +484,18 @@ export const alertServiceFactory = ({return createdAlert;}+ // The plan was built from a read taken before this transaction, so two overlapping saves could each+ // delete or overwrite the other's channels. The table's update trigger bumps updatedAt on every write,+ // so it works as a version: refuse if it moved, and write the row so a save still in flight sees this one.+ const current = await alertDAL.findByIdForUpdate(plan.alert.id, tx);+ if (!current) throw new NotFoundError({ message: `Alert with ID '${plan.alert.id}' not found` });+ if (current.updatedAt.getTime() !== plan.alert.updatedAt.getTime()) {+ throw new ConflictError({ message: "This alert was changed while you were saving it. Reload and try again." });+ }const updatedAlert =- Object.keys(plan.patch).length > 0 ? await alertDAL.updateById(plan.alert.id, plan.patch, tx) : plan.alert;+ Object.keys(plan.patch).length > 0+ ? await alertDAL.updateById(plan.alert.id, plan.patch, tx)+ : await alertDAL.touchById(plan.alert.id, tx);for (const channelId of plan.deleteChannelIds) {// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serialawait alertChannelService.deleteChannel(channelId, tx);@@ -548,7 +555,7 @@ export const alertServiceFactory = ({"replaceAll" in channels ? channels.replaceAll : $channelsWithRecipients(existing, channels.replaceRecipients);const { plan } = existing- ? await $prepareUpdate({ alertId: existing.id, name, channels: alertChannels, ...actor })+ ? await $prepareUpdate(existing, { alertId: existing.id, name, channels: alertChannels, ...actor }): await $prepareCreate({name,resourceType,@@ -672,7 +679,10 @@ export const alertServiceFactory = ({};const updateAlert = async (dto: TUpdateAlertDTO): Promise<TAlertResponse> => {- const { plan, provider, cipher } = await $prepareUpdate(dto);+ // Read from the primary: the update plan is built from this row and its channels.+ const alert = await alertDAL.findActiveById(dto.alertId, { readFromPrimary: true });+ if (!alert) throw new NotFoundError({ message: `Alert with ID '${dto.alertId}' not found` });+ const { plan, provider, cipher } = await $prepareUpdate(alert, dto);const { updated, channels } = await alertDAL.transaction(async (tx) => {const updatedAlert = await $applyPlan(plan, tx);