Skip to content

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

test(e2e): cover platform behaviour the blackbox suite cannot reach

Claude45ccf066e6ab
diff --git a/backend/e2e-test/routes/v1/additional-privilege-legacy.spec.ts b/backend/e2e-test/routes/v1/additional-privilege-legacy.spec.ts
new file mode 100644
index 0000000000..3662a3f1cd
--- /dev/null
+++ b/backend/e2e-test/routes/v1/additional-privilege-legacy.spec.ts
@@ -0,0 +1,168 @@
+import { OrgMembershipRole, ProjectMembershipRole, TableName } from "@app/db/schemas";
+
+// Additional privileges are refused on every project created today: only projects that existed before
+// the legacy-privileges migration carry isLegacyAdditionalPrivilegesEnabled, and no route sets it. The
+// flag is written straight to the table so the behaviour those projects still rely on stays covered.
+import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
+import { addIdentityToProject, createIdentityActor } from "e2e-test/testUtils/identities";
+import { pollUntil } from "e2e-test/testUtils/poll";
+import { addUserMembership, createUser, createUserAccessToken, deleteUsers } from "e2e-test/testUtils/users";
+
+const READ_SECRETS = [{ subject: "secrets", action: ["describeSecret", "readValue"] }];
+
+describe("Additional privileges on a legacy project", () => {
+ let orgId: string;
+ let projectId: string;
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+ const users: string[] = [];
+
+ beforeAll(async () => {
+ ({ orgId, projectId, authToken, cleanup } = await createIsolatedOrgAndProject("legacy-privileges"));
+ await testDb(TableName.Project).where({ id: projectId }).update({ isLegacyAdditionalPrivilegesEnabled: true });
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ await deleteUsers(users);
+ });
+
+ const listSecrets = (token: string) =>
+ testServer.inject({
+ method: "GET",
+ url: "/api/v3/secrets/raw",
+ headers: { authorization: `Bearer ${token}` },
+ query: { workspaceId: projectId, environment: "dev", secretPath: "/" }
+ });
+
+ const noAccessIdentity = async () => {
+ const identity = await createIdentityActor({ orgId, authToken, role: OrgMembershipRole.Member });
+ await addIdentityToProject({
+ projectId,
+ identityId: identity.identityId,
+ role: ProjectMembershipRole.NoAccess,
+ authToken
+ });
+ return identity;
+ };
+
+ const waitForStatus = (token: string, status: number) =>
+ pollUntil({
+ describe: `secret listing to answer ${status}`,
+ read: async () => (await listSecrets(token)).statusCode,
+ done: (code) => code === status,
+ timeoutMs: 20_000
+ });
+
+ test("an identity privilege grants access, and deleting it takes the access away", async () => {
+ const identity = await noAccessIdentity();
+ expect((await listSecrets(identity.authToken)).statusCode).toBe(403);
+
+ const created = await testServer.inject({
+ method: "POST",
+ url: "/api/v2/identity-project-additional-privilege",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: {
+ identityId: identity.identityId,
+ projectId,
+ slug: "read-dev",
+ permissions: READ_SECRETS,
+ type: { isTemporary: false }
+ }
+ });
+ expect(created.statusCode, created.payload).toBe(200);
+ await waitForStatus(identity.authToken, 200);
+
+ const deleted = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/identity-project-additional-privilege/${created.json().privilege.id as string}`,
+ headers: { authorization: `Bearer ${authToken}` }
+ });
+ expect(deleted.statusCode, deleted.payload).toBe(200);
+ await waitForStatus(identity.authToken, 403);
+ }, 60_000);
+
+ test("a user privilege grants access, and deleting it takes the access away", async () => {
+ const user = await createUser("legacy-privilege-user");
+ users.push(user.userId);
+ await addUserMembership({ userId: user.userId, orgId, role: OrgMembershipRole.Member });
+ const projectMembershipId = await addUserMembership({
+ userId: user.userId,
+ orgId,
+ projectId,
+ role: ProjectMembershipRole.NoAccess
+ });
+ const userToken = await createUserAccessToken({ userId: user.userId, orgId });
+ expect((await listSecrets(userToken)).statusCode).toBe(403);
+
+ const created = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/user-project-additional-privilege",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: { projectMembershipId, slug: "read-dev", permissions: READ_SECRETS, type: { isTemporary: false } }
+ });
+ expect(created.statusCode, created.payload).toBe(200);
+ await waitForStatus(userToken, 200);
+
+ const deleted = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/user-project-additional-privilege/${created.json().privilege.id as string}`,
+ headers: { authorization: `Bearer ${authToken}` }
+ });
+ expect(deleted.statusCode, deleted.payload).toBe(200);
+ await waitForStatus(userToken, 403);
+ }, 60_000);
+
+ test("a temporary privilege whose window has ended grants nothing", async () => {
+ const identity = await noAccessIdentity();
+
+ const created = await testServer.inject({
+ method: "POST",
+ url: "/api/v2/identity-project-additional-privilege",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: {
+ identityId: identity.identityId,
+ projectId,
+ slug: "expired-read",
+ permissions: READ_SECRETS,
+ type: {
+ isTemporary: true,
+ temporaryMode: "relative",
+ temporaryRange: "1h",
+ temporaryAccessStartTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
+ }
+ }
+ });
+ expect(created.statusCode, created.payload).toBe(200);
+
+ expect((await listSecrets(identity.authToken)).statusCode).toBe(403);
+ });
+
+ test("an actor cannot grant a privilege broader than its own", async () => {
+ const actor = await createIdentityActor({ orgId, authToken, role: OrgMembershipRole.Member });
+ await addIdentityToProject({
+ projectId,
+ identityId: actor.identityId,
+ role: ProjectMembershipRole.Member,
+ authToken
+ });
+ const target = await noAccessIdentity();
+
+ const res = await testServer.inject({
+ method: "POST",
+ url: "/api/v2/identity-project-additional-privilege",
+ headers: { authorization: `Bearer ${actor.authToken}` },
+ body: {
+ identityId: target.identityId,
+ projectId,
+ slug: "too-broad",
+ permissions: [{ subject: "role", action: ["create", "edit", "delete"] }],
+ type: { isTemporary: false }
+ }
+ });
+
+ expect(res.statusCode).toBe(403);
+ const privileges = await testDb(TableName.AdditionalPrivilege).where({ actorIdentityId: target.identityId });
+ expect(privileges).toHaveLength(0);
+ });
+});
diff --git a/backend/e2e-test/routes/v1/gateway-enrollment-token-expiry.spec.ts b/backend/e2e-test/routes/v1/gateway-enrollment-token-expiry.spec.ts
new file mode 100644
index 0000000000..1607b92b07
--- /dev/null
+++ b/backend/e2e-test/routes/v1/gateway-enrollment-token-expiry.spec.ts
@@ -0,0 +1,60 @@
+// An enrollment token lives for an hour and nothing moves the clock, so the test moves the deadline:
+// the stored token is backdated, which is exactly the state an hour of waiting would leave.
+import crypto from "node:crypto";
+
+import { TableName } from "@app/db/schemas";
+
+import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
+
+describe("Gateway enrollment token expiry", () => {
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ authToken, cleanup } = await createIsolatedOrgAndProject("gateway-enrollment-expiry"));
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ });
+
+ test("an expired enrollment token is refused and cannot be used again", async () => {
+ const headers = { authorization: `Bearer ${authToken}` };
+ const created = await testServer.inject({
+ method: "POST",
+ url: "/api/v3/gateways",
+ headers,
+ body: { name: `gw-${crypto.randomUUID().slice(0, 8)}`, authMethod: { method: "token" } }
+ });
+ expect(created.statusCode, created.payload).toBe(200);
+ const gatewayId = (created.json().gateway?.id ?? created.json().id) as string;
+
+ const minted = await testServer.inject({
+ method: "POST",
+ url: `/api/v3/gateways/${gatewayId}/token-auth/generate-enrollment-token`,
+ headers
+ });
+ expect(minted.statusCode, minted.payload).toBe(200);
+ const { token } = minted.json() as { token: string };
+ const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
+ await testDb(TableName.ResourceTokenAuth)
+ .where({ tokenHash })
+ .update({ expiresAt: new Date(Date.now() - 60_000) });
+
+ const login = await testServer.inject({
+ method: "POST",
+ url: "/api/v3/gateways/login",
+ body: { method: "token", token }
+ });
+ expect(login.statusCode).toBe(400);
+ expect(login.json().message).toBe("Enrollment token has expired");
+
+ const again = await testServer.inject({
+ method: "POST",
+ url: "/api/v3/gateways/login",
+ body: { method: "token", token }
+ });
+ expect(again.statusCode).toBe(400);
+ expect(again.json().message).toBe("Invalid enrollment token");
+ });
+});
diff --git a/backend/e2e-test/routes/v1/group-legacy-privilege.spec.ts b/backend/e2e-test/routes/v1/group-legacy-privilege.spec.ts
new file mode 100644
index 0000000000..af38f30c7f
--- /dev/null
+++ b/backend/e2e-test/routes/v1/group-legacy-privilege.spec.ts
@@ -0,0 +1,79 @@
+// New organizations use the new privilege system and no route turns it off, so the legacy system's
+// role comparison is reached by writing the flag, as identity-auth-boundary.spec.ts does.
+import { packRules } from "@casl/ability/extra";
+
+import { AccessScope, OrgMembershipRole, TableName } from "@app/db/schemas";
+
+import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
+import { createIdentityActor } from "e2e-test/testUtils/identities";
+import { overrideLicenseFeatures } from "e2e-test/testUtils/license";
+import { addUserMembership, createUser, deleteUsers } from "e2e-test/testUtils/users";
+
+describe("Group membership on the legacy privilege system", () => {
+ let orgId: string;
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+ const users: string[] = [];
+ let restoreLicense: () => void;
+
+ beforeAll(async () => {
+ restoreLicense = overrideLicenseFeatures({ groups: true });
+ ({ orgId, authToken, cleanup } = await createIsolatedOrgAndProject("group-legacy-privilege"));
+ await testDb(TableName.Organization).where({ id: orgId }).update({ shouldUseNewPrivilegeSystem: false });
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ await deleteUsers(users);
+ restoreLicense();
+ });
+
+ test("an actor cannot add a user to a group more privileged than itself", async () => {
+ const actor = await createIdentityActor({ orgId, authToken, role: OrgMembershipRole.Member });
+ const [role] = await testDb(TableName.Role)
+ .insert({
+ name: "group-editor",
+ slug: `group-editor-${orgId.slice(0, 8)}`,
+ orgId,
+ permissions: JSON.stringify(
+ packRules([{ subject: "groups", action: ["read", "edit", "add-members"] }] as never)
+ )
+ })
+ .returning("id");
+ const membership = await testDb(TableName.Membership)
+ .where({ scope: AccessScope.Organization, scopeOrgId: orgId, actorIdentityId: actor.identityId })
+ .first();
+ await testDb(TableName.MembershipRole)
+ .where({ membershipId: (membership as { id: string }).id })
+ .delete();
+ await testDb(TableName.MembershipRole).insert({
+ membershipId: (membership as { id: string }).id,
+ role: "custom",
+ customRoleId: (role as { id: string }).id
+ });
+
+ const groupRes = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/groups",
+ headers: { authorization: `Bearer ${authToken}` },
+ body: { name: "admins", role: OrgMembershipRole.Admin }
+ });
+ expect(groupRes.statusCode, groupRes.payload).toBe(200);
+ const groupId = groupRes.json().id as string;
+
+ const user = await createUser("legacy-group-member");
+ users.push(user.userId);
+ await addUserMembership({ userId: user.userId, orgId, role: OrgMembershipRole.Member });
+
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v1/groups/${groupId}/users/${encodeURIComponent(user.username)}`,
+ headers: { authorization: `Bearer ${actor.authToken}` }
+ });
+
+ expect(res.statusCode).toBe(403);
+ expect(res.json().message).toContain("more privileged group");
+ const members = await testDb(TableName.UserGroupMembership).where({ groupId });
+ expect(members).toHaveLength(0);
+ });
+});
diff --git a/backend/e2e-test/routes/v1/identity-credential-expiry-alert.spec.ts b/backend/e2e-test/routes/v1/identity-credential-expiry-alert.spec.ts
new file mode 100644
index 0000000000..f27d656790
--- /dev/null
+++ b/backend/e2e-test/routes/v1/identity-credential-expiry-alert.spec.ts
@@ -0,0 +1,82 @@
+import { OrgMembershipRole } from "@app/db/schemas";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+
+// Expiry alerts are evaluated by the daily alert cron, which only enqueues one dispatch job per
+// enabled alert. The test enqueues that job itself rather than waiting for midnight.
+import { TTestSmtpService } from "e2e-test/mocks/smtp";
+import { createAlert } from "e2e-test/testUtils/alerts";
+import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
+import { createIdentityActor } from "e2e-test/testUtils/identities";
+import { pollUntil } from "e2e-test/testUtils/poll";
+import { addUserMembership, createUser, deleteUsers } from "e2e-test/testUtils/users";
+
+const smtp = () => (globalThis as unknown as { testSmtp: TTestSmtpService }).testSmtp;
+const queue = () => (globalThis as unknown as { testQueue: TQueueServiceFactory }).testQueue;
+
+describe("Machine identity credential expiry alert", () => {
+ let orgId: string;
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+ let recipient: { userId: string; username: string };
+
+ beforeAll(async () => {
+ ({ orgId, authToken, cleanup } = await createIsolatedOrgAndProject("identity-expiry-alert"));
+ recipient = await createUser("expiry-alert-recipient");
+ await addUserMembership({ userId: recipient.userId, orgId, role: OrgMembershipRole.Member });
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ await deleteUsers([recipient.userId]);
+ });
+
+ test("a client secret expiring within the lead time is mailed to the alert's recipients", async () => {
+ const identity = await createIdentityActor({ orgId, authToken });
+ const secretRes = await testServer.inject({
+ method: "POST",
+ url: `/api/v1/auth/universal-auth/identities/${identity.identityId}/client-secrets`,
+ headers: { authorization: `Bearer ${authToken}` },
+ body: { description: "expiring-soon", ttl: 2 * 24 * 60 * 60 }
+ });
+ expect(secretRes.statusCode, secretRes.payload).toBe(200);
+
+ const alertRes = await createAlert({
+ authToken,
+ body: {
+ name: "credential expiry",
+ resourceType: "identity.authentication",
+ resourceId: identity.identityId,
+ eventType: "identity.authentication.expiry",
+ condition: { alertBefore: "7d" },
+ channels: [
+ {
+ name: "Email",
+ channelType: "email",
+ config: {},
+ recipients: [{ principalType: "user", principalId: recipient.userId }]
+ }
+ ]
+ }
+ });
+ const alertId = alertRes.id;
+
+ await queue().queue(
+ QueueName.AlertDispatch,
+ QueueJobs.AlertDispatch,
+ { alertId, scheduledAt: new Date().toISOString() },
+ { jobId: `e2e-alert-dispatch-${alertId}`, removeOnComplete: true, removeOnFail: true, attempts: 1 }
+ );
+
+ const [email] = await pollUntil({
+ describe: "the credential expiry alert email",
+ read: () =>
+ smtp()
+ .getEmails()
+ .filter((mail) => JSON.stringify(mail.substitutions).includes("expiring-soon")),
+ done: (emails) => emails.length > 0,
+ timeoutMs: 30_000
+ });
+
+ expect(email.recipients).toEqual([recipient.username]);
+ }, 40_000);
+});
diff --git a/backend/e2e-test/routes/v1/identity-org-membership-deactivation.spec.ts b/backend/e2e-test/routes/v1/identity-org-membership-deactivation.spec.ts
new file mode 100644
index 0000000000..346d1be444
--- /dev/null
+++ b/backend/e2e-test/routes/v1/identity-org-membership-deactivation.spec.ts
@@ -0,0 +1,94 @@
+import { AccessScope, OrgMembershipRole, ProjectMembershipRole } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
+
+// The route that updates an identity's org membership takes no isActive, so the service is driven
+// directly: it is the same path a future route would take, and it owns the revoke and restore hooks
+// that keep cached token verdicts honest.
+import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
+import { createIdentityActor } from "e2e-test/testUtils/identities";
+
+type TMembershipIdentityService = {
+ updateMembership: (dto: unknown) => Promise<unknown>;
+};
+
+const membershipIdentity = () =>
+ (globalThis as unknown as { testServices: { membershipIdentity: TMembershipIdentityService } }).testServices
+ .membershipIdentity;
+
+const setActive = async (orgId: string, identityId: string, isActive: boolean) => {
+ await membershipIdentity().updateMembership({
+ permission: {
+ type: ActorType.USER,
+ id: seedData1.id,
+ authMethod: AuthMethod.EMAIL,
+ orgId,
+ rootOrgId: orgId,
+ parentOrgId: orgId
+ },
+ scopeData: { scope: AccessScope.Organization, orgId },
+ selector: { identityId },
+ data: { isActive, roles: [{ role: OrgMembershipRole.Member, isTemporary: false }] }
+ });
+};
+
+const details = (token: string) =>
+ testServer.inject({
+ method: "GET",
+ url: "/api/v1/identities/details",
+ headers: { authorization: `Bearer ${token}` }
+ });
+
+describe("Machine identity org membership deactivation", () => {
+ let orgId: string;
+ let projectId: string;
+ let authToken: string;
+ let cleanup: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ orgId, projectId, authToken, cleanup } = await createIsolatedOrgAndProject("identity-deactivation"));
+ });
+
+ afterAll(async () => {
+ await cleanup();
+ });
+
+ test("an identity's token is refused while its org membership is deactivated and accepted again once reactivated", async () => {
+ const identity = await createIdentityActor({ orgId, authToken, role: OrgMembershipRole.Member });
+ expect((await details(identity.authToken)).statusCode).toBe(200);
+
+ await setActive(orgId, identity.identityId, false);
+
+ // Deactivation writes the same org revocation marker as removal, so a token issued before it is
+ // refused with the removal message; the inactive message is only reached on the cold path.
+ const refused = await details(identity.authToken);
+ expect(refused.statusCode).toBe(401);
+ expect(refused.json().message).toBe("Failed to authorize: Identity is not a member of the organization");
+
+ await setActive(orgId, identity.identityId, true);
+
+ expect((await details(identity.authToken)).statusCode).toBe(200);
+ });
+
+ test("an identity whose org membership is deactivated cannot be added to a project", async () => {
+ const identity = await createIdentityActor({ orgId, authToken, role: OrgMembershipRole.Member });
+ await setActive(orgId, identity.identityId, false);
+
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v1/projects/${projectId}/memberships/identities/${identity.identityId}`,
+ headers: { authorization: `Bearer ${authToken}` },
+ body: { roles: [{ role: ProjectMembershipRole.Viewer }] }
+ });
+
+ expect(res.statusCode).toBe(400);
+ const members = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/projects/${projectId}/memberships/identities`,
+ headers: { authorization: `Bearer ${authToken}` }
+ });
+ expect(
+ (members.json().identityMemberships as { identityId: string }[]).some((m) => m.identityId === identity.identityId)
+ ).toBe(false);
+ });
+});