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
test(e2e): share user fixtures and document the testUtils helpers
Calvin367b85304cc9
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 2ea5fe7129..9e0ffe679b 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -48,6 +48,33 @@ Unit tests go next to source as `*.test.ts` and test pure functions with VitestE2E tests live in `e2e-test/routes/`. The custom Vitest environment (`e2e-test/vitest-environment-knex.ts`) bootstraps a full server with DB, Redis, and encryption. Tests use injected globals: `testServer` (Fastify instance), `jwtAuthToken` (pre-authenticated JWT). Use `testServer.inject()` for HTTP assertions. Test helpers in `e2e-test/testUtils/` provide CRUD wrappers for secrets, folders, and secret imports. See `e2e-test/routes/v1/org.spec.ts` for a representative e2e test.+#### Writing e2e tests with `testUtils`++**Build test state with the helpers in `e2e-test/testUtils/`, not by hand.** Before writing a+`testServer.inject` call or a `testDb` insert to set something up, check `testUtils/` for a helper+that already does it. If none exists, add one there rather than a local helper in the spec: two+specs had each written their own `createTargetUser` before `testUtils/users.ts` existed, and every+copy drifts on its own.++- **Isolate each test.** `createIsolatedOrgAndProject` (`fixtures.ts`) gives a test its own org and+ project, a token scoped to it, and a `cleanup` that deletes the org. Prefer it over the shared+ `seedData1` org and project, whose state leaks between tests and files.+- **Don't lean on the seed user as a participant.** When a test needs someone other than the caller+ (a recipient, a member, a target), create them with `createUser` and `addUserMembership`+ (`users.ts`). Those write rows directly because signup needs SRP, so the user can be named but+ cannot log in.+- **Go through the API for everything else**, with the domain helpers (`secrets.ts`, `folders.ts`,+ `alerts.ts`, `reminders.ts`, `identities.ts`, ...). Write a helper with `request()` (`request.ts`)+ so a call is sent when made and a caller can `.expect()` a non-200 or take the `.raw()` response.+- **Assert on outcomes a user would see**: an API response, an email in `testSmtp`, a message at a+ fake destination. Read `testDb` only when the API cannot show the thing under test (eg an alert+ orphaned by a cascade), and say why in a comment.+- **Wait with `pollUntil`** (`poll.ts`) for anything asynchronous, never a fixed sleep.+- **Run background jobs on demand rather than faking the clock.** Postgres `NOW()`, Redis TTLs and+ JWT expiry all read different clocks, so `vi.setSystemTime` cannot move them together. Give the+ job an explicit `now` and reach it through a pass-through wrapper in `e2e-test/fakes/` (eg+ `reminder-queue.ts` and `event-outbox-queue.ts`, driven by `runDailyReminders` in `reminders.ts`).+#### Faking a third-party provider**Never add test-only code to `src/`** — no test-mode enum members, no lookup map entries, nodiff --git a/backend/e2e-test/routes/v1/membership-downgrade-boundary.spec.ts b/backend/e2e-test/routes/v1/membership-downgrade-boundary.spec.tsindex 4b44766d64..35dac83441 100644--- a/backend/e2e-test/routes/v1/membership-downgrade-boundary.spec.ts+++ b/backend/e2e-test/routes/v1/membership-downgrade-boundary.spec.ts@@ -23,6 +23,8 @@ import { packRules } from "@casl/ability/extra";import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";+import { addUserMembership, createUser } from "../../testUtils/users";+const adminHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });const asIdentity = (token: string) => ({ authorization: `Bearer ${token}` });@@ -67,28 +69,6 @@ const createActorIdentity = async (name: string) => {return { identityId, token: loginRes.json().accessToken as string };};-const createTargetUser = async (label: string) => {- const username = `${label}-${crypto.randomUUID()}@localhost.local`;- const [user] = await testDb(TableName.Users)- .insert({ username, email: username, firstName: label, isAccepted: true, isGhost: false })- .returning("id");- return { userId: (user as { id: string }).id, username };-};--const giveProjectMembership = async (userId: string, projectId: string, role: ProjectMembershipRole) => {- const [membership] = await testDb(TableName.Membership)- .insert({- scope: AccessScope.Project,- scopeOrgId: seedData1.organization.id,- scopeProjectId: projectId,- actorUserId: userId- })- .returning("id");- const membershipId = (membership as { id: string }).id;- await testDb(TableName.MembershipRole).insert({ membershipId, role });- return membershipId;-};-describe("Privilege boundary on project membership downgrade", () => {let project: { id: string };let actor: { identityId: string; token: string };@@ -155,8 +135,13 @@ describe("Privilege boundary on project membership downgrade", () => {});test("baseline: DELETE on an Admin target follows the removal boundary", async () => {- const target = await createTargetUser("del");- const membershipId = await giveProjectMembership(target.userId, project.id, ProjectMembershipRole.Admin);+ const target = await createUser("del");+ const membershipId = await addUserMembership({+ userId: target.userId,+ orgId: seedData1.organization.id,+ projectId: project.id,+ role: ProjectMembershipRole.Admin+ });const res = await testServer.inject({method: "DELETE",@@ -168,8 +153,13 @@ describe("Privilege boundary on project membership downgrade", () => {});test("setting a more privileged member to no-access is bounded, like removing them", async () => {- const target = await createTargetUser("patch");- const membershipId = await giveProjectMembership(target.userId, project.id, ProjectMembershipRole.Admin);+ const target = await createUser("patch");+ const membershipId = await addUserMembership({+ userId: target.userId,+ orgId: seedData1.organization.id,+ projectId: project.id,+ role: ProjectMembershipRole.Admin+ });const res = await testServer.inject({method: "PATCH",@@ -182,8 +172,13 @@ describe("Privilege boundary on project membership downgrade", () => {});test("regression: downgrading to a real role stays bounded", async () => {- const target = await createTargetUser("patchv");- const membershipId = await giveProjectMembership(target.userId, project.id, ProjectMembershipRole.Admin);+ const target = await createUser("patchv");+ const membershipId = await addUserMembership({+ userId: target.userId,+ orgId: seedData1.organization.id,+ projectId: project.id,+ role: ProjectMembershipRole.Admin+ });const res = await testServer.inject({method: "PATCH",@@ -197,8 +192,13 @@ describe("Privilege boundary on project membership downgrade", () => {test("regression: an admin can still downgrade an Admin member to no-access", async () => {await setNewPrivilegeSystem(false);- const target = await createTargetUser("admin-downgrade");- const membershipId = await giveProjectMembership(target.userId, project.id, ProjectMembershipRole.Admin);+ const target = await createUser("admin-downgrade");+ const membershipId = await addUserMembership({+ userId: target.userId,+ orgId: seedData1.organization.id,+ projectId: project.id,+ role: ProjectMembershipRole.Admin+ });const res = await testServer.inject({method: "PATCH",@@ -230,12 +230,12 @@ describe("Privilege boundary on org membership downgrade", () => {});const createAdminTarget = async () => {- const { userId } = await createTargetUser("org-downgrade");- const [membership] = await testDb(TableName.Membership)- .insert({ scope: AccessScope.Organization, scopeOrgId: seedData1.organization.id, actorUserId: userId })- .returning("id");- const membershipId = (membership as { id: string }).id;- await testDb(TableName.MembershipRole).insert({ membershipId, role: OrgMembershipRole.Admin });+ const { userId } = await createUser("org-downgrade");+ const membershipId = await addUserMembership({+ userId,+ orgId: seedData1.organization.id,+ role: OrgMembershipRole.Admin+ });targetUserIds.push(userId);return { userId, membershipId };};diff --git a/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.ts b/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.tsindex d72e08c394..bd2c8df63a 100644--- a/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.ts+++ b/backend/e2e-test/routes/v1/privilege-boundary-removal.spec.ts@@ -8,13 +8,13 @@* actor's role is exactly what the assertion is about.*/-import crypto from "node:crypto";-import { packRules } from "@casl/ability/extra";import { AccessScope, OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";+import { addUserMembership, createUser } from "../../testUtils/users";+const adminHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });const asIdentity = (token: string) => ({ authorization: `Bearer ${token}` });@@ -273,42 +273,6 @@ const findIdentityMembershipId = async (identityId: string, projectId?: string)return (row as { id: string }).id;};-/**- * The seed carries exactly one user and every removal path here targets a user membership. The routes- * only need a non-ghost Users row joined to a Membership, never a login, so skip signup and SRP.- */-const createTargetUser = async (label: string) => {- const username = `${label}-${crypto.randomUUID()}@localhost.local`;- const [user] = await testDb(TableName.Users)- .insert({ username, email: username, firstName: label, isAccepted: true, isGhost: false })- .returning("id");-- return { userId: (user as { id: string }).id, username };-};--const giveUserMembership = async ({- userId,- role,- projectId-}: {- userId: string;- role: OrgMembershipRole | ProjectMembershipRole;- projectId?: string;-}) => {- const [membership] = await testDb(TableName.Membership)- .insert({- scope: projectId ? AccessScope.Project : AccessScope.Organization,- scopeOrgId: seedData1.organization.id,- scopeProjectId: projectId ?? null,- actorUserId: userId- })- .returning("id");-- const membershipId = (membership as { id: string }).id;- await testDb(TableName.MembershipRole).insert({ membershipId, role });- return membershipId;-};-const dropUser = async (userId: string) => {await testDb(TableName.Membership).where({ actorUserId: userId }).delete();await testDb(TableName.Users).where({ id: userId }).delete();@@ -342,10 +306,14 @@ describe("Privilege boundary on org membership removal", () => {actor = await createActorIdentity("e2e-pb-org-actor");await useCustomRole(await findIdentityMembershipId(actor.identityId), roleId);- const target = await createTargetUser("e2e-pb-org-target");+ const target = await createUser("e2e-pb-org-target");adminTarget = {userId: target.userId,- membershipId: await giveUserMembership({ userId: target.userId, role: OrgMembershipRole.Admin })+ membershipId: await addUserMembership({+ orgId: seedData1.organization.id,+ userId: target.userId,+ role: OrgMembershipRole.Admin+ })};});@@ -375,7 +343,8 @@ describe("Privilege boundary on org membership removal", () => {const res = await deleteOrgMembership(adminTarget.membershipId, adminHeaders());expect(res.statusCode).toBe(200);- adminTarget.membershipId = await giveUserMembership({+ adminTarget.membershipId = await addUserMembership({+ orgId: seedData1.organization.id,userId: adminTarget.userId,role: OrgMembershipRole.Admin});@@ -413,10 +382,15 @@ describe("Privilege boundary on the bulk project member removal route", () => {await addIdentityToProject(project.id, actor.identityId, ProjectMembershipRole.Member);await useCustomRole(await findIdentityMembershipId(actor.identityId, project.id), roleId);- const target = await createTargetUser("e2e-pb-bulk-target");+ const target = await createUser("e2e-pb-bulk-target");adminTarget = target;- await giveUserMembership({ userId: target.userId, role: OrgMembershipRole.Member });- await giveUserMembership({+ await addUserMembership({+ orgId: seedData1.organization.id,+ userId: target.userId,+ role: OrgMembershipRole.Member+ });+ await addUserMembership({+ orgId: seedData1.organization.id,userId: target.userId,role: ProjectMembershipRole.Admin,projectId: project.iddiff --git a/backend/e2e-test/routes/v1/secret-reminder.spec.ts b/backend/e2e-test/routes/v1/secret-reminder.spec.tsindex f9d0b9d023..d5c6355e57 100644--- a/backend/e2e-test/routes/v1/secret-reminder.spec.ts+++ b/backend/e2e-test/routes/v1/secret-reminder.spec.ts@@ -1,4 +1,4 @@-import { seedData1 } from "@app/db/seed-data";+import { OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";import { SECRET_REMINDER_RESOURCE_TYPE } from "@app/services/reminder/reminder-events";import { up as migrateRemindersToAlerts } from "../../../src/db/migrations/20260929130000_migrate-secret-reminders-to-alerts";@@ -16,6 +16,7 @@ import {waitForReminderEmails} from "../../testUtils/reminders";import { createSecretV2, getSecretByNameV2 } from "../../testUtils/secrets";+import { addUserMembership, createUser } from "../../testUtils/users";const ENVIRONMENT = "dev";const DAY_MS = 24 * 60 * 60 * 1000;@@ -30,9 +31,15 @@ describe("Secret reminders delivered through alerts", () => {let projectId: string;let authToken: string;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 };beforeEach(async () => {- ({ projectId, authToken, cleanup } = await createIsolatedOrgAndProject("reminders"));+ let orgId: string;+ ({ orgId, projectId, authToken, cleanup } = await createIsolatedOrgAndProject("reminders"));+ member = await createUser("reminder-recipient");+ await addUserMembership({ userId: member.userId, orgId, role: OrgMembershipRole.Member });+ await addUserMembership({ userId: member.userId, orgId, projectId, role: ProjectMembershipRole.Member });});afterEach(async () => {@@ -61,20 +68,20 @@ describe("Secret reminders delivered through alerts", () => {test("setting a reminder creates its alert with an email channel to the recipients", async () => {const secretId = await createSecret("CREATE");- await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [seedData1.id] });+ await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [member.userId] });const [alert] = await reminderAlerts(secretId);expect(alert.name).toBe("Reminder for CREATE");expect(alert.channels).toHaveLength(1);expect(alert.channels[0]).toMatchObject({channelType: "email",- recipients: [{ principalType: "user", principalId: seedData1.id }]+ recipients: [{ principalType: "user", principalId: member.userId }]});expect(await getSecretReminder({ secretId, authToken })).toMatchObject({repeatDays: 30,message: "rotate it",- recipients: [seedData1.id]+ recipients: [member.userId]});});@@ -88,7 +95,7 @@ describe("Secret reminders delivered through alerts", () => {test("updating the reminder keeps channels added through the alert API", async () => {const secretId = await createSecret("KEEP_WEBHOOK");- await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [seedData1.id] });+ await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [member.userId] });const [alert] = await reminderAlerts(secretId);await updateAlert({@@ -113,7 +120,7 @@ describe("Secret reminders delivered through alerts", () => {test("the secret listing reports recipients from the reminder's alert", async () => {const secretId = await createSecret("LISTING");- await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [seedData1.id] });+ await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [member.userId] });const res = await testServer.inject({method: "GET",@@ -127,7 +134,7 @@ describe("Secret reminders delivered through alerts", () => {secretReminderRepeatDays: number;}[];expect(secret.secretReminderRepeatDays).toBe(30);- expect(secret.secretReminderRecipients.map((recipient) => recipient.user.id)).toEqual([seedData1.id]);+ expect(secret.secretReminderRecipients.map((recipient) => recipient.user.id)).toEqual([member.userId]);});test("listing reminder alerts across a project is refused", async () => {@@ -144,7 +151,7 @@ describe("Secret reminders delivered through alerts", () => {authToken});const secretId = await createSecret("MOVE");- await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [seedData1.id] });+ await setSecretReminder({ secretId, authToken, repeatDays: 30, recipients: [member.userId] });const [before] = await reminderAlerts(secretId);const move = await testServer.inject({@@ -175,7 +182,7 @@ describe("Secret reminders delivered through alerts", () => {test("the daily job emails a due reminder and moves its schedule forward", async () => {const secretId = await createSecret("DISPATCH");- await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [seedData1.id] });+ await setSecretReminder({ secretId, authToken, repeatDays: 30, message: "rotate it", recipients: [member.userId] });const dueDate = await nextReminderDate(secretId);await runDailyReminders({ now: new Date() });@@ -184,7 +191,7 @@ describe("Secret reminders delivered through alerts", () => {await runDailyReminders({ now: dueDate });const [email] = await waitForReminderEmails("DISPATCH");- expect(email.recipients).toEqual([seedData1.email]);+ expect(email.recipients).toEqual([member.username]);expect(JSON.stringify(email.substitutions)).toContain("rotate it");expect((await nextReminderDate(secretId)).getTime()).toBe(dueDate.getTime() + 30 * DAY_MS);@@ -252,16 +259,14 @@ describe("Secret reminders delivered through alerts", () => {test("gives existing reminders an alert, keeping only recipients still in the project", async () => {const secretId = await createSecret("MIGRATE");- const [outsider] = await testDb("users")- .insert({ username: "[email protected]", email: "[email protected]" })- .returning("id");+ const outsider = await createUser("reminder-outsider");const reminderId = await seedReminder(secretId, {repeatDays: 30,nextReminderDate: new Date(Date.now() + DAY_MS)});await testDb("reminders_recipients").insert([- { reminderId, userId: seedData1.id },- { reminderId, userId: outsider.id }+ { reminderId, userId: member.userId },+ { reminderId, userId: outsider.userId }]);await migrateRemindersToAlerts(testDb);@@ -269,7 +274,7 @@ describe("Secret reminders delivered through alerts", () => {const [alert] = await reminderAlerts(secretId);expect(alert).toMatchObject({ name: "Reminder for MIGRATE", triggerType: "event" });expect(alert.channels).toHaveLength(1);- expect(alert.channels[0].recipients).toEqual([{ principalType: "user", principalId: seedData1.id }]);+ expect(alert.channels[0].recipients).toEqual([{ principalType: "user", principalId: member.userId }]);// The API does not report who created an alert.expect(await testDb("alerts").where({ id: alert.id }).first()).toMatchObject({createdByActorType: "platform",diff --git a/backend/e2e-test/testUtils/users.ts b/backend/e2e-test/testUtils/users.tsnew file mode 100644index 0000000000..f7c6e6f497--- /dev/null+++ b/backend/e2e-test/testUtils/users.ts@@ -0,0 +1,37 @@+import crypto from "node:crypto";++import { AccessScope, OrgMembershipRole, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";++// Writes the rows directly rather than going through signup, which needs SRP. The user can be named+// in memberships and reminders but cannot log in.+export const createUser = async (label: string) => {+ const username = `${label}-${crypto.randomUUID()}@localhost.local`;+ const [user] = await testDb(TableName.Users)+ .insert({ username, email: username, firstName: label, isAccepted: true, isGhost: false })+ .returning("id");++ return { userId: (user as { id: string }).id, username };+};++// 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: {+ userId: string;+ orgId: string;+ projectId?: string;+ role: OrgMembershipRole | ProjectMembershipRole;+}) => {+ const [membership] = await testDb(TableName.Membership)+ .insert({+ scope: dto.projectId ? AccessScope.Project : AccessScope.Organization,+ scopeOrgId: dto.orgId,+ scopeProjectId: dto.projectId ?? null,+ actorUserId: dto.userId,+ ...(dto.projectId ? {} : { status: OrgMembershipStatus.Accepted })+ })+ .returning("id");++ const membershipId = (membership as { id: string }).id;+ await testDb(TableName.MembershipRole).insert({ membershipId, role: dto.role });+ return membershipId;+};