Skip to content

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

refactor(reminders): write reminder alerts as the caller through the public alert API

Calvinb325b1e6b04e
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index 12d1e81493..4be58c6795 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -24,18 +24,13 @@ export type TUpdateAlertDTO = TGenericPermission & {
channels?: TAlertChannelInput[];
};
-// For domain services that own their resource's authorization (eg reminders) and for background
-// work with no actor. They skip the provider's permission check, so callers must check first.
-export type TAlertCreator = { actorType: string; actorId: string | null };
-
-export type TCreateAlertInternalDTO = Omit<TCreateAlertDTO, keyof TGenericPermission | "projectId"> & {
+// What a create writes once the caller has been authorized and the input validated.
+export type TNewAlertRows = Omit<TCreateAlertDTO, keyof TGenericPermission | "projectId"> & {
orgId: string;
projectId: string | null;
- createdBy: TAlertCreator;
+ createdBy: { actorType: string; actorId: string };
};
-export type TUpdateAlertInternalDTO = Omit<TUpdateAlertDTO, keyof TGenericPermission>;
-
export type TGetAlertDTO = TGenericPermission & { alertId: string };
export type TDeleteAlertDTO = TGenericPermission & { alertId: string };
diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.ts
index dcb9bf3d6e..f57683f124 100644
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@ -63,8 +63,6 @@ const buildService = (opts?: {
const alerts = new Map<string, Record<string, unknown>>();
const channels = new Map<string, TChannelRow>(); // channelId -> row
const memberships = new Map<string, string[]>(); // alertId -> channelIds
- const createTxs: unknown[] = [];
- let transactionsOpened = 0;
let channelSeq = 0;
const matches = (row: Record<string, unknown>, filter: Record<string, unknown>) => {
@@ -84,12 +82,8 @@ const buildService = (opts?: {
const service = alertServiceFactory({
alertDAL: {
- transaction: async (cb: (tx: unknown) => unknown) => {
- transactionsOpened += 1;
- return cb({});
- },
- create: async (data: Record<string, unknown>, tx?: unknown) => {
- createTxs.push(tx);
+ transaction: async (cb: (tx: unknown) => unknown) => cb({}),
+ create: async (data: Record<string, unknown>) => {
if (opts?.createError) throw opts.createError;
const row = {
id: "alert-1",
@@ -210,9 +204,7 @@ const buildService = (opts?: {
service,
permissionCalls,
alerts,
- memberships,
- createTxs,
- transactionsOpened: () => transactionsOpened
+ memberships
};
};
@@ -377,64 +369,12 @@ describe("alert service", () => {
expect(permissionCalls.map((call) => call.action)).toContain("delete");
});
-});
-
-describe("alert service internal entry points", () => {
- const internalCreate = {
- name: "Reminder for DB_PASSWORD",
- resourceType: RESOURCE_TYPE,
- resourceId: "resource-1",
- eventType: "test.resource.opened",
- condition: null,
- orgId: "org-1",
- projectId: "proj-1",
- channels: [emailChannel],
- createdBy: { actorType: "platform", actorId: null }
- };
-
- test("createAlertInternal skips the provider permission check and records the given creator", async () => {
- const { service, permissionCalls, alerts } = buildService();
- const alert = await service.createAlertInternal(internalCreate);
-
- expect(permissionCalls).toHaveLength(0);
- expect(alerts.get(alert.id)).toMatchObject({ createdByActorType: "platform", createdByActorId: null });
- expect(alert.channels).toHaveLength(1);
- });
-
- test("createAlertInternal still validates the condition", async () => {
- const { service } = buildService();
- await expect(
- service.createAlertInternal({
- ...internalCreate,
- eventType: "test.resource.expiration",
- condition: { wrong: true }
- })
- ).rejects.toThrow("Invalid alert condition");
- });
-
- test("createAlertInternal writes inside the caller's transaction when given one", async () => {
- const { service, createTxs, transactionsOpened } = buildService();
- const callerTx = { caller: true } as never;
- await service.createAlertInternal(internalCreate, callerTx);
-
- expect(createTxs).toEqual([callerTx]);
- expect(transactionsOpened()).toBe(0);
- });
-
- test("updateAlertInternal skips the provider permission check", async () => {
- const { service, permissionCalls } = buildService();
- const created = await service.createAlertInternal(internalCreate);
- const updated = await service.updateAlertInternal({ alertId: created.id, enabled: false });
-
- expect(permissionCalls).toHaveLength(0);
- expect(updated.enabled).toBe(false);
- });
test("a concurrent duplicate create surfaces as a readable error, not a 500", async () => {
const { service } = buildService({
createError: new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation }, name: "Create" })
});
- await expect(service.createAlertInternal(internalCreate)).rejects.toThrow(
+ await expect(service.createAlert(validCreate)).rejects.toThrow(
"An alert for this resource and event already exists"
);
});
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index dfc6630b9f..d754be93d3 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -17,12 +17,11 @@ import { TAlertProviderRegistry } from "./alert-provider-registry";
import {
TAlertResponse,
TCreateAlertDTO,
- TCreateAlertInternalDTO,
TDeleteAlertDTO,
TGetAlertDTO,
TListAlertsDTO,
- TUpdateAlertDTO,
- TUpdateAlertInternalDTO
+ TNewAlertRows,
+ TUpdateAlertDTO
} from "./alert-service-types";
import { AlertPermissionAction, IResourceAlertProvider, TAlertEventDefinition, toAlertActor } from "./alert-types";
@@ -111,7 +110,7 @@ export const alertServiceFactory = ({
});
const $createAlertRows = async (
- input: TCreateAlertInternalDTO,
+ input: TNewAlertRows,
event: TAlertEventDefinition,
cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,
tx: Knex
@@ -216,7 +215,7 @@ export const alertServiceFactory = ({
throw new BadRequestError({ message: "At least one channel is required" });
}
- const input: TCreateAlertInternalDTO = {
+ const input: TNewAlertRows = {
name: dto.name,
description: dto.description,
resourceType: dto.resourceType,
@@ -355,7 +354,7 @@ export const alertServiceFactory = ({
const $updateAlertRows = async (
alert: TAlerts,
- input: TUpdateAlertInternalDTO,
+ input: Omit<TUpdateAlertDTO, keyof TGenericPermission>,
cipher: Awaited<ReturnType<typeof getAlertChannelCipher>>,
tx: Knex
): Promise<TAlertResponse> => {
@@ -471,36 +470,6 @@ export const alertServiceFactory = ({
tx?: Knex
): Promise<number> => $reapAlerts({ resourceType, resourceId }, tx);
- const createAlertInternal = async (input: TCreateAlertInternalDTO, tx?: Knex): Promise<TAlertResponse> => {
- const provider = $getProvider(input.resourceType);
- const event = $getEvent(provider, input.eventType);
- $validateCondition(event, input.condition);
- if (input.channels.length === 0) {
- throw new BadRequestError({ message: "At least one channel is required" });
- }
-
- const cipher = await getAlertChannelCipher(kmsService, input, tx);
- return tx
- ? $createAlertRows(input, event, cipher, tx)
- : alertDAL.transaction((trx) => $createAlertRows(input, event, cipher, trx));
- };
-
- const updateAlertInternal = async (input: TUpdateAlertInternalDTO, tx?: Knex): Promise<TAlertResponse> => {
- const alert = await alertDAL.findActiveById(input.alertId, tx);
- if (!alert) throw new NotFoundError({ message: `Alert with ID '${input.alertId}' not found` });
-
- const provider = $getProvider(alert.resourceType);
- if (input.condition !== undefined) $validateCondition($getEvent(provider, alert.eventType), input.condition);
- if (input.channels !== undefined && input.channels.length === 0) {
- throw new BadRequestError({ message: "At least one channel is required" });
- }
-
- const cipher = await getAlertChannelCipher(kmsService, { orgId: alert.orgId, projectId: alert.projectId }, tx);
- return tx
- ? $updateAlertRows(alert, input, cipher, tx)
- : alertDAL.transaction((trx) => $updateAlertRows(alert, input, cipher, trx));
- };
-
const findAlertsForResources = async (
{ resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },
tx?: Knex
@@ -577,8 +546,6 @@ export const alertServiceFactory = ({
deleteAlert,
deleteAlertsForResource,
deleteAlertsForDeletedResource,
- createAlertInternal,
- updateAlertInternal,
findAlertsForResources,
deleteAlertsForDeletedResources,
repointAlertsForResource,
diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.ts
index ebe40189a7..12a6feb703 100644
--- a/backend/src/services/reminder/reminder-service.test.ts
+++ b/backend/src/services/reminder/reminder-service.test.ts
@@ -249,15 +249,15 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
filterRecipientsInScope: async (_scope: unknown, recipients: { principalType: string; principalId: string }[]) =>
opts.projectUserIds ? recipients.filter((r) => opts.projectUserIds!.includes(r.principalId)) : recipients,
findAlertsForResources: async () => (opts.existingAlert ? [opts.existingAlert] : []),
- createAlertInternal: async (input: unknown) => {
+ createAlert: async (input: unknown) => {
calls.push("alert:create");
created.push(input);
return input;
},
- updateAlertInternal: async (input: { alertId: string; name?: string; channels?: unknown[] }) => {
+ updateAlert: async ({ alertId, name, channels }: { alertId: string; name?: string; channels?: unknown[] }) => {
calls.push("alert:update");
- updated.push(input);
- return input;
+ updated.push({ alertId, name, channels });
+ return { alertId, name, channels };
},
findRecipientsForResources: async ({ resourceIds }: { resourceIds: string[] }) =>
resourceIds.map((resourceId) => ({ resourceId, principalId: "user-1" })),
@@ -276,18 +276,21 @@ const buildWriteService = (opts: { existingAlert?: TStoredAlert; projectUserIds?
return { service, calls, created, updated, deletedAlerts, repointed };
};
-const createInput = (recipients?: string[] | null) => ({
- secretId: "secret-1",
- projectId: "proj-1",
- repeatDays: 30,
- message: "rotate it",
- recipients
-});
+const caller = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null };
+
+const saveReminder = (
+ service: ReturnType<typeof buildWriteService>["service"],
+ fields: { recipients?: string[] | null; channels?: unknown[] }
+) =>
+ service.createReminder({
+ ...caller,
+ reminder: { secretId: "secret-1", repeatDays: 30, message: "rotate it", ...fields }
+ } as never);
describe("reminder alert sync", () => {
- test("a new reminder gets an alert with an email channel to its recipients, created by the platform", async () => {
+ test("a new reminder gets an alert with an email channel to its recipients, written as the caller", async () => {
const { service, created } = buildWriteService();
- await service.createReminderInternal(createInput(["user-1", "user-2"]));
+ await saveReminder(service, { recipients: ["user-1", "user-2"] });
expect(created).toEqual([
expect.objectContaining({
@@ -295,9 +298,8 @@ describe("reminder alert sync", () => {
resourceType: SECRET_REMINDER_RESOURCE_TYPE,
resourceId: "secret-1",
eventType: SECRET_REMINDER_DUE_EVENT,
- orgId: "org-1",
projectId: "proj-1",
- createdBy: { actorType: "platform", actorId: null },
+ ...caller,
channels: [
{
name: "Email",
@@ -314,13 +316,13 @@ describe("reminder alert sync", () => {
test("syncs the alert before writing the reminder, so a reminder never exists without one", async () => {
const { service, calls } = buildWriteService();
- await service.createReminderInternal(createInput(["user-1"]));
+ await saveReminder(service, { recipients: ["user-1"] });
expect(calls).toEqual(["alert:create", "reminder:create"]);
});
test("no recipients means everyone in the project", async () => {
const { service, created } = buildWriteService();
- await service.createReminderInternal(createInput([]));
+ await saveReminder(service, { recipients: [] });
expect((created[0] as { channels: { recipients: unknown }[] }).channels[0].recipients).toEqual([
{ principalType: "project-members", principalId: "proj-1" }
]);
@@ -328,7 +330,7 @@ describe("reminder alert sync", () => {
test("recipients who left the project are dropped instead of failing the write", async () => {
const { service, created } = buildWriteService({ projectUserIds: ["user-1"] });
- await service.createReminderInternal(createInput(["user-1", "user-gone"]));
+ await saveReminder(service, { recipients: ["user-1", "user-gone"] });
expect((created[0] as { channels: { recipients: unknown }[] }).channels[0].recipients).toEqual([
{ principalType: "user", principalId: "user-1" }
]);
@@ -336,7 +338,7 @@ describe("reminder alert sync", () => {
test("refuses a recipient list with nobody left in the project rather than sending to everyone", async () => {
const { service, calls } = buildWriteService({ projectUserIds: [] });
- await expect(service.createReminderInternal(createInput(["user-gone"]))).rejects.toThrow(
+ await expect(saveReminder(service, { recipients: ["user-gone"] })).rejects.toThrow(
/None of the selected reminder recipients/
);
expect(calls).toEqual([]);
@@ -352,13 +354,7 @@ describe("reminder alert sync", () => {
{ name: "Webhook", channelType: "webhook", config: { url: "https://example.com" } }
];
const save = (service: ReturnType<typeof buildWriteService>["service"]) =>
- service.createReminder({
- actor: "user",
- actorId: "user-1",
- actorOrgId: "org-1",
- actorAuthMethod: null,
- reminder: { secretId: "secret-1", repeatDays: 30, recipients: ["user-1"], channels }
- } as never);
+ saveReminder(service, { recipients: ["user-1"], channels });
const existing = buildWriteService({
existingAlert: { id: "alert-1", name: "Reminder for OLD_NAME", resourceId: "secret-1", channels: [] }
@@ -373,7 +369,7 @@ describe("reminder alert sync", () => {
test("more than 20 recipients are split across email channels", async () => {
const { service, created } = buildWriteService();
- await service.createReminderInternal(createInput(Array.from({ length: 45 }, (_, i) => `user-${i}`)));
+ await saveReminder(service, { recipients: Array.from({ length: 45 }, (_, i) => `user-${i}`) });
const { channels } = created[0] as { channels: { name: string; recipients: unknown[] }[] };
expect(channels.map((c) => c.name)).toEqual(["Email", "Email 2", "Email 3"]);
expect(channels.map((c) => c.recipients.length)).toEqual([20, 20, 5]);
@@ -391,7 +387,7 @@ describe("reminder alert sync", () => {
]
}
});
- await service.createReminderInternal(createInput(["user-1"]));
+ await saveReminder(service, { recipients: ["user-1"] });
expect(created).toHaveLength(0);
expect(updated).toEqual([
diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.ts
index 7f849cd072..63a09afd3d 100644
--- a/backend/src/services/reminder/reminder-service.ts
+++ b/backend/src/services/reminder/reminder-service.ts
@@ -8,6 +8,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { ProjectPermissionSecretActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { TGenericPermission } from "@app/lib/types";
import { TAlertChannelInput } from "../alert/alert-channel-service-types";
import { AlertChannelType } from "../alert/alert-channel-types";
@@ -34,8 +35,8 @@ type TReminderServiceFactoryDep = {
eventEmitter: TEventEmitter;
alertService: Pick<
TAlertServiceFactory,
- | "createAlertInternal"
- | "updateAlertInternal"
+ | "createAlert"
+ | "updateAlert"
| "findAlertsForResources"
| "findRecipientsForResources"
| "deleteAlertsForDeletedResources"
@@ -83,21 +84,22 @@ export const reminderServiceFactory = ({
// Given `channels`, they are the alert's complete channel list. Otherwise the reminder API only knows
// user ids, so it owns the alert's email channels and leaves every other channel (Slack, webhook,
// PagerDuty) as the user configured it. An empty list keeps the reminder's original meaning: everyone
- // in the project.
+ // in the project. The alert is written as the caller, so the reminder provider checks they can edit
+ // the secret.
const $syncReminderAlert = async ({
secretId,
secretKey,
projectId,
recipients,
channels,
- createdBy
+ actor
}: {
secretId: string;
secretKey: string;
projectId: string;
recipients?: string[] | null;
channels?: TAlertChannelInput[];
- createdBy: { actorType: ActorType; actorId: string | null };
+ actor: TGenericPermission;
}) => {
const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
@@ -107,22 +109,30 @@ export const reminderServiceFactory = ({
resourceIds: [secretId]
});
- if (channels) {
+ const $writeAlert = async (alertChannels: TAlertChannelInput[]) => {
if (existing) {
- await alertService.updateAlertInternal({ alertId: existing.id, name: reminderAlertName(secretKey), channels });
- } else {
- await alertService.createAlertInternal({
+ await alertService.updateAlert({
+ alertId: existing.id,
name: reminderAlertName(secretKey),
- resourceType: SECRET_REMINDER_RESOURCE_TYPE,
- resourceId: secretId,
- eventType: SECRET_REMINDER_DUE_EVENT,
- condition: null,
- orgId: project.orgId,
- projectId,
- channels,
- createdBy
+ channels: alertChannels,
+ ...actor
});
+ return;
}
+ await alertService.createAlert({
+ name: reminderAlertName(secretKey),
+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,
+ resourceId: secretId,
+ eventType: SECRET_REMINDER_DUE_EVENT,
+ condition: null,
+ projectId,
+ channels: alertChannels,
+ ...actor
+ });
+ };
+
+ if (channels) {
+ await $writeAlert(channels);
return;
}
@@ -156,22 +166,7 @@ export const reminderServiceFactory = ({
});
}
- if (!existing) {
- await alertService.createAlertInternal({
- name: reminderAlertName(secretKey),
- resourceType: SECRET_REMINDER_RESOURCE_TYPE,
- resourceId: secretId,
- eventType: SECRET_REMINDER_DUE_EVENT,
- condition: null,
- orgId: project.orgId,
- projectId,
- channels: emailChannels,
- createdBy
- });
- return;
- }
-
- const otherChannels: TAlertChannelInput[] = existing.channels
+ const otherChannels: TAlertChannelInput[] = (existing?.channels ?? [])
.filter((channel) => channel.channelType !== AlertChannelType.EMAIL)
.map((channel) => ({
id: channel.id,
@@ -180,11 +175,7 @@ export const reminderServiceFactory = ({
enabled: channel.enabled
}));
- await alertService.updateAlertInternal({
- alertId: existing.id,
- name: reminderAlertName(secretKey),
- channels: [...emailChannels, ...otherChannels]
- });
+ await $writeAlert([...emailChannels, ...otherChannels]);
};
const $getSecretForPermissionCheck = async (secretId: string) => {
@@ -221,7 +212,7 @@ export const reminderServiceFactory = ({
channels,
projectId,
fromDate: fromDateInput,
- createdBy
+ actor
}: {
secretId: string;
secretKey: string;
@@ -232,7 +223,7 @@ export const reminderServiceFactory = ({
channels?: TAlertChannelInput[];
fromDate?: string | null;
projectId: string;
- createdBy: { actorType: ActorType; actorId: string | null };
+ actor: TGenericPermission;
}) => {
let nextReminderDate;
let fromDate;
@@ -255,7 +246,7 @@ export const reminderServiceFactory = ({
// The alert goes first, outside any transaction because encrypting channel config can call out to
// KMS. If the reminder write then fails, an alert with no reminder never fires and is reused next time.
- await $syncReminderAlert({ secretId, secretKey, projectId, recipients, channels, createdBy });
+ await $syncReminderAlert({ secretId, secretKey, projectId, recipients, channels, actor });
const existingReminder = await reminderDAL.findOne({ secretId });
let reminderId: string;
@@ -283,28 +274,6 @@ export const reminderServiceFactory = ({
return { id: reminderId, created: !existingReminder };
};
- const createReminderInternal: TReminderServiceFactory["createReminderInternal"] = async ({
- secretId,
- projectId,
- ...reminder
- }) => {
- if (!secretId) {
- throw new BadRequestError({ message: "secretId is required" });
- }
- const secret = await secretV2BridgeDAL.findOneWithTags({ [`${TableName.SecretV2}.id` as "id"]: secretId });
- if (!secret) {
- throw new NotFoundError({ message: `Secret with ID '${secretId}' not found` });
- }
-
- return $saveReminder({
- ...reminder,
- secretId,
- secretKey: secret.key,
- projectId,
- createdBy: { actorType: ActorType.PLATFORM, actorId: null }
- });
- };
-
const createReminder: TReminderServiceFactory["createReminder"] = async ({
actor,
actorId,
@@ -331,7 +300,7 @@ export const reminderServiceFactory = ({
secretId: secret.id,
secretKey: secret.key,
projectId: secret.projectId,
- createdBy: { actorType: actor, actorId }
+ actor: { actor, actorId, actorOrgId, actorAuthMethod }
});
};
@@ -598,7 +567,6 @@ export const reminderServiceFactory = ({
deleteReminderBySecretId,
batchCreateReminders,
moveReminderAlerts,
- createReminderInternal,
getRemindersForDashboard
};
};
diff --git a/backend/src/services/reminder/reminder-types.ts b/backend/src/services/reminder/reminder-types.ts
index 0b05fcea3b..2a2459b90b 100644
--- a/backend/src/services/reminder/reminder-types.ts
+++ b/backend/src/services/reminder/reminder-types.ts
@@ -89,25 +89,5 @@ export interface TReminderServiceFactory {
moveReminderAlerts: (moves: { fromSecretId: string; toSecretId: string }[], tx: Knex) => Promise<void>;
- createReminderInternal: ({
- secretId,
- message,
- repeatDays,
- nextReminderDate,
- recipients,
- projectId
- }: {
- secretId?: string;
- message?: string | null;
- repeatDays?: number | null;
- nextReminderDate?: string | null;
- recipients?: string[] | null;
- projectId: string;
- fromDate?: string | null;
- }) => Promise<{
- id: string;
- created: boolean;
- }>;
-
getRemindersForDashboard: (secretIds: string[]) => Promise<Record<string, TReminder & { recipients: string[] }>>;
}
diff --git a/backend/src/services/secret/secret-queue.ts b/backend/src/services/secret/secret-queue.ts
index 99cb2d2495..f487666847 100644
--- a/backend/src/services/secret/secret-queue.ts
+++ b/backend/src/services/secret/secret-queue.ts
@@ -1,4 +1,5 @@
/* eslint-disable no-await-in-loop */
+import { ForbiddenError } from "@casl/ability";
import { AxiosError } from "axios";
import { randomUUID } from "crypto";
import { Knex } from "knex";
@@ -124,7 +125,7 @@ type TSecretQueueFactoryDep = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;
secretSyncQueue: Pick<TSecretSyncQueueFactory, "queueSecretSyncsSyncSecretsByPath">;
- reminderService: Pick<TReminderServiceFactory, "createReminderInternal" | "deleteReminderBySecretId">;
+ reminderService: Pick<TReminderServiceFactory, "createReminder" | "deleteReminderBySecretId">;
projectEventsService: TProjectEventsService;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
@@ -276,7 +277,7 @@ export const secretQueueFactory = ({
const addSecretReminder = async ({
oldSecret,
newSecret,
- projectId,
+ actor,
secretReminderRecipients
}: TCreateSecretReminderDTO) => {
try {
@@ -294,16 +295,18 @@ export const secretQueueFactory = ({
});
}
- await reminderService.createReminderInternal({
- secretId: newSecret.id,
- message: newSecret.secretReminderNote,
- repeatDays: newSecret.secretReminderRepeatDays,
- recipients: secretReminderRecipients,
- projectId
+ await reminderService.createReminder({
+ ...actor,
+ reminder: {
+ secretId: newSecret.id,
+ message: newSecret.secretReminderNote,
+ repeatDays: newSecret.secretReminderRepeatDays,
+ recipients: secretReminderRecipients
+ }
});
} catch (err) {
logger.error(err, "Failed to create secret reminder.");
- if (err instanceof BadRequestError) throw err;
+ if (err instanceof BadRequestError || err instanceof ForbiddenError) throw err;
throw new BadRequestError({
name: "SecretReminderCreateFailed",
message: "Failed to create secret reminder."
@@ -311,7 +314,7 @@ export const secretQueueFactory = ({
}
};
- const handleSecretReminder = async ({ newSecret, oldSecret, projectId }: THandleReminderDTO) => {
+ const handleSecretReminder = async ({ newSecret, oldSecret, projectId, actor }: THandleReminderDTO) => {
const { secretReminderRepeatDays, secretReminderNote, secretReminderRecipients } = newSecret;
if (newSecret.type !== SecretType.Personal && secretReminderRepeatDays !== undefined) {
@@ -323,6 +326,7 @@ export const secretQueueFactory = ({
oldSecret,
newSecret,
projectId,
+ actor,
secretReminderRecipients: secretReminderRecipients ?? [],
deleteRecipients: false
});
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index 4c2565c69b..c4a0e96769 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -429,7 +429,8 @@ export const secretServiceFactory = ({
...inputSecret
},
oldSecret: secrets[0],
- projectId
+ projectId,
+ actor: { actor, actorId, actorOrgId, actorAuthMethod }
});
const tags = inputSecret.tags ? await secretTagDAL.findManyTagsById(projectId, inputSecret.tags) : [];
diff --git a/backend/src/services/secret/secret-types.ts b/backend/src/services/secret/secret-types.ts
index 29388f8903..16b9c9ee36 100644
--- a/backend/src/services/secret/secret-types.ts
+++ b/backend/src/services/secret/secret-types.ts
@@ -10,7 +10,7 @@ import {
TSecretsUpdate
} from "@app/db/schemas";
import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";
-import { OrderByDirection, TProjectPermission } from "@app/lib/types";
+import { OrderByDirection, TGenericPermission, TProjectPermission } from "@app/lib/types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
import { TSecretDALFactory } from "@app/services/secret/secret-dal";
@@ -443,12 +443,15 @@ export type THandleReminderDTO = {
newSecret: TPartialInputSecret;
oldSecret: TPartialSecret;
projectId: string;
+ // Whoever is updating the secret, as whom the reminder is saved.
+ actor: TGenericPermission;
};
export type TCreateSecretReminderDTO = {
oldSecret: TPartialSecret;
newSecret: TPartialSecret;
projectId: string;
+ actor: TGenericPermission;
secretReminderRecipients: string[];
deleteRecipients?: boolean;