Skip to content

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

remove unused code

Thiago Araujo da Silvaa0db8c7ae168
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index d01d17c3ad..a7d6930e9e 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -79,7 +79,6 @@ import { RequestMemoizer } from "@app/lib/request-context/request-memoizer";
import { TAuthMode } from "@app/server/plugins/auth/inject-identity";
import { TAccountRecoveryServiceFactory } from "@app/services/account-recovery/account-recovery-service";
import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";
-import { TAlertChannelServiceFactory } from "@app/services/alert/alert-channel-service";
import { TAlertServiceFactory } from "@app/services/alert/alert-service";
import { TAnnouncementServiceFactory } from "@app/services/announcement/announcement-service";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
@@ -442,7 +441,6 @@ declare module "fastify" {
identityAuthTemplate: TIdentityAuthTemplateServiceFactory;
notification: TNotificationServiceFactory;
alert: TAlertServiceFactory;
- alertChannel: TAlertChannelServiceFactory;
announcement: TAnnouncementServiceFactory;
offlineUsageReport: TOfflineUsageReportServiceFactory;
orgProductStats: TOrgProductStatsServiceFactory;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7b47581196..360a289901 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1053,9 +1053,6 @@ export const registerRoutes = async (
const alertChannelService = alertChannelServiceFactory({
alertChannelDAL,
alertChannelRecipientDAL,
- alertChannelMembershipDAL,
- kmsService,
- permissionService,
orgDAL,
projectDAL,
groupDAL
@@ -4108,7 +4105,6 @@ export const registerRoutes = async (
projectEventsSSE: projectEventsSSEService,
notification: notificationService,
alert: alertService,
- alertChannel: alertChannelService,
announcement: announcementService,
mfaSession: mfaSessionService,
membershipUser: membershipUserService,
diff --git a/backend/src/server/routes/v1/alert-channel-router.ts b/backend/src/server/routes/v1/alert-channel-router.ts
deleted file mode 100644
index bb1e082c80..0000000000
--- a/backend/src/server/routes/v1/alert-channel-router.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { z } from "zod";
-
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AlertChannelType } from "@app/services/alert/alert-channel-types";
-import { AlertPrincipalType } from "@app/services/alert/alert-types";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-const RecipientInputSchema = z.object({
- principalType: z.nativeEnum(AlertPrincipalType),
- principalId: z.string().min(1)
-});
-
-const ChannelResponseSchema = z.object({
- id: z.string().uuid(),
- name: z.string(),
- channelType: z.string(),
- directed: z.boolean(),
- config: z.record(z.unknown()),
- enabled: z.boolean(),
- recipients: z.array(z.object({ principalType: z.string(), principalId: z.string() })),
- usageCount: z.number(),
- orgId: z.string(),
- projectId: z.string().nullable(),
- createdAt: z.date(),
- updatedAt: z.date()
-});
-
-export const registerAlertChannelRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "POST",
- url: "/",
- config: { rateLimit: writeLimit },
- schema: {
- operationId: "createAlertChannel",
- body: z.object({
- name: z.string().min(1).max(255),
- channelType: z.nativeEnum(AlertChannelType),
- config: z.record(z.unknown()).default({}),
- enabled: z.boolean().optional(),
- recipients: z.array(RecipientInputSchema).optional(),
- projectId: z.string().nullable().optional()
- }),
- response: { 200: z.object({ channel: ChannelResponseSchema }) }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const channel = await server.services.alertChannel.createChannel({
- ...req.body,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
- return { channel };
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "listAlertChannels",
- querystring: z.object({ projectId: z.string().optional() }),
- response: { 200: z.object({ channels: ChannelResponseSchema.array() }) }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const channels = await server.services.alertChannel.listChannels({
- ...req.query,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
- return { channels };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:channelId",
- config: { rateLimit: readLimit },
- schema: {
- operationId: "getAlertChannelById",
- params: z.object({ channelId: z.string().uuid() }),
- response: { 200: z.object({ channel: ChannelResponseSchema }) }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const channel = await server.services.alertChannel.getChannelById({
- channelId: req.params.channelId,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
- return { channel };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:channelId",
- config: { rateLimit: writeLimit },
- schema: {
- operationId: "updateAlertChannel",
- params: z.object({ channelId: z.string().uuid() }),
- body: z.object({
- name: z.string().min(1).max(255).optional(),
- config: z.record(z.unknown()).optional(),
- enabled: z.boolean().optional(),
- recipients: z.array(RecipientInputSchema).optional()
- }),
- response: { 200: z.object({ channel: ChannelResponseSchema }) }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const channel = await server.services.alertChannel.updateChannel({
- channelId: req.params.channelId,
- ...req.body,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
- return { channel };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:channelId",
- config: { rateLimit: writeLimit },
- schema: {
- operationId: "deleteAlertChannel",
- params: z.object({ channelId: z.string().uuid() }),
- response: { 200: z.object({ channel: z.object({ id: z.string().uuid() }) }) }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const channel = await server.services.alertChannel.deleteChannel({
- channelId: req.params.channelId,
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId
- });
- return { channel };
- }
- });
-};
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index e2a7e381f0..06076dfc9b 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -11,7 +11,6 @@ import { registerSecretSyncRouter, SECRET_SYNC_REGISTER_ROUTER_MAP } from "@app/
import { registerAccountRecoveryRouter } from "./account-recovery-router";
import { registerAdminRouter } from "./admin-router";
-import { registerAlertChannelRouter } from "./alert-channel-router";
import { registerAlertRouter } from "./alert-router";
import { registerAnnouncementRouter } from "./announcement-router";
import { APPROVAL_POLICY_REGISTER_ROUTER_MAP } from "./approval-policy-routers";
@@ -141,7 +140,6 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(registerUserRouter, { prefix: "/user" });
await server.register(registerNotificationRouter, { prefix: "/notifications" });
await server.register(registerAlertRouter, { prefix: "/alerts" });
- await server.register(registerAlertChannelRouter, { prefix: "/alert-channels" });
await server.register(registerAnnouncementRouter, { prefix: "/announcement" });
await server.register(registerInviteOrgRouter, { prefix: "/invite-org" });
await server.register(registerUserActionRouter, { prefix: "/user-action" });
diff --git a/backend/src/services/alert/alert-channel-dal.ts b/backend/src/services/alert/alert-channel-dal.ts
index 8b26385fc1..327765873e 100644
--- a/backend/src/services/alert/alert-channel-dal.ts
+++ b/backend/src/services/alert/alert-channel-dal.ts
@@ -7,75 +7,11 @@ import { ormify, selectAllTableCols } from "@app/lib/knex";
export type TAlertChannelDALFactory = ReturnType<typeof alertChannelDALFactory>;
-export type TAlertChannelWithUsage = TAlertChannels & { usageCount: number };
-export type TAlertChannelWithAlertId = TAlertChannels & { alertId: string };
+type TAlertChannelWithAlertId = TAlertChannels & { alertId: string };
export const alertChannelDALFactory = (db: TDbClient) => {
const alertChannelOrm = ormify(db, TableName.AlertChannel);
- const scopeFilter = (query: Knex.QueryBuilder, orgId: string, projectId?: string | null): void => {
- void query.where(`${TableName.AlertChannel}.orgId`, orgId);
- if (projectId) void query.where(`${TableName.AlertChannel}.projectId`, projectId);
- else void query.whereNull(`${TableName.AlertChannel}.projectId`);
- };
-
- const findWithUsageByScope = async (
- { orgId, projectId }: { orgId: string; projectId?: string | null },
- tx?: Knex
- ): Promise<TAlertChannelWithUsage[]> => {
- try {
- const query = (tx || db.replicaNode())(TableName.AlertChannel)
- .leftJoin(
- TableName.AlertChannelMembership,
- `${TableName.AlertChannel}.id`,
- `${TableName.AlertChannelMembership}.channelId`
- )
- .leftJoin(TableName.Project, `${TableName.AlertChannel}.projectId`, `${TableName.Project}.id`)
- .whereNull(`${TableName.Project}.deleteAfter`);
- scopeFilter(query, orgId, projectId);
-
- const rows = await query
- .groupBy(`${TableName.AlertChannel}.id`)
- .select(selectAllTableCols(TableName.AlertChannel))
- .select(db.raw(`count(??.??)::int as "usageCount"`, [TableName.AlertChannelMembership, "id"]))
- .orderBy(`${TableName.AlertChannel}.createdAt`, "asc");
-
- return rows as unknown as TAlertChannelWithUsage[];
- } catch (error) {
- throw new DatabaseError({ error, name: "FindWithUsageByScope" });
- }
- };
-
- const findActiveById = async (id: string, tx?: Knex): Promise<TAlertChannels | undefined> => {
- try {
- const channel = await (tx || db.replicaNode())(TableName.AlertChannel)
- .leftJoin(TableName.Project, `${TableName.AlertChannel}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.AlertChannel}.id`, id)
- .whereNull(`${TableName.Project}.deleteAfter`)
- .select(selectAllTableCols(TableName.AlertChannel))
- .first();
-
- return channel as TAlertChannels | undefined;
- } catch (error) {
- throw new DatabaseError({ error, name: "FindActiveById" });
- }
- };
-
- const findByNameInScope = async (
- name: string,
- { orgId, projectId }: { orgId: string; projectId?: string | null },
- tx?: Knex
- ): Promise<TAlertChannels | undefined> => {
- try {
- const query = (tx || db.replicaNode())(TableName.AlertChannel).where(`${TableName.AlertChannel}.name`, name);
- scopeFilter(query, orgId, projectId);
- const channel = await query.select(selectAllTableCols(TableName.AlertChannel)).first();
- return channel as TAlertChannels | undefined;
- } catch (error) {
- throw new DatabaseError({ error, name: "FindByNameInScope" });
- }
- };
-
const findByAlertId = async (
alertId: string,
filter: { enabled?: boolean } = {},
@@ -125,9 +61,6 @@ export const alertChannelDALFactory = (db: TDbClient) => {
return {
...alertChannelOrm,
- findWithUsageByScope,
- findActiveById,
- findByNameInScope,
findByAlertId,
findByAlertIds
};
diff --git a/backend/src/services/alert/alert-channel-service-types.ts b/backend/src/services/alert/alert-channel-service-types.ts
index 54d01cf2ab..5af0e01111 100644
--- a/backend/src/services/alert/alert-channel-service-types.ts
+++ b/backend/src/services/alert/alert-channel-service-types.ts
@@ -1,5 +1,3 @@
-import { TGenericPermission } from "@app/lib/types";
-
import { AlertChannelType } from "./alert-channel-types";
import { AlertPrincipalType } from "./alert-types";
@@ -8,44 +6,6 @@ export type TChannelRecipientInput = {
principalId: string;
};
-export type TCreateAlertChannelDTO = TGenericPermission & {
- name: string;
- channelType: AlertChannelType;
- config: Record<string, unknown>;
- enabled?: boolean;
- recipients?: TChannelRecipientInput[];
- projectId?: string | null;
-};
-
-export type TUpdateAlertChannelDTO = TGenericPermission & {
- channelId: string;
- name?: string;
- config?: Record<string, unknown>;
- enabled?: boolean;
- recipients?: TChannelRecipientInput[];
-};
-
-export type TDeleteAlertChannelDTO = TGenericPermission & { channelId: string };
-
-export type TGetAlertChannelDTO = TGenericPermission & { channelId: string };
-
-export type TListAlertChannelsDTO = TGenericPermission & { projectId?: string | null };
-
-export type TAlertChannelDetail = {
- id: string;
- name: string;
- channelType: string;
- directed: boolean;
- config: Record<string, unknown>;
- enabled: boolean;
- recipients: { principalType: string; principalId: string }[];
- usageCount: number;
- orgId: string;
- projectId: string | null;
- createdAt: Date;
- updatedAt: Date;
-};
-
export type TAlertChannelEmbedded = {
id: string;
name: string;
diff --git a/backend/src/services/alert/alert-channel-service.test.ts b/backend/src/services/alert/alert-channel-service.test.ts
index 32f6450bb1..279b8ffc0a 100644
--- a/backend/src/services/alert/alert-channel-service.test.ts
+++ b/backend/src/services/alert/alert-channel-service.test.ts
@@ -1,17 +1,15 @@
-import { createMongoAbility } from "@casl/ability";
+import { Knex } from "knex";
import { alertChannelServiceFactory, TAlertChannelServiceFactoryDep } from "./alert-channel-service";
import { AlertChannelType } from "./alert-channel-types";
import { AlertPrincipalType } from "./alert-types";
// Identity cipher: encryptedConfig is just JSON bytes of the config.
-const kmsServiceMock = {
- createCipherPairWithDataKey: async () => ({
- encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
- decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
- })
-};
+const encryptor = ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText });
+const decryptor = ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob;
+const cipher = { encryptor, decryptor } as never;
const encConfig = (config: unknown) => Buffer.from(JSON.stringify(config));
+const tx = {} as Knex;
type TRow = {
id: string;
@@ -26,28 +24,14 @@ type TRow = {
updatedAt: Date;
};
-const actor = {
- actor: "user" as never,
- actorId: "user-1",
- actorAuthMethod: null as never,
- actorOrgId: "org-1"
-};
-
-const buildService = (opts?: { seed?: TRow[]; allow?: boolean }) => {
+const buildService = (opts?: { seed?: TRow[] }) => {
const store = new Map<string, TRow>();
(opts?.seed ?? []).forEach((r) => store.set(r.id, r));
const recipients = new Map<string, Array<{ channelId: string; principalType: string; principalId: string }>>();
- const memberships = new Map<string, number>(); // channelId -> usage count
let counter = 0;
- const ability = () =>
- createMongoAbility(
- opts?.allow === false ? [] : [{ action: ["read", "create", "edit", "delete"], subject: "settings" }]
- );
-
const service = alertChannelServiceFactory({
alertChannelDAL: {
- transaction: async (cb: (tx: unknown) => unknown) => cb({}),
create: async (data: Record<string, unknown>) => {
counter += 1;
const row = {
@@ -62,8 +46,6 @@ const buildService = (opts?: { seed?: TRow[]; allow?: boolean }) => {
store.set(row.id, row);
return row;
},
- findActiveById: async (id: string) => store.get(id),
- findById: async (id: string) => store.get(id),
updateById: async (id: string, data: Record<string, unknown>) => {
store.set(id, { ...(store.get(id) as TRow), ...data, updatedAt: new Date() });
return store.get(id);
@@ -71,15 +53,7 @@ const buildService = (opts?: { seed?: TRow[]; allow?: boolean }) => {
deleteById: async (id: string) => {
store.delete(id);
return { id };
- },
- findByNameInScope: async (name: string, scope: { orgId: string; projectId?: string | null }) =>
- [...store.values()].find(
- (r) => r.name === name && r.orgId === scope.orgId && (r.projectId ?? null) === (scope.projectId ?? null)
- ),
- findWithUsageByScope: async (scope: { orgId: string; projectId?: string | null }) =>
- [...store.values()]
- .filter((r) => r.orgId === scope.orgId && (r.projectId ?? null) === (scope.projectId ?? null))
- .map((r) => ({ ...r, usageCount: memberships.get(r.id) ?? 0 }))
+ }
},
alertChannelRecipientDAL: {
insertMany: async (data: Array<{ channelId: string; principalType: string; principalId: string }>) => {
@@ -93,14 +67,6 @@ const buildService = (opts?: { seed?: TRow[]; allow?: boolean }) => {
return 0;
}
},
- alertChannelMembershipDAL: {
- countByChannelId: async (channelId: string) => memberships.get(channelId) ?? 0
- },
- kmsService: kmsServiceMock,
- permissionService: {
- getOrgPermission: async () => ({ permission: ability() }),
- getProjectPermission: async () => ({ permission: ability() })
- },
orgDAL: {
findMembership: async (filter: { $in?: { actorUserId?: string[] } }) =>
(filter.$in?.actorUserId ?? []).map((actorUserId) => ({ actorUserId }))
@@ -120,7 +86,7 @@ const buildService = (opts?: { seed?: TRow[]; allow?: boolean }) => {
groupDAL: { find: async (filter: { $in?: { id?: string[] } }) => (filter.$in?.id ?? []).map((id) => ({ id })) }
} as unknown as TAlertChannelServiceFactoryDep);
- return { service, store, recipients, memberships };
+ return { service, store, recipients };
};
const seedRow = (
@@ -137,186 +103,137 @@ const seedRow = (
});
describe("alert channel service", () => {
- test("creates a webhook channel, stores config, and reports zero usage", async () => {
- const { service, store } = buildService();
- const channel = await service.createChannel({
- name: "Ops webhook",
- channelType: AlertChannelType.WEBHOOK,
- config: { url: "https://example.com/hook", signingSecret: "s3cr3t" },
- ...actor
- });
+ test("creates a webhook channel, stores config, and redacts secrets in the detail view", async () => {
+ const { service } = buildService();
+ const channel = await service.createChannelInTx(
+ {
+ name: "Ops webhook",
+ channelType: AlertChannelType.WEBHOOK,
+ config: { url: "https://example.com/hook", signingSecret: "s3cr3t" },
+ orgId: "org-1"
+ },
+ encryptor as never,
+ tx
+ );
- expect(channel.name).toBe("Ops webhook");
- expect(channel.usageCount).toBe(0);
+ const [detail] = await service.getDetailsForChannels([channel], { decryptor: decryptor as never });
+ expect(detail.name).toBe("Ops webhook");
// Secret is redacted on the way out.
- expect(channel.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });
- expect(store.get(channel.id)).toBeDefined();
+ expect(detail.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });
+ expect(detail.recipients).toEqual([]);
});
test("requires recipients for a directed (email) channel and rejects them for others", async () => {
const { service } = buildService();
await expect(
- service.createChannel({ name: "Team email", channelType: AlertChannelType.EMAIL, config: {}, ...actor })
+ service.createChannelInTx(
+ { name: "Team email", channelType: AlertChannelType.EMAIL, config: {}, orgId: "org-1" },
+ encryptor as never,
+ tx
+ )
).rejects.toThrow("require at least one recipient");
await expect(
- service.createChannel({
- name: "Ops webhook",
- channelType: AlertChannelType.WEBHOOK,
- config: { url: "https://example.com/hook" },
- recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
- ...actor
- })
+ service.createChannelInTx(
+ {
+ name: "Ops webhook",
+ channelType: AlertChannelType.WEBHOOK,
+ config: { url: "https://example.com/hook" },
+ recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
+ orgId: "org-1"
+ },
+ encryptor as never,
+ tx
+ )
).rejects.toThrow("do not take recipients");
});
test("creates a directed email channel with recipients", async () => {
const { service, recipients } = buildService();
- const channel = await service.createChannel({
- name: "Team email",
- channelType: AlertChannelType.EMAIL,
- config: {},
- recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
- ...actor
- });
- expect(channel.directed).toBe(true);
- expect(channel.recipients).toEqual([{ principalType: "user", principalId: "user-1" }]);
+ const channel = await service.createChannelInTx(
+ {
+ name: "Team email",
+ channelType: AlertChannelType.EMAIL,
+ config: {},
+ recipients: [{ principalType: AlertPrincipalType.USER, principalId: "user-1" }],
+ orgId: "org-1"
+ },
+ encryptor as never,
+ tx
+ );
+ const [detail] = await service.getDetailsForChannels([channel], { decryptor: decryptor as never });
+ expect(detail.directed).toBe(true);
+ expect(detail.recipients).toEqual([{ principalType: "user", principalId: "user-1" }]);
expect(recipients.get(channel.id)).toHaveLength(1);
});
- test("rejects a duplicate channel name in the same scope", async () => {
- const { service } = buildService({
- seed: [
- seedRow({
- id: "ch-x",
- name: "dupe",
- channelType: AlertChannelType.WEBHOOK,
- encryptedConfig: encConfig({ url: "https://example.com" })
- })
- ]
- });
- await expect(
- service.createChannel({
- name: "dupe",
- channelType: AlertChannelType.WEBHOOK,
- config: { url: "https://example.com/hook" },
- ...actor
- })
- ).rejects.toThrow(/already exists/);
- });
-
test("keeps an omitted secret on update", async () => {
- const { service } = buildService({
- seed: [
- seedRow({
- id: "ch-1",
- channelType: AlertChannelType.WEBHOOK,
- encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" })
- })
- ]
+ const { service } = buildService();
+ const channel = seedRow({
+ id: "ch-1",
+ channelType: AlertChannelType.WEBHOOK,
+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" })
});
// Config sent without signingSecret -> keep the existing one.
- const updated = await service.updateChannel({
- channelId: "ch-1",
- config: { url: "https://example.com/hook" },
- ...actor
- });
- expect(updated.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: true });
+ const finalConfig = await service.updateChannelInTx(
+ { channelId: "ch-1", config: { url: "https://example.com/hook" } },
+ channel as never,
+ cipher,
+ tx
+ );
+ expect(finalConfig).toEqual({ url: "https://example.com/hook", signingSecret: "s3cr3t" });
});
- test("clears an optional secret when explicitly emptied on update (fixes #2)", async () => {
- const { service, store } = buildService({
- seed: [
- seedRow({
- id: "ch-1",
- channelType: AlertChannelType.WEBHOOK,
- encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" })
- })
- ]
+ test("clears an optional secret when explicitly emptied on update", async () => {
+ const { service, store } = buildService();
+ const channel = seedRow({
+ id: "ch-1",
+ channelType: AlertChannelType.WEBHOOK,
+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "s3cr3t" })
});
- const updated = await service.updateChannel({
- channelId: "ch-1",
- config: { url: "https://example.com/hook", signingSecret: "" },
- ...actor
- });
+ const finalConfig = await service.updateChannelInTx(
+ { channelId: "ch-1", config: { url: "https://example.com/hook", signingSecret: "" } },
+ channel as never,
+ cipher,
+ tx
+ );
- expect(updated.config).toEqual({ url: "https://example.com/hook", hasSigningSecret: false });
+ expect(finalConfig).toEqual({ url: "https://example.com/hook" });
// And it is actually gone from the stored ciphertext, not just hidden.
const stored = JSON.parse(store.get("ch-1")!.encryptedConfig.toString()) as Record<string, unknown>;
expect(stored).not.toHaveProperty("signingSecret");
});
test("sets a new secret when a value is provided on update", async () => {
- const { service, store } = buildService({
- seed: [
- seedRow({
- id: "ch-1",
- channelType: AlertChannelType.WEBHOOK,
- encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "old" })
- })
- ]
+ const { service, store } = buildService();
+ const channel = seedRow({
+ id: "ch-1",
+ channelType: AlertChannelType.WEBHOOK,
+ encryptedConfig: encConfig({ url: "https://example.com/hook", signingSecret: "old" })
});
- await service.updateChannel({
- channelId: "ch-1",
- config: { url: "https://example.com/hook", signingSecret: "new" },
- ...actor
- });
+ await service.updateChannelInTx(
+ { channelId: "ch-1", config: { url: "https://example.com/hook", signingSecret: "new" } },
+ channel as never,
+ cipher,
+ tx
+ );
const stored = JSON.parse(store.get("ch-1")!.encryptedConfig.toString()) as Record<string, unknown>;
expect(stored.signingSecret).toBe("new");
});
test("rejects clearing a required secret (Slack webhook URL)", async () => {
- const { service } = buildService({
- seed: [
- seedRow({
- id: "ch-1",
- channelType: AlertChannelType.SLACK,
- encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/T/B/xxx" })
- })
- ]
+ const { service } = buildService();
+ const channel = seedRow({
+ id: "ch-1",
+ channelType: AlertChannelType.SLACK,
+ encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/T/B/xxx" })
});
- await expect(service.updateChannel({ channelId: "ch-1", config: { webhookUrl: "" }, ...actor })).rejects.toThrow(
- /Invalid slack channel config/
- );
- });
-
- test("denies channel management without the settings permission", async () => {
- const { service } = buildService({ allow: false });
await expect(
- service.createChannel({
- name: "nope",
- channelType: AlertChannelType.WEBHOOK,
- config: { url: "https://example.com/hook" },
- ...actor
- })
- ).rejects.toThrow();
- });
-
- test("lists channels with their usage counts", async () => {
- const { service, memberships } = buildService({
- seed: [
- seedRow({
- id: "ch-1",
- name: "a",
- channelType: AlertChannelType.WEBHOOK,
- encryptedConfig: encConfig({ url: "https://example.com/1" })
- }),
- seedRow({
- id: "ch-2",
- name: "b",
- channelType: AlertChannelType.WEBHOOK,
- encryptedConfig: encConfig({ url: "https://example.com/2" })
- })
- ]
- });
- memberships.set("ch-1", 3);
-
- const channels = await service.listChannels({ ...actor });
- expect(channels.find((c) => c.id === "ch-1")?.usageCount).toBe(3);
- expect(channels.find((c) => c.id === "ch-2")?.usageCount).toBe(0);
+ service.updateChannelInTx({ channelId: "ch-1", config: { webhookUrl: "" } }, channel as never, cipher, tx)
+ ).rejects.toThrow(/Invalid slack channel config/);
});
});
diff --git a/backend/src/services/alert/alert-channel-service.ts b/backend/src/services/alert/alert-channel-service.ts
index 67d785fac2..2184293b28 100644
--- a/backend/src/services/alert/alert-channel-service.ts
+++ b/backend/src/services/alert/alert-channel-service.ts
@@ -1,38 +1,21 @@
-import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
import { z } from "zod";
-import { ActionProjectType, OrganizationActionScope, TAlertChannels } from "@app/db/schemas";
+import { TAlertChannels } from "@app/db/schemas";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
-import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
-import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { TGenericPermission } from "@app/lib/types";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { BadRequestError } from "@app/lib/errors";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import {
decryptChannelConfig,
encryptChannelConfig,
- getAlertChannelCipher,
TAlertDecryptor,
TAlertEncryptor
} from "./alert-channel-crypto-fns";
import { TAlertChannelDALFactory } from "./alert-channel-dal";
-import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-dal";
import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";
-import {
- TAlertChannelDetail,
- TAlertChannelEmbedded,
- TChannelRecipientInput,
- TCreateAlertChannelDTO,
- TDeleteAlertChannelDTO,
- TGetAlertChannelDTO,
- TListAlertChannelsDTO,
- TUpdateAlertChannelDTO
-} from "./alert-channel-service-types";
+import { TAlertChannelEmbedded, TChannelRecipientInput } from "./alert-channel-service-types";
import { AlertChannelType } from "./alert-channel-types";
import { AlertPrincipalType } from "./alert-types";
import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
@@ -40,9 +23,6 @@ import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
export type TAlertChannelServiceFactoryDep = {
alertChannelDAL: TAlertChannelDALFactory;
alertChannelRecipientDAL: TAlertChannelRecipientDALFactory;
- alertChannelMembershipDAL: Pick<TAlertChannelMembershipDALFactory, "countByChannelId">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
orgDAL: Pick<TOrgDALFactory, "findMembership">;
projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;
groupDAL: Pick<TGroupDALFactory, "find">;
@@ -73,19 +53,9 @@ export type TUpdateChannelInTxInput = {
const capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);
-const ORG_TO_PROJECT_ACTION: Record<OrgPermissionActions, ProjectPermissionActions> = {
- [OrgPermissionActions.Read]: ProjectPermissionActions.Read,
- [OrgPermissionActions.Create]: ProjectPermissionActions.Create,
- [OrgPermissionActions.Edit]: ProjectPermissionActions.Edit,
- [OrgPermissionActions.Delete]: ProjectPermissionActions.Delete
-};
-
export const alertChannelServiceFactory = ({
alertChannelDAL,
alertChannelRecipientDAL,
- alertChannelMembershipDAL,
- kmsService,
- permissionService,
orgDAL,
projectDAL,
groupDAL
@@ -96,36 +66,6 @@ export const alertChannelServiceFactory = ({
return definition;
};
- const $assertPermission = async (
- action: OrgPermissionActions,
- orgId: string,
- projectId: string | null | undefined,
- actor: TGenericPermission
- ) => {
- if (projectId) {
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.actor,
- actorId: actor.actorId,
- projectId,
- actorAuthMethod: actor.actorAuthMethod,
- actorOrgId: actor.actorOrgId,
- actionProjectType: ActionProjectType.Any
- });
- ForbiddenError.from(permission).throwUnlessCan(ORG_TO_PROJECT_ACTION[action], ProjectPermissionSub.Settings);
- return;
- }
-
- const { permission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor: actor.actor,
- actorId: actor.actorId,
- orgId,
- actorAuthMethod: actor.actorAuthMethod,
- actorOrgId: actor.actorOrgId
- });
- ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.Settings);
- };
-
// Confirms every recipient principal (user/group) actually belongs to the channel's scope so an
// alert can't be made to notify a foreign principal.
const $validateRecipients = async (
@@ -247,52 +187,6 @@ export const alertChannelServiceFactory = ({
return merged;
};
- const $countUsage = (channelId: string, tx?: Knex): Promise<number> =>
- alertChannelMembershipDAL.countByChannelId(channelId, tx);
-
- const $buildDetail = (
- channel: {
- id: string;
- name: string;
- channelType: string;
- enabled: boolean;
- orgId: string;
- projectId?: string | null;
- createdAt: Date;
- updatedAt: Date;
- },
- config: Record<string, unknown>,
- recipients: { principalType: string; principalId: string }[],
- usageCount: number
- ): TAlertChannelDetail => {
- const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
- return {
- id: channel.id,
- name: channel.name,
- channelType: channel.channelType,
- directed: Boolean(definition?.directed),
- config: $redactConfig(channel.channelType, config),
- enabled: channel.enabled,
- recipients,
- usageCount,
- orgId: channel.orgId,
- projectId: channel.projectId ?? null,
- createdAt: channel.createdAt,
- updatedAt: channel.updatedAt
- };
- };
-
- const $assertNameAvailable = async (
- name: string,
- scope: { orgId: string; projectId?: string | null },
- excludeId?: string
- ) => {
- const existing = await alertChannelDAL.findByNameInScope(name, scope);
- if (existing && existing.id !== excludeId) {
- throw new BadRequestError({ message: `A channel named '${name}' already exists in this scope` });
- }
- };
-
const createChannelInTx = async (
input: TCreateChannelInTxInput,
encryptor: TAlertEncryptor,
@@ -411,167 +305,7 @@ export const alertChannelServiceFactory = ({
});
};
- // ----- Standalone channel endpoints (reusable model) -----
-
- const createChannel = async (dto: TCreateAlertChannelDTO): Promise<TAlertChannelDetail> => {
- const actor: TGenericPermission = {
- actor: dto.actor,
- actorId: dto.actorId,
- actorAuthMethod: dto.actorAuthMethod,
- actorOrgId: dto.actorOrgId
- };
- await $assertPermission(OrgPermissionActions.Create, dto.actorOrgId, dto.projectId, actor);
- await $assertNameAvailable(dto.name, { orgId: dto.actorOrgId, projectId: dto.projectId });
-
- const { encryptor } = await getAlertChannelCipher(kmsService, {
- orgId: dto.actorOrgId,
- projectId: dto.projectId ?? null
- });
-
- const recipients = dto.recipients ?? [];
- const channel = await alertChannelDAL.transaction((tx) =>
- createChannelInTx(
- {
- name: dto.name,
- channelType: dto.channelType,
- config: dto.config,
- enabled: dto.enabled,
- recipients,
- orgId: dto.actorOrgId,
- projectId: dto.projectId ?? null,
- createdByUserId: dto.actorId
- },
- encryptor,
- tx
- )
- );
-
- return $buildDetail(channel, dto.config, recipients, 0);
- };
-
- const updateChannel = async (dto: TUpdateAlertChannelDTO): Promise<TAlertChannelDetail> => {
- const actor: TGenericPermission = {
- actor: dto.actor,
- actorId: dto.actorId,
- actorAuthMethod: dto.actorAuthMethod,
- actorOrgId: dto.actorOrgId
- };
-
- const channel = await alertChannelDAL.findActiveById(dto.channelId);
- if (!channel) throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' not found` });
-
- await $assertPermission(OrgPermissionActions.Edit, channel.orgId, channel.projectId, actor);
-
- const scope = { orgId: channel.orgId, projectId: channel.projectId };
- if (dto.name !== undefined && dto.name !== channel.name) {
- await $assertNameAvailable(dto.name, scope, channel.id);
- }
-
- const cipher = await getAlertChannelCipher(kmsService, scope);
- return alertChannelDAL.transaction(async (tx) => {
- const finalConfig = await updateChannelInTx(
- { channelId: channel.id, name: dto.name, config: dto.config, enabled: dto.enabled, recipients: dto.recipients },
- channel,
- cipher,
- tx
- );
-
- const updated = await alertChannelDAL.findById(channel.id, tx);
- const recipients = await alertChannelRecipientDAL.findByChannelId(channel.id, tx);
- const usageCount = await $countUsage(channel.id, tx);
-
- return $buildDetail(
- updated,
- finalConfig,
- recipients.map((r) => ({ principalType: r.principalType, principalId: r.principalId })),
- usageCount
- );
- });
- };
-
- const deleteChannel = async (dto: TDeleteAlertChannelDTO): Promise<{ id: string }> => {
- const actor: TGenericPermission = {
- actor: dto.actor,
- actorId: dto.actorId,
- actorAuthMethod: dto.actorAuthMethod,
- actorOrgId: dto.actorOrgId
- };
- const channel = await alertChannelDAL.findActiveById(dto.channelId);
- if (!channel) throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' not found` });
-
- await $assertPermission(OrgPermissionActions.Delete, channel.orgId, channel.projectId, actor);
-
- // Membership rows CASCADE-delete, detaching the channel from every alert that referenced it.
- await alertChannelDAL.deleteById(channel.id);
- return { id: channel.id };
- };
-
- const getChannelById = async (dto: TGetAlertChannelDTO): Promise<TAlertChannelDetail> => {
- const actor: TGenericPermission = {
- actor: dto.actor,
- actorId: dto.actorId,
- actorAuthMethod: dto.actorAuthMethod,
- actorOrgId: dto.actorOrgId
- };
- const channel = await alertChannelDAL.findActiveById(dto.channelId);
- if (!channel) throw new NotFoundError({ message: `Channel with ID '${dto.channelId}' not found` });
-
- await $assertPermission(OrgPermissionActions.Read, channel.orgId, channel.projectId, actor);
-
- const { decryptor } = await getAlertChannelCipher(kmsService, {
- orgId: channel.orgId,
- projectId: channel.projectId
- });
- const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);
- const [recipients, usageCount] = await Promise.all([
- alertChannelRecipientDAL.findByChannelId(channel.id),
- $countUsage(channel.id)
- ]);
- return $buildDetail(
- channel,
- config,
- recipients.map((r) => ({ principalType: r.principalType, principalId: r.principalId })),
- usageCount
- );
- };
-
- const listChannels = async (dto: TListAlertChannelsDTO): Promise<TAlertChannelDetail[]> => {
- const actor: TGenericPermission = {
- actor: dto.actor,
- actorId: dto.actorId,
- actorAuthMethod: dto.actorAuthMethod,
- actorOrgId: dto.actorOrgId
- };
- await $assertPermission(OrgPermissionActions.Read, dto.actorOrgId, dto.projectId, actor);
-
- const scope = { orgId: dto.actorOrgId, projectId: dto.projectId ?? null };
- const channels = await alertChannelDAL.findWithUsageByScope(scope);
- if (channels.length === 0) return [];
-
- const [recipients, { decryptor }] = await Promise.all([
- alertChannelRecipientDAL.findByChannelIds(channels.map((c) => c.id)),
- getAlertChannelCipher(kmsService, scope)
- ]);
-
- const recipientsByChannel = new Map<string, { principalType: string; principalId: string }[]>();
- recipients.forEach((r) => {
- const list = recipientsByChannel.get(r.channelId) ?? [];
- list.push({ principalType: r.principalType, principalId: r.principalId });
- recipientsByChannel.set(r.channelId, list);
- });
-
- return channels.map((channel) => {
- const config = decryptChannelConfig<Record<string, unknown>>(channel.encryptedConfig, decryptor);
- return $buildDetail(channel, config, recipientsByChannel.get(channel.id) ?? [], channel.usageCount);
- });
- };
-
return {
- createChannel,
- updateChannel,
- deleteChannel,
- getChannelById,
- listChannels,
createChannelInTx,
updateChannelInTx,
deleteChannelInTx,
diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.ts
index d17fa7ad2a..c85f6e2cd6 100644
--- a/backend/src/services/alert/alert-channel-types.ts
+++ b/backend/src/services/alert/alert-channel-types.ts
@@ -98,8 +98,3 @@ export const PagerDutyChannelConfigSchema = z.object({
.string()
.refine((val) => pagerDutyIntegrationKeyRegex.test(val), "Integration key must be a 32-character hex string")
});
-
-export type TEmailChannelConfig = z.infer<typeof EmailChannelConfigSchema>;
-export type TWebhookChannelConfig = z.infer<typeof WebhookChannelConfigSchema>;
-export type TSlackChannelConfig = z.infer<typeof SlackChannelConfigSchema>;
-export type TPagerDutyChannelConfig = z.infer<typeof PagerDutyChannelConfigSchema>;
diff --git a/backend/src/services/alert/alert-queue.ts b/backend/src/services/alert/alert-queue.ts
index b7fe2a35e0..23f13fa53a 100644
--- a/backend/src/services/alert/alert-queue.ts
+++ b/backend/src/services/alert/alert-queue.ts
@@ -15,8 +15,6 @@ type TAlertQueueServiceFactoryDep = {
alertEngine: Pick<TAlertEngine, "runAlert">;
};
-export type TAlertQueueServiceFactory = ReturnType<typeof alertQueueServiceFactory>;
-
const ALERT_DISPATCH_CONCURRENCY = 5;
export const alertQueueServiceFactory = ({
@@ -76,5 +74,5 @@ export const alertQueueServiceFactory = ({
});
};
- return { init, enqueueDueAlerts };
+ return { init };
};
diff --git a/frontend/src/hooks/api/alerts/mutations.ts b/frontend/src/hooks/api/alerts/mutations.ts
index 5ac8bcfbbe..4176381917 100644
--- a/frontend/src/hooks/api/alerts/mutations.ts
+++ b/frontend/src/hooks/api/alerts/mutations.ts
@@ -23,13 +23,12 @@ export const useUpdateAlert = () => {
const queryClient = useQueryClient();
return useMutation<TAlert, unknown, TUpdateAlertDTO>({
- mutationFn: async ({ alertId, projectId, ...body }) => {
+ mutationFn: async ({ alertId, ...body }) => {
const { data } = await apiRequest.patch<{ alert: TAlert }>(`/api/v1/alerts/${alertId}`, body);
return data.alert;
},
- onSuccess: (_, { alertId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({ queryKey: alertKeys.all });
- queryClient.invalidateQueries({ queryKey: alertKeys.byId(alertId) });
}
});
};
@@ -44,9 +43,8 @@ export const useDeleteAlert = () => {
);
return data.alert;
},
- onSuccess: (_, { alertId }) => {
+ onSuccess: () => {
queryClient.invalidateQueries({ queryKey: alertKeys.all });
- queryClient.invalidateQueries({ queryKey: alertKeys.byId(alertId) });
}
});
};
diff --git a/frontend/src/hooks/api/alerts/queries.ts b/frontend/src/hooks/api/alerts/queries.ts
index 2363fa6226..663af0d037 100644
--- a/frontend/src/hooks/api/alerts/queries.ts
+++ b/frontend/src/hooks/api/alerts/queries.ts
@@ -6,8 +6,7 @@ import { TAlert, TListAlertsDTO } from "./types";
export const alertKeys = {
all: ["alerts"] as const,
- list: (filters: TListAlertsDTO) => [...alertKeys.all, "list", filters] as const,
- byId: (alertId: string) => [...alertKeys.all, alertId] as const
+ list: (filters: TListAlertsDTO) => [...alertKeys.all, "list", filters] as const
};
const fetchAlerts = async (filters: TListAlertsDTO) => {
diff --git a/frontend/src/hooks/api/alerts/types.ts b/frontend/src/hooks/api/alerts/types.ts
index 0de9a7c72e..bfee4ffd99 100644
--- a/frontend/src/hooks/api/alerts/types.ts
+++ b/frontend/src/hooks/api/alerts/types.ts
@@ -58,7 +58,6 @@ export type TAlertChannelEmbedded = {
id: string;
name: string;
channelType: AlertChannelType;
- directed: boolean;
enabled: boolean;
config: Record<string, unknown>;
recipients: TAlertChannelRecipient[];
@@ -84,7 +83,6 @@ export type TListAlertsDTO = {
resourceType: string;
projectId?: string;
resourceId?: string;
- enabled?: boolean;
};
export type TAlertChannelInput = {
@@ -110,7 +108,6 @@ export type TCreateAlertDTO = {
export type TUpdateAlertDTO = {
alertId: string;
- projectId?: string | null;
name?: string;
description?: string | null;
condition?: unknown;
diff --git a/frontend/src/views/AlertsPage/components/AlertForm.tsx b/frontend/src/views/AlertsPage/components/AlertForm.tsx
index 8842fb634e..8b2edfec6a 100644
--- a/frontend/src/views/AlertsPage/components/AlertForm.tsx
+++ b/frontend/src/views/AlertsPage/components/AlertForm.tsx
@@ -216,7 +216,6 @@ export const AlertForm = ({
if (isEditing && alert) {
await updateAlert.mutateAsync({
alertId: alert.id,
- projectId: alert.projectId,
name: data.name,
description: data.description || null,
enabled: data.enabled,