Skip to content

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

fix(reminders): second round of review fixes and the e2e isolation leaks

Calvin5012fcb06089
diff --git a/backend/e2e-test/encryption-key-rotation.spec.ts b/backend/e2e-test/encryption-key-rotation.spec.ts
index 717f0c0d69..9c3766e2e1 100644
--- a/backend/e2e-test/encryption-key-rotation.spec.ts
+++ b/backend/e2e-test/encryption-key-rotation.spec.ts
@@ -1,5 +1,6 @@
-import { beforeAll, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { TableName, TKmsRootConfig } from "@app/db/schemas";
import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";
import { getConfig, initEnvConfig, TEnvConfig } from "@app/lib/config/env";
import { TCronJobFactory } from "@app/lib/cron/cron-job";
@@ -23,7 +24,7 @@ import { projectDALFactory } from "@app/services/project/project-dal";
// calls: promotion happens only when an *instance* starts with a key that matches a staged row. Each
// "instance" below is a fresh KMS service whose env carries a different key, booted against the same
// database the test server is running on. The tests form one saga — each builds on the state the
-// previous one left — and the file gets a freshly migrated database from the environment setup.
+// previous one left.
// Simulates a separate instance booting with `key` as its configured encryption key.
const bootInstanceWithKey = async (key: string) => {
@@ -76,11 +77,24 @@ describe("encryption key rotation: boot-time promotion", () => {
stop: async () => {}
};
+ // Every spec file shares this database, and the saga leaves the root key wrapped with keys the
+ // environment does not carry. Restoring the rows keeps a later file that boots its own KMS (eg a
+ // data migration run from a spec) on the configured key.
+ let rootConfigRows: TKmsRootConfig[] = [];
+
beforeAll(async () => {
// Spec files run in a separate module graph from the test server, so the env config and the
// cryptography module must be initialized here as well (same process env, same result).
initLogger();
await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);
+ rootConfigRows = await testDb(TableName.KmsServerRootConfig).select("*");
+ });
+
+ afterAll(async () => {
+ await testDb.transaction(async (tx) => {
+ await tx(TableName.KmsServerRootConfig).delete();
+ await tx(TableName.KmsServerRootConfig).insert(rootConfigRows);
+ });
});
let originalLabel: string;
diff --git a/backend/e2e-test/fakes/event-outbox-queue.ts b/backend/e2e-test/fakes/event-outbox-queue.ts
index b5506e8649..2e7365e0ad 100644
--- a/backend/e2e-test/fakes/event-outbox-queue.ts
+++ b/backend/e2e-test/fakes/event-outbox-queue.ts
@@ -16,7 +16,9 @@ const globalScope = globalThis as typeof globalThis & {
};
export const eventOutboxQueueFactory: typeof RealEventOutboxQueue.eventOutboxQueueFactory = (deps) => {
- globalScope.infisicalEventOutboxService = deps.eventOutboxService;
+ // The shared test server boots first. A spec that boots and closes a second server of its own (eg
+ // api-run-modes.spec.ts) must not take the handle, or later specs would drive that closed server.
+ globalScope.infisicalEventOutboxService ??= deps.eventOutboxService;
return RealEventOutboxQueue.eventOutboxQueueFactory(deps);
};
diff --git a/backend/e2e-test/fakes/reminder-queue.ts b/backend/e2e-test/fakes/reminder-queue.ts
index dc1b830798..901a6b6c21 100644
--- a/backend/e2e-test/fakes/reminder-queue.ts
+++ b/backend/e2e-test/fakes/reminder-queue.ts
@@ -17,7 +17,9 @@ const globalScope = globalThis as typeof globalThis & {
};
export const dailyReminderQueueServiceFactory: typeof RealReminderQueue.dailyReminderQueueServiceFactory = (deps) => {
- globalScope.infisicalReminderService = deps.reminderService;
+ // The shared test server boots first. A spec that boots and closes a second server of its own (eg
+ // api-run-modes.spec.ts) must not take the handle, or later specs would drive that closed server.
+ globalScope.infisicalReminderService ??= deps.reminderService;
return RealReminderQueue.dailyReminderQueueServiceFactory(deps);
};
diff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
index 4d97e9cff3..860a828e2d 100644
--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts
@@ -14,7 +14,7 @@ import {
waitForReminderEmails
} from "../../testUtils/reminders";
import { createSecretV2, getSecretByNameV2 } from "../../testUtils/secrets";
-import { addUserMembership, createUser } from "../../testUtils/users";
+import { addUserMembership, createUser, deleteUsers } from "../../testUtils/users";
const ENVIRONMENT = "dev";
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -33,17 +33,26 @@ describe("Secret reminders delivered through alerts", () => {
let cleanup: () => Promise<void>;
// A project member other than the caller, so a reminder's recipients are never just whoever set it.
let member: { userId: string; username: string };
+ let createdUserIds: string[] = [];
+
+ const newUser = async (label: string) => {
+ const user = await createUser(label);
+ createdUserIds.push(user.userId);
+ return user;
+ };
beforeEach(async () => {
let orgId: string;
({ orgId, projectId, authToken, cleanup } = await createIsolatedOrgAndProject("reminders"));
- member = await createUser("reminder-recipient");
+ member = await newUser("reminder-recipient");
await addUserMembership({ userId: member.userId, orgId, role: OrgMembershipRole.Member });
await addUserMembership({ userId: member.userId, orgId, projectId, role: ProjectMembershipRole.Member });
});
afterEach(async () => {
await cleanup();
+ await deleteUsers(createdUserIds);
+ createdUserIds = [];
});
const createSecret = async (key: string, opts: { secretPath?: string } = {}) => {
@@ -231,7 +240,7 @@ describe("Secret reminders delivered through alerts", () => {
const secretId = await createSecret("MIGRATE");
const everyoneSecretId = await createSecret("MIGRATE_EVERYONE");
const nobodyLeftSecretId = await createSecret("MIGRATE_NOBODY_LEFT");
- const outsider = await createUser("reminder-outsider");
+ const outsider = await newUser("reminder-outsider");
const dueDate = new Date(Date.now() + DAY_MS);
const reminderId = await seedReminder(secretId, { repeatDays: 30, nextReminderDate: dueDate });
await seedReminder(everyoneSecretId, { repeatDays: 7, nextReminderDate: dueDate });
diff --git a/backend/e2e-test/testUtils/users.ts b/backend/e2e-test/testUtils/users.ts
index f7c6e6f497..7d4f98f039 100644
--- a/backend/e2e-test/testUtils/users.ts
+++ b/backend/e2e-test/testUtils/users.ts
@@ -13,6 +13,13 @@ export const createUser = async (label: string) => {
return { userId: (user as { id: string }).id, username };
};
+// Spec files share one database, so a spec deletes the users it created. Removes their memberships too.
+export const deleteUsers = async (userIds: string[]) => {
+ if (userIds.length === 0) return;
+ await testDb(TableName.Membership).whereIn("actorUserId", userIds).delete();
+ await testDb(TableName.Users).whereIn("id", userIds).delete();
+};
+
// Org memberships are written as accepted, the state a member who joined is in. Anything that
// resolves members (alert recipients, for one) skips a membership that is still invited.
export const addUserMembership = async (dto: {
diff --git a/backend/src/server/routes/v1/alert-channel-schemas.ts b/backend/src/server/routes/v1/alert-channel-schemas.ts
index e9ee22c904..74c0775aec 100644
--- a/backend/src/server/routes/v1/alert-channel-schemas.ts
+++ b/backend/src/server/routes/v1/alert-channel-schemas.ts
@@ -3,15 +3,23 @@ import { z } from "zod";
import { AlertChannelType } from "@app/services/alert/alert-channel-types";
import { AlertPrincipalType, MAX_RECIPIENTS_PER_CHANNEL } from "@app/services/alert/alert-types";
+// Each channel type validates its own fields in the alert module; this only stops an oversized body
+// from reaching it.
+const MAX_CHANNEL_CONFIG_LENGTH = 8192;
+const ChannelConfigSchema = z
+ .record(z.unknown())
+ .refine((config) => JSON.stringify(config).length <= MAX_CHANNEL_CONFIG_LENGTH, "Channel config is too large");
+
export const ChannelRecipientSchema = z.object({
principalType: z.nativeEnum(AlertPrincipalType),
- principalId: z.string().min(1)
+ // A user or group id, or the project's id for project members. Older project ids are not UUIDs.
+ principalId: z.string().trim().min(1).max(255)
});
export const CreateChannelInputSchema = z.object({
name: z.string().min(1).max(255),
channelType: z.nativeEnum(AlertChannelType),
- config: z.record(z.unknown()).default({}),
+ config: ChannelConfigSchema.default({}),
enabled: z.boolean().optional(),
recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
});
@@ -20,7 +28,7 @@ export const UpdateChannelInputSchema = z.object({
id: z.string().uuid().optional(),
name: z.string().min(1).max(255),
channelType: z.nativeEnum(AlertChannelType),
- config: z.record(z.unknown()).optional(),
+ config: ChannelConfigSchema.optional(),
enabled: z.boolean().optional(),
recipients: z.array(ChannelRecipientSchema).max(MAX_RECIPIENTS_PER_CHANNEL).optional()
});
diff --git a/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts b/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts
index ebd7396678..d39e92c0c8 100644
--- a/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts
+++ b/backend/src/server/routes/v1/reminder-routers/secret-reminder-router.ts
@@ -5,7 +5,7 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { MAX_CHANNELS_PER_ALERT } from "@app/services/alert/alert-types";
+import { MAX_CHANNELS_PER_ALERT, MAX_RECIPIENTS_PER_CHANNEL } from "@app/services/alert/alert-types";
import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -28,7 +28,12 @@ export const registerSecretReminderRouter = async (server: FastifyZodProvider) =
repeatDays: z.number().min(1).nullable().optional(),
nextReminderDate: z.string().datetime().nullable().optional(),
fromDate: z.string().datetime().nullable().optional(),
- recipients: z.string().array().optional(),
+ recipients: z
+ .string()
+ .uuid()
+ .array()
+ .max(MAX_RECIPIENTS_PER_CHANNEL * MAX_CHANNELS_PER_ALERT)
+ .optional(),
// The reminder alert's complete channel list, saved with the schedule. Replaces `recipients`.
channels: z.array(UpdateChannelInputSchema).min(1).max(MAX_CHANNELS_PER_ALERT).optional()
})
diff --git a/backend/src/services/alert/alert-channel-types.ts b/backend/src/services/alert/alert-channel-types.ts
index 31801a2e88..5f8963e50e 100644
--- a/backend/src/services/alert/alert-channel-types.ts
+++ b/backend/src/services/alert/alert-channel-types.ts
@@ -82,6 +82,7 @@ export const EmailChannelConfigSchema = z.object({}).strip();
export const WebhookChannelConfigSchema = z.object({
url: z
.string()
+ .max(2048)
.url()
.refine((url) => url.startsWith("https://"), "Webhook URL must use HTTPS"),
signingSecret: z.string().max(256).optional().nullable()
@@ -90,6 +91,7 @@ export const WebhookChannelConfigSchema = z.object({
export const SlackChannelConfigSchema = z.object({
webhookUrl: z
.string()
+ .max(2048)
.url()
.refine((url) => url.startsWith("https://"), "Slack webhook URL must use HTTPS")
.refine((url) => {
@@ -102,5 +104,8 @@ export const SlackChannelConfigSchema = z.object({
});
export const PagerDutyChannelConfigSchema = z.object({
- integrationKey: z.string().refine((val) => pagerDutyIntegrationKeyRegex.test(val), PAGERDUTY_INTEGRATION_KEY_ERROR)
+ integrationKey: z
+ .string()
+ .max(256)
+ .refine((val) => pagerDutyIntegrationKeyRegex.test(val), PAGERDUTY_INTEGRATION_KEY_ERROR)
});
diff --git a/backend/src/services/alert/providers/secret-reminder-alert-dal.ts b/backend/src/services/alert/providers/secret-reminder-alert-dal.ts
index 0ac15ab0f0..d46c79f7b3 100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-dal.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-dal.ts
@@ -61,5 +61,7 @@ export const secretReminderAlertDALFactory = (db: TDbClient) => {
}
};
- return { findReminderSecrets };
+ const primaryNode = () => db.primaryNode();
+
+ return { findReminderSecrets, primaryNode };
};
diff --git a/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts b/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
index 7089430c23..b33ea89dc3 100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-provider.test.ts
@@ -27,15 +27,18 @@ const SECRET: TReminderSecret = {
tagSlugs: ["payments"]
};
-const buildProvider = (opts: { secrets?: TReminderSecret[]; rules?: { action: string; subject: string }[] } = {}) => {
+const buildProvider = (
+ opts: { secrets?: TReminderSecret[]; rules?: { action: string; subject: string }[]; unresolvedPath?: boolean } = {}
+) => {
const permissionCalls: unknown[] = [];
const provider = secretReminderAlertProviderFactory({
secretReminderAlertDAL: {
findReminderSecrets: async (ids: string[]) =>
- (opts.secrets ?? [SECRET]).filter((secret) => ids.includes(secret.secretId))
+ (opts.secrets ?? [SECRET]).filter((secret) => ids.includes(secret.secretId)),
+ primaryNode: () => ({}) as never
},
folderDAL: {
- findSecretPathByFolderIds: async () => [{ id: "folder-1", path: "/payments" }]
+ findSecretPathByFolderIds: async () => (opts.unresolvedPath ? [] : [{ id: "folder-1", path: "/payments" }])
} as never,
permissionService: {
getProjectPermission: async (input: unknown) => {
@@ -114,6 +117,11 @@ describe("secret reminder alert provider", () => {
expect(await provider.findTargetsByIds(dueEvent())).toEqual([]);
});
+ test("drops a secret whose folder path cannot be resolved", async () => {
+ const { provider } = buildProvider({ unresolvedPath: true });
+ expect(await provider.findTargetsByIds(dueEvent())).toEqual([]);
+ });
+
test("drops a secret that does not belong to the event's project", async () => {
const { provider } = buildProvider({ secrets: [{ ...SECRET, projectId: "proj-2" }] });
expect(await provider.findTargetsByIds(dueEvent())).toEqual([]);
@@ -221,6 +229,20 @@ describe("secret reminder alert provider", () => {
).rejects.toThrow("not found in this project");
});
+ test("refuses to authorize a secret whose folder path cannot be resolved, rather than checking the root", async () => {
+ const { provider, permissionCalls } = buildProvider({ unresolvedPath: true });
+ await expect(
+ provider.assertPermission({
+ action: AlertPermissionAction.Edit,
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceId: "secret-1",
+ actor
+ })
+ ).rejects.toThrow("Secret with ID 'secret-1' not found in this project");
+ expect(permissionCalls).toHaveLength(0);
+ });
+
test("rejects an org-scoped reminder alert", async () => {
const { provider } = buildProvider();
await expect(
diff --git a/backend/src/services/alert/providers/secret-reminder-alert-provider.ts b/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
index bec99eec7c..e423a8cf62 100644
--- a/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
+++ b/backend/src/services/alert/providers/secret-reminder-alert-provider.ts
@@ -37,7 +37,7 @@ export type TSecretReminderTarget = TReminderSecret & {
};
export type TSecretReminderAlertProviderDep = {
- secretReminderAlertDAL: Pick<TSecretReminderAlertDALFactory, "findReminderSecrets">;
+ secretReminderAlertDAL: Pick<TSecretReminderAlertDALFactory, "findReminderSecrets" | "primaryNode">;
folderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
};
@@ -68,13 +68,24 @@ export const secretReminderAlertProviderFactory = ({
folderIdsByProject.set(secret.projectId, [...(folderIdsByProject.get(secret.projectId) ?? []), secret.folderId]);
});
for (const [projectId, folderIds] of folderIdsByProject) {
+ // The path decides what a permission check allows, so it comes from the primary like the secret:
+ // a replica that has not seen a new folder would otherwise leave it unresolved.
// eslint-disable-next-line no-await-in-loop -- reminders fire per secret, so this is one project
- const folders = await folderDAL.findSecretPathByFolderIds(projectId, folderIds);
+ const folders = await folderDAL.findSecretPathByFolderIds(
+ projectId,
+ folderIds,
+ secretReminderAlertDAL.primaryNode()
+ );
folders.forEach((folder) => {
if (folder?.path) paths.set(folder.id, folder.path);
});
}
- return secrets.map((secret) => ({ ...secret, secretPath: paths.get(secret.folderId) ?? "/" }));
+ // A secret whose path cannot be resolved is left out rather than treated as sitting at the root,
+ // which would check permissions against the wrong path.
+ return secrets.flatMap((secret) => {
+ const secretPath = paths.get(secret.folderId);
+ return secretPath ? [{ ...secret, secretPath }] : [];
+ });
};
const findTargetsByIds = async (input: TFindTargetsByIdsInput): Promise<TSecretReminderTarget[]> => {
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx
index 669094d4f4..be8385982f 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretReminderForm.tsx
@@ -201,9 +201,16 @@ export const SecretReminderForm = ({
const reminderType = watch("reminderType");
const fromDate = watch("fromDate");
+ // A reminder can exist without an alert (eg the backfill skipped it because everyone it listed had
+ // left the project). It has nobody to notify, so the form asks for recipients instead of offering
+ // the everyone default, which would send to people nobody chose.
+ const hasNoAlert = isEditMode && isAlertLoaded && !alert;
+
useEffect(() => {
if (alert) setValue("channels", alert.channels.map(toChannelForm), { shouldDirty: false });
- }, [alert, setValue]);
+ else if (hasNoAlert)
+ setValue("channels", [{ ...everyoneEmailChannel, recipients: [] }], { shouldDirty: false });
+ }, [alert, hasNoAlert, everyoneEmailChannel, setValue]);
const isPending = isCreating || isDeleting;
@@ -427,7 +434,6 @@ export const SecretReminderForm = ({
{...field}
value={field.value ?? ""}
placeholder="Remember to rotate this secret every month."
- className="max-h-32 min-h-16 resize-none"
disabled={!canEditSecret}
/>
)}
@@ -443,6 +449,11 @@ export const SecretReminderForm = ({
Couldn&apos;t load this reminder&apos;s channels. Close and reopen to try again.
</p>
)}
+ {hasNoAlert && (
+ <p className="text-xs text-muted">
+ This reminder has nobody to notify. Choose recipients.
+ </p>
+ )}
{areChannelsReady && (
<ChannelsField
projectId={projectId}