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
add more tests
Thiago Araujo da Silvaf57c9683498d
diff --git a/backend/e2e-test/routes/v1/sso-alias-tenant-isolation.spec.ts b/backend/e2e-test/routes/v1/sso-alias-tenant-isolation.spec.tsnew file mode 100644index 0000000000..c8c5b3c70b--- /dev/null+++ b/backend/e2e-test/routes/v1/sso-alias-tenant-isolation.spec.ts@@ -0,0 +1,304 @@+import crypto from "node:crypto";++import { TableName } from "@app/db/schemas";+import { AccessScope, OrgMembershipStatus } from "@app/db/schemas";+import { orgDALFactory } from "@app/services/org/org-dal";+import { userDALFactory } from "@app/services/user/user-dal";+import { userAliasDALFactory } from "@app/services/user-alias/user-alias-dal";+import { adoptProvisionedShadowUser, resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias-fns";+import { UserAliasType } from "@app/services/user-alias/user-alias-types";++// Drives the resolver against real Postgres so the org scoping, the NULL-orgId semantics of whereIn,+// and the sub-org widening are all exercised as SQL rather than as reasoning.+const createdUserIds: string[] = [];+const createdOrgIds: string[] = [];++const makeOrg = async (rootOrgId?: string) => {+ const [org] = await testDb(TableName.Organization)+ .insert({ name: `o-${crypto.randomUUID()}`, slug: `o-${crypto.randomUUID()}`, rootOrgId: rootOrgId ?? null })+ .returning("*");+ createdOrgIds.push(org.id);+ return org;+};++const makeUserWithAlias = async (opts: {+ externalId: string;+ orgId: string | null;+ aliasType?: UserAliasType;+ isGhost?: boolean;+}) => {+ const email = `u-${crypto.randomUUID()}@tenant.example`;+ const [user] = await testDb(TableName.Users)+ .insert({ username: email, email, isAccepted: true, isGhost: opts.isGhost ?? false, authMethods: ["email"] })+ .returning("*");+ createdUserIds.push(user.id);+ await testDb(TableName.UserAliases).insert({+ userId: user.id,+ externalId: opts.externalId,+ orgId: opts.orgId,+ aliasType: opts.aliasType ?? UserAliasType.OIDC,+ isEmailVerified: true+ });+ return user;+};++const resolveAs = (orgId: string, identifiers: string[], rootOrgId?: string | null) =>+ resolveUsersBySsoExternalId({+ identifiers,+ orgId,+ rootOrgId,+ userAliasDAL: userAliasDALFactory(testDb),+ userDAL: userDALFactory(testDb)+ });++describe("SSO alias resolution is tenant scoped", () => {+ afterEach(async () => {+ if (createdUserIds.length) {+ const memberships = await testDb(TableName.Membership)+ .whereIn("actorUserId", createdUserIds)+ .select("id")+ .then((r) => r.map((x) => x.id));+ if (memberships.length) await testDb(TableName.MembershipRole).whereIn("membershipId", memberships).del();+ await testDb(TableName.Membership).whereIn("actorUserId", createdUserIds).del();+ await testDb(TableName.UserAliases).whereIn("userId", createdUserIds).del();+ await testDb(TableName.Users).whereIn("id", createdUserIds).del();+ createdUserIds.length = 0;+ }+ if (createdOrgIds.length) {+ // children first so the self-referencing rootOrgId FK is satisfied+ await testDb(TableName.Organization).whereIn("id", createdOrgIds).whereNotNull("rootOrgId").del();+ await testDb(TableName.Organization).whereIn("id", createdOrgIds).del();+ createdOrgIds.length = 0;+ }+ });++ test("an identifier resolves inside its own org", async () => {+ const org = await makeOrg();+ const identifier = `id-${crypto.randomUUID()}`;+ const user = await makeUserWithAlias({ externalId: identifier, orgId: org.id });++ const { resolved } = await resolveAs(org.id, [identifier]);++ expect(resolved.get(identifier)?.id).toBe(user.id);+ });++ test("org A cannot resolve an identifier that belongs to org B", async () => {+ const orgA = await makeOrg();+ const orgB = await makeOrg();+ const identifier = `id-${crypto.randomUUID()}`;+ await makeUserWithAlias({ externalId: identifier, orgId: orgB.id });++ const { resolved, ambiguousIdentifiers } = await resolveAs(orgA.id, [identifier]);++ expect(resolved.size).toBe(0);+ expect(ambiguousIdentifiers).toEqual([]);+ });++ test("a NULL-org social alias is unreachable from any org", async () => {+ const org = await makeOrg();+ const identifier = `id-${crypto.randomUUID()}`;+ await makeUserWithAlias({ externalId: identifier, orgId: null, aliasType: UserAliasType.GOOGLE });++ const { resolved } = await resolveAs(org.id, [identifier]);++ expect(resolved.size).toBe(0);+ });++ test("a NULL-org alias of an org-scoped type is still unreachable", async () => {+ const org = await makeOrg();+ const identifier = `id-${crypto.randomUUID()}`;+ await makeUserWithAlias({ externalId: identifier, orgId: null, aliasType: UserAliasType.OIDC });++ const { resolved } = await resolveAs(org.id, [identifier]);++ // whereIn("orgId", [...]) excludes NULL in SQL, which is the first of the two locks.+ expect(resolved.size).toBe(0);+ });++ test("a ghost user is never returned even when the alias is in scope", async () => {+ const org = await makeOrg();+ const identifier = `id-${crypto.randomUUID()}`;+ await makeUserWithAlias({ externalId: identifier, orgId: org.id, isGhost: true });++ const { resolved } = await resolveAs(org.id, [identifier]);++ expect(resolved.size).toBe(0);+ });++ test("only org-scoped alias types resolve; social types never do", async () => {+ const org = await makeOrg();+ const wanted = [UserAliasType.OIDC, UserAliasType.SAML, UserAliasType.LDAP];+ const refused = [UserAliasType.GOOGLE, UserAliasType.GITHUB, UserAliasType.GITLAB];+ const ids: Record<string, string> = {};+ for await (const aliasType of [...wanted, ...refused]) {+ const identifier = `id-${aliasType}-${crypto.randomUUID()}`;+ ids[aliasType] = identifier;+ // Give the social ones an orgId too, so aliasType is the only thing refusing them.+ await makeUserWithAlias({ externalId: identifier, orgId: org.id, aliasType });+ }++ const { resolved } = await resolveAs(+ org.id,+ Object.values(ids)+ );++ wanted.forEach((t) => expect(resolved.has(ids[t])).toBe(true));+ refused.forEach((t) => expect(resolved.has(ids[t])).toBe(false));+ });++ describe("sub-organizations", () => {+ test("a sub-org resolves an alias held on its root org", async () => {+ const root = await makeOrg();+ const sub = await makeOrg(root.id);+ const identifier = `id-${crypto.randomUUID()}`;+ const user = await makeUserWithAlias({ externalId: identifier, orgId: root.id });++ const { resolved } = await resolveAs(sub.id, [identifier], root.id);++ expect(resolved.get(identifier)?.id).toBe(user.id);+ });++ test("a root org cannot reach down into a sub-org's alias", async () => {+ const root = await makeOrg();+ const sub = await makeOrg(root.id);+ const identifier = `id-${crypto.randomUUID()}`;+ await makeUserWithAlias({ externalId: identifier, orgId: sub.id });++ // A root org has no rootOrgId of its own, so the widening never applies in this direction.+ const { resolved } = await resolveAs(root.id, [identifier], null);++ expect(resolved.size).toBe(0);+ });++ test("sibling sub-orgs cannot reach each other", async () => {+ const root = await makeOrg();+ const subA = await makeOrg(root.id);+ const subB = await makeOrg(root.id);+ const identifier = `id-${crypto.randomUUID()}`;+ await makeUserWithAlias({ externalId: identifier, orgId: subB.id });++ const { resolved } = await resolveAs(subA.id, [identifier], root.id);++ expect(resolved.size).toBe(0);+ });+ });++ // Adoption looks the placeholder up by username with no org filter, so the org-membership guard is+ // the only thing keeping it inside one tenant. These drive it against a real transaction.+ describe("placeholder adoption is bounded by org membership", () => {+ const seedPlaceholder = async (username: string, membershipOrgId?: string) => {+ const [user] = await testDb(TableName.Users)+ .insert({+ username,+ email: username,+ isAccepted: false,+ isEmailVerified: false,+ isGhost: false,+ authMethods: ["email"]+ })+ .returning("*");+ createdUserIds.push(user.id);+ if (membershipOrgId) {+ const [m] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ actorUserId: user.id,+ scopeOrgId: membershipOrgId,+ isActive: true,+ status: OrgMembershipStatus.Invited+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: m.id, role: "member" });+ }+ return user;+ };++ const adoptAs = (orgId: string, externalId: string, assertedEmail: string) =>+ testDb.transaction((tx) =>+ adoptProvisionedShadowUser({+ externalId,+ assertedEmail,+ orgId,+ userDAL: userDALFactory(testDb),+ userAliasDAL: userAliasDALFactory(testDb),+ orgDAL: orgDALFactory(testDb),+ tx+ })+ );++ test("org A cannot adopt a placeholder that only belongs to org B", async () => {+ const orgA = await makeOrg();+ const orgB = await makeOrg();+ const identifier = `ph-${crypto.randomUUID()}@tenant.example`;+ const placeholder = await seedPlaceholder(identifier, orgB.id);++ const adopted = await adoptAs(orgA.id, identifier, `real-${crypto.randomUUID()}@tenant.example`);++ expect(adopted).toBeNull();+ await expect(testDb(TableName.Users).where({ id: placeholder.id }).first()).resolves.toMatchObject({+ username: identifier+ });+ });++ test("a placeholder with no membership anywhere is never adopted", async () => {+ const org = await makeOrg();+ const identifier = `ph-${crypto.randomUUID()}@tenant.example`;+ const placeholder = await seedPlaceholder(identifier);++ const adopted = await adoptAs(org.id, identifier, `real-${crypto.randomUUID()}@tenant.example`);++ expect(adopted).toBeNull();+ await expect(testDb(TableName.Users).where({ id: placeholder.id }).first()).resolves.toMatchObject({+ username: identifier+ });+ });++ test("the org that provisioned the placeholder can adopt it", async () => {+ const org = await makeOrg();+ const identifier = `ph-${crypto.randomUUID()}@tenant.example`;+ const asserted = `real-${crypto.randomUUID()}@tenant.example`;+ const placeholder = await seedPlaceholder(identifier, org.id);++ const adopted = await adoptAs(org.id, identifier, asserted);++ expect(adopted?.id).toBe(placeholder.id);+ await expect(testDb(TableName.Users).where({ id: placeholder.id }).first()).resolves.toMatchObject({+ username: asserted,+ email: asserted+ });+ });+ });++ test("a batch resolves only the in-scope members of a mixed set", async () => {+ const orgA = await makeOrg();+ const orgB = await makeOrg();+ const mine = `id-${crypto.randomUUID()}`;+ const theirs = `id-${crypto.randomUUID()}`;+ const social = `id-${crypto.randomUUID()}`;+ const mineUser = await makeUserWithAlias({ externalId: mine, orgId: orgA.id });+ await makeUserWithAlias({ externalId: theirs, orgId: orgB.id });+ await makeUserWithAlias({ externalId: social, orgId: null, aliasType: UserAliasType.GITHUB });++ const { resolved } = await resolveAs(orgA.id, [mine, theirs, social]);++ expect([...resolved.keys()]).toEqual([mine]);+ expect(resolved.get(mine)?.id).toBe(mineUser.id);+ });++ test("the same identifier in two orgs resolves to each org's own user, never the other's", async () => {+ const orgA = await makeOrg();+ const orgB = await makeOrg();+ const identifier = `id-${crypto.randomUUID()}`;+ const userA = await makeUserWithAlias({ externalId: identifier, orgId: orgA.id });+ const userB = await makeUserWithAlias({ externalId: identifier, orgId: orgB.id });++ const fromA = await resolveAs(orgA.id, [identifier]);+ const fromB = await resolveAs(orgB.id, [identifier]);++ expect(fromA.resolved.get(identifier)?.id).toBe(userA.id);+ expect(fromB.resolved.get(identifier)?.id).toBe(userB.id);+ // Reused identifiers across tenants are not an ambiguity: each org sees only its own.+ expect(fromA.ambiguousIdentifiers).toEqual([]);+ expect(fromB.ambiguousIdentifiers).toEqual([]);+ });+});diff --git a/backend/e2e-test/routes/v1/sso-deprovisioning.spec.ts b/backend/e2e-test/routes/v1/sso-deprovisioning.spec.tsnew file mode 100644index 0000000000..0ff8db1ff1--- /dev/null+++ b/backend/e2e-test/routes/v1/sso-deprovisioning.spec.ts@@ -0,0 +1,327 @@+import crypto from "node:crypto";++import { AccessScope, OrgMembershipStatus, TableName } from "@app/db/schemas";+import { seedData1 } from "@app/db/seed-data";+import { UserAliasType } from "@app/services/user-alias/user-alias-types";++const ORG_ID = seedData1.organization.id;+const PROJECT_ID = seedData1.project.id;+const UPN_DOMAIN = "upn.example.local";++let identityToken = "";+const createdUserIds: string[] = [];+const createdGroupIds: string[] = [];+const createdOrgIds: string[] = [];++const mailbox = () => `p-${crypto.randomUUID()}@mail.example.local`;+const upn = () => `m${crypto.randomInt(100000, 999999)}@${UPN_DOMAIN}`;++/** A member with an SSO alias whose externalId is a UPN, mirroring the customer's shape. */+const seedAliasedMember = async (opts: { externalId: string; aliasOrgId?: string | null } & { email?: string }) => {+ const email = opts.email ?? mailbox();+ const [user] = await testDb(TableName.Users)+ .insert({ username: email, email, isAccepted: true, isGhost: false, authMethods: ["email"] })+ .returning("*");+ createdUserIds.push(user.id);++ await testDb(TableName.UserAliases).insert({+ userId: user.id,+ externalId: opts.externalId,+ orgId: opts.aliasOrgId === undefined ? ORG_ID : opts.aliasOrgId,+ aliasType: UserAliasType.OIDC,+ isEmailVerified: true+ });++ const [orgM] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ actorUserId: user.id,+ scopeOrgId: ORG_ID,+ isActive: true,+ status: OrgMembershipStatus.Accepted+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: orgM.id, role: "member" });++ return user;+};++const giveDirectProjectMembership = async (userId: string) => {+ const [m] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Project,+ actorUserId: userId,+ scopeOrgId: ORG_ID,+ scopeProjectId: PROJECT_ID,+ isActive: true+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: m.id, role: "member" });+ return m;+};++const giveProjectKey = (userId: string) =>+ testDb(TableName.ProjectKeys).insert({+ projectId: PROJECT_ID,+ receiverId: userId,+ encryptedKey: "encrypted",+ nonce: "nonce"+ });++/** Puts the user in a group that is itself a member of the project. */+const giveGroupProjectAccess = async (userId: string) => {+ const [group] = await testDb(TableName.Groups)+ .insert({ orgId: ORG_ID, name: `g-${crypto.randomUUID()}`, slug: `g-${crypto.randomUUID()}` })+ .returning("*");+ createdGroupIds.push(group.id);+ await testDb(TableName.UserGroupMembership).insert({ userId, groupId: group.id, isPending: false });+ const [m] = await testDb(TableName.Membership)+ .insert({+ scope: AccessScope.Project,+ actorGroupId: group.id,+ scopeOrgId: ORG_ID,+ scopeProjectId: PROJECT_ID,+ isActive: true+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: m.id, role: "member" });+ return group;+};++const projectMemberships = (userId: string) =>+ testDb(TableName.Membership).where({ actorUserId: userId, scopeProjectId: PROJECT_ID, scope: AccessScope.Project });+const projectKeys = (userId: string) =>+ testDb(TableName.ProjectKeys).where({ receiverId: userId, projectId: PROJECT_ID });+const aliasesFor = (userId: string) => testDb(TableName.UserAliases).where({ userId });++const removeFromProject = (body: { usernames?: string[]; emails?: string[] }) =>+ testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${PROJECT_ID}/memberships`,+ headers: { authorization: `Bearer ${identityToken}` },+ body: { usernames: body.usernames ?? [], emails: body.emails ?? [] }+ });++describe("SSO identifier de-provisioning", () => {+ beforeAll(async () => {+ const res = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/universal-auth/login",+ body: {+ clientId: seedData1.machineIdentity.clientCredentials.id,+ clientSecret: seedData1.machineIdentity.clientCredentials.secret+ }+ });+ expect(res.statusCode).toBe(200);+ identityToken = res.json().accessToken as string;+ });++ afterEach(async () => {+ if (createdUserIds.length) {+ await testDb(TableName.ProjectKeys).whereIn("receiverId", createdUserIds).del();+ await testDb(TableName.UserGroupMembership).whereIn("userId", createdUserIds).del();+ const ids = await testDb(TableName.Membership)+ .whereIn("actorUserId", createdUserIds)+ .select("id")+ .then((r) => r.map((x) => x.id));+ if (ids.length) await testDb(TableName.MembershipRole).whereIn("membershipId", ids).del();+ await testDb(TableName.Membership).whereIn("actorUserId", createdUserIds).del();+ await testDb(TableName.UserAliases).whereIn("userId", createdUserIds).del();+ await testDb(TableName.UserEncryptionKey).whereIn("userId", createdUserIds).del();+ await testDb(TableName.Users).whereIn("id", createdUserIds).del();+ createdUserIds.length = 0;+ }+ if (createdGroupIds.length) {+ const ids = await testDb(TableName.Membership)+ .whereIn("actorGroupId", createdGroupIds)+ .select("id")+ .then((r) => r.map((x) => x.id));+ if (ids.length) await testDb(TableName.MembershipRole).whereIn("membershipId", ids).del();+ await testDb(TableName.Membership).whereIn("actorGroupId", createdGroupIds).del();+ await testDb(TableName.UserGroupMembership).whereIn("groupId", createdGroupIds).del();+ await testDb(TableName.Groups).whereIn("id", createdGroupIds).del();+ createdGroupIds.length = 0;+ }+ if (createdOrgIds.length) {+ await testDb(TableName.Organization).whereIn("id", createdOrgIds).del();+ createdOrgIds.length = 0;+ }+ });++ describe("removal by IdP identifier", () => {+ test("removes the aliased member's project membership", async () => {+ const identifier = upn();+ const user = await seedAliasedMember({ externalId: identifier });+ await giveDirectProjectMembership(user.id);++ expect((await removeFromProject({ usernames: [identifier] })).statusCode).toBe(200);++ await expect(projectMemberships(user.id)).resolves.toHaveLength(0);+ });++ test("removes the project key of a member with no other access", async () => {+ const identifier = upn();+ const user = await seedAliasedMember({ externalId: identifier });+ await giveDirectProjectMembership(user.id);+ await giveProjectKey(user.id);++ expect((await removeFromProject({ usernames: [identifier] })).statusCode).toBe(200);++ await expect(projectKeys(user.id)).resolves.toHaveLength(0);+ });++ // The regression this guards: the group lookup keys on users.username, so removal must resolve+ // the identifier before consulting it. Feeding it the raw UPN would match nothing and strip the+ // project key of someone who still reaches the project through their group.+ test("PRESERVES the project key when the member still has group access", async () => {+ const identifier = upn();+ const user = await seedAliasedMember({ externalId: identifier });+ await giveDirectProjectMembership(user.id);+ await giveProjectKey(user.id);+ await giveGroupProjectAccess(user.id);++ expect((await removeFromProject({ usernames: [identifier] })).statusCode).toBe(200);++ await expect(projectMemberships(user.id)).resolves.toHaveLength(0);+ await expect(projectKeys(user.id)).resolves.toHaveLength(1);+ });++ test("removal by email behaves identically for a group member", async () => {+ const email = mailbox();+ const user = await seedAliasedMember({ externalId: upn(), email });+ await giveDirectProjectMembership(user.id);+ await giveProjectKey(user.id);+ await giveGroupProjectAccess(user.id);++ expect((await removeFromProject({ emails: [email] })).statusCode).toBe(200);++ await expect(projectKeys(user.id)).resolves.toHaveLength(1);+ });++ test("naming one person by both email and identifier removes them once", async () => {+ const email = mailbox();+ const identifier = upn();+ const user = await seedAliasedMember({ externalId: identifier, email });+ await giveDirectProjectMembership(user.id);++ expect((await removeFromProject({ emails: [email], usernames: [identifier] })).statusCode).toBe(200);++ await expect(projectMemberships(user.id)).resolves.toHaveLength(0);+ });++ test("removes several members named by a mix of emails and identifiers", async () => {+ const emailUser = await seedAliasedMember({ externalId: upn() });+ const upnIdentifier = upn();+ const upnUser = await seedAliasedMember({ externalId: upnIdentifier });+ await giveDirectProjectMembership(emailUser.id);+ await giveDirectProjectMembership(upnUser.id);++ const res = await removeFromProject({ emails: [emailUser.username], usernames: [upnIdentifier] });++ expect(res.statusCode).toBe(200);+ await expect(projectMemberships(emailUser.id)).resolves.toHaveLength(0);+ await expect(projectMemberships(upnUser.id)).resolves.toHaveLength(0);+ });++ test("deletes the member's additional privileges", async () => {+ const identifier = upn();+ const user = await seedAliasedMember({ externalId: identifier });+ await giveDirectProjectMembership(user.id);+ await testDb(TableName.AdditionalPrivilege).insert({+ actorUserId: user.id,+ projectId: PROJECT_ID,+ name: `priv-${crypto.randomUUID()}`,+ permissions: JSON.stringify([])+ });++ expect((await removeFromProject({ usernames: [identifier] })).statusCode).toBe(200);++ await expect(+ testDb(TableName.AdditionalPrivilege).where({ actorUserId: user.id, projectId: PROJECT_ID })+ ).resolves.toHaveLength(0);+ });+ });++ describe("removal refuses to act on a partial or ambiguous match", () => {+ test("a member plus a non-member removes nobody", async () => {+ const identifier = upn();+ const member = await seedAliasedMember({ externalId: identifier });+ await giveDirectProjectMembership(member.id);+ const strangerId = upn();+ const stranger = await seedAliasedMember({ externalId: strangerId });++ const res = await removeFromProject({ usernames: [identifier, strangerId] });++ expect(res.statusCode).toBe(400);+ expect(res.json().message).toContain("not part of project");+ // The whole request is rejected, so the real member keeps their access.+ await expect(projectMemberships(member.id)).resolves.toHaveLength(1);+ await expect(projectMemberships(stranger.id)).resolves.toHaveLength(0);+ });++ test("an identifier reaching two accounts removes nobody", async () => {+ const identifier = upn();+ const a = await seedAliasedMember({ externalId: identifier });+ const b = await seedAliasedMember({ externalId: identifier });+ await giveDirectProjectMembership(a.id);+ await giveDirectProjectMembership(b.id);++ const res = await removeFromProject({ usernames: [identifier] });++ expect(res.statusCode).toBe(400);+ expect(res.json().message).toContain(identifier);+ await expect(projectMemberships(a.id)).resolves.toHaveLength(1);+ await expect(projectMemberships(b.id)).resolves.toHaveLength(1);+ });++ test("an alias belonging to another org removes nobody", async () => {+ const identifier = upn();+ const [otherOrg] = await testDb(TableName.Organization)+ .insert({ name: "other", slug: `other-${crypto.randomUUID()}` })+ .returning("*");+ createdOrgIds.push(otherOrg.id);+ const user = await seedAliasedMember({ externalId: identifier, aliasOrgId: otherOrg.id });+ await giveDirectProjectMembership(user.id);++ const res = await removeFromProject({ usernames: [identifier] });++ expect(res.statusCode).toBe(400);+ await expect(projectMemberships(user.id)).resolves.toHaveLength(1);+ });++ test("a global social alias removes nobody", async () => {+ const identifier = upn();+ const user = await seedAliasedMember({ externalId: identifier, aliasOrgId: null });+ await testDb(TableName.UserAliases)+ .where({ userId: user.id })+ .update({ aliasType: UserAliasType.GOOGLE, orgId: null });+ await giveDirectProjectMembership(user.id);++ const res = await removeFromProject({ usernames: [identifier] });++ expect(res.statusCode).toBe(400);+ await expect(projectMemberships(user.id)).resolves.toHaveLength(1);+ });+ });++ describe("org membership removal reaps the org-scoped alias", () => {+ test("deleting an org membership deletes that org's alias", async () => {+ const user = await seedAliasedMember({ externalId: upn() });+ expect(await aliasesFor(user.id)).toHaveLength(1);+ const [orgMembership] = await testDb(TableName.Membership).where({+ actorUserId: user.id,+ scopeOrgId: ORG_ID,+ scope: AccessScope.Organization+ });++ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v2/organizations/${ORG_ID}/memberships/${orgMembership.id}`,+ headers: { authorization: `Bearer ${identityToken}` }+ });++ expect(res.statusCode).toBe(200);+ await expect(aliasesFor(user.id)).resolves.toHaveLength(0);+ });+ });+});diff --git a/backend/e2e-test/routes/v1/sso-provisioning-matrix.spec.ts b/backend/e2e-test/routes/v1/sso-provisioning-matrix.spec.tsnew file mode 100644index 0000000000..f4e5a9f465--- /dev/null+++ b/backend/e2e-test/routes/v1/sso-provisioning-matrix.spec.ts@@ -0,0 +1,376 @@+import crypto from "node:crypto";++import { AccessScope, OrgMembershipStatus, TableName } from "@app/db/schemas";+import { seedData1 } from "@app/db/seed-data";+import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";+import { UserAliasType } from "@app/services/user-alias/user-alias-types";++const ORG_ID = seedData1.organization.id;+const PROJECT_ID = seedData1.project.id;+const MAIL_DOMAIN = "mail.example.local";+const UPN_DOMAIN = "upn.example.local";++let identityToken = "";+const createdUserIds: string[] = [];+const createdOrgIds: string[] = [];++const mailbox = () => `p-${crypto.randomUUID()}@${MAIL_DOMAIN}`;+const upn = () => `m${crypto.randomInt(100000, 999999)}@${UPN_DOMAIN}`;++const seedUser = async (username: string, overrides: Record<string, unknown> = {}) => {+ const [user] = await testDb(TableName.Users)+ .insert({ username, email: username, isAccepted: true, isGhost: false, authMethods: ["email"], ...overrides })+ .returning("*");+ createdUserIds.push(user.id);+ return user;+};++const seedAlias = (opts: {+ userId: string;+ externalId: string;+ orgId?: string | null;+ aliasType?: UserAliasType;+}) =>+ testDb(TableName.UserAliases).insert({+ userId: opts.userId,+ externalId: opts.externalId,+ orgId: opts.orgId === undefined ? ORG_ID : opts.orgId,+ aliasType: opts.aliasType ?? UserAliasType.OIDC,+ isEmailVerified: true+ });++const seedMembership = async (userId: string, scope: AccessScope) => {+ const [m] = await testDb(TableName.Membership)+ .insert({+ scope,+ actorUserId: userId,+ scopeOrgId: ORG_ID,+ scopeProjectId: scope === AccessScope.Project ? PROJECT_ID : null,+ isActive: true,+ status: scope === AccessScope.Organization ? OrgMembershipStatus.Accepted : null+ })+ .returning("*");+ await testDb(TableName.MembershipRole).insert({ membershipId: m.id, role: "member" });+ return m;+};++const findUser = (username: string) =>+ testDb(TableName.Users).where({ username }).select("id", "username", "email", "isAccepted").first();+const requireUser = async (username: string) => {+ const user = await findUser(username);+ if (!user) throw new Error(`expected a user with username '${username}'`);+ return user;+};+const usersByEmail = (email: string) => testDb(TableName.Users).where({ email }).select("id");+const orgMemberships = (userId: string) =>+ testDb(TableName.Membership).where({ actorUserId: userId, scopeOrgId: ORG_ID, scope: AccessScope.Organization });+const projectMemberships = (userId: string) =>+ testDb(TableName.Membership).where({ actorUserId: userId, scopeProjectId: PROJECT_ID, scope: AccessScope.Project });++// The customer's entitlement system authenticates as a machine identity, which is also the only way+// to reach these routes once the org enforces SSO: an email-login JWT is refused org-scoped access.+const asIdentity = (method: "POST" | "DELETE", body: object) =>+ testServer.inject({+ method,+ url: `/api/v1/projects/${PROJECT_ID}/memberships`,+ headers: { authorization: `Bearer ${identityToken}` },+ body+ });++const addToProject = (usernames: string[]) => asIdentity("POST", { usernames, emails: [], roleSlugs: ["member"] });+const removeFromProject = (usernames: string[]) => asIdentity("DELETE", { usernames, emails: [] });+const readMembership = (username: string) =>+ testServer.inject({+ method: "POST",+ url: `/api/v1/projects/${PROJECT_ID}/memberships/details`,+ headers: { authorization: `Bearer ${identityToken}` },+ body: { username }+ });++const inviteToOrg = (inviteeEmails: string[], projectIds?: string[]) =>+ testServer.inject({+ method: "POST",+ url: "/api/v1/invite-org/signup",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: { inviteeEmails, organizationId: ORG_ID, ...(projectIds ? { projectIds } : {}) }+ });++const setAuthEnforced = (value: boolean) =>+ testDb(TableName.Organization).where({ id: ORG_ID }).update({ authEnforced: value });++describe("SSO identifier provisioning", () => {+ beforeAll(async () => {+ const res = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/universal-auth/login",+ body: {+ clientId: seedData1.machineIdentity.clientCredentials.id,+ clientSecret: seedData1.machineIdentity.clientCredentials.secret+ }+ });+ expect(res.statusCode).toBe(200);+ identityToken = res.json().accessToken as string;++ for await (const domain of [MAIL_DOMAIN, UPN_DOMAIN]) {+ await testDb(TableName.EmailDomains).insert({+ orgId: ORG_ID,+ domain,+ status: EmailDomainStatus.Verified,+ verificationCode: crypto.randomUUID(),+ verificationRecordName: `_infisical.${domain}`,+ codeExpiresAt: new Date(Date.now() + 86_400_000)+ });+ }+ });++ afterAll(async () => {+ await testDb(TableName.EmailDomains).where({ orgId: ORG_ID }).whereIn("domain", [MAIL_DOMAIN, UPN_DOMAIN]).del();+ });++ afterEach(async () => {+ await setAuthEnforced(false);+ if (createdUserIds.length) {+ const ids = await testDb(TableName.Membership)+ .whereIn("actorUserId", createdUserIds)+ .select("id")+ .then((r) => r.map((x) => x.id));+ if (ids.length) await testDb(TableName.MembershipRole).whereIn("membershipId", ids).del();+ await testDb(TableName.Membership).whereIn("actorUserId", createdUserIds).del();+ await testDb(TableName.UserAliases).whereIn("userId", createdUserIds).del();+ await testDb(TableName.UserEncryptionKey).whereIn("userId", createdUserIds).del();+ await testDb(TableName.Users).whereIn("id", createdUserIds).del();+ createdUserIds.length = 0;+ }+ if (createdOrgIds.length) {+ await testDb(TableName.Organization).whereIn("id", createdOrgIds).del();+ createdOrgIds.length = 0;+ }+ });++ describe("machine identity provisions a project, org enforces SSO", () => {+ beforeEach(() => setAuthEnforced(true));++ test("an IdP identifier resolves through the SSO alias, no second account", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier });++ expect((await addToProject([identifier])).statusCode).toBe(200);++ await expect(findUser(identifier)).resolves.toBeUndefined();+ await expect(projectMemberships(user.id)).resolves.toHaveLength(1);+ await expect(orgMemberships(user.id)).resolves.toHaveLength(1);+ });++ test("the same person named by email and identifier lands one membership", async () => {+ const email = mailbox();+ const identifier = upn();+ const user = await seedUser(email);+ await seedAlias({ userId: user.id, externalId: identifier });++ expect((await asIdentity("POST", { emails: [email], usernames: [identifier], roleSlugs: ["member"] })).statusCode).toBe(200);++ await expect(projectMemberships(user.id)).resolves.toHaveLength(1);+ });++ test("SAML and LDAP aliases resolve too", async () => {+ const samlId = upn();+ const ldapId = upn();+ const samlUser = await seedUser(mailbox());+ const ldapUser = await seedUser(mailbox());+ await seedAlias({ userId: samlUser.id, externalId: samlId, aliasType: UserAliasType.SAML });+ await seedAlias({ userId: ldapUser.id, externalId: ldapId, aliasType: UserAliasType.LDAP });++ expect((await addToProject([samlId, ldapId])).statusCode).toBe(200);++ await expect(findUser(samlId)).resolves.toBeUndefined();+ await expect(findUser(ldapId)).resolves.toBeUndefined();+ await expect(projectMemberships(samlUser.id)).resolves.toHaveLength(1);+ await expect(projectMemberships(ldapUser.id)).resolves.toHaveLength(1);+ });++ test("an unknown identifier falls through to a placeholder", async () => {+ const identifier = upn();++ expect((await addToProject([identifier])).statusCode).toBe(200);++ const shadow = await requireUser(identifier);+ expect(shadow).toMatchObject({ email: identifier, isAccepted: false });+ createdUserIds.push(shadow.id);+ });++ test("removal accepts the identifier the caller provisioned with", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier });+ await seedMembership(user.id, AccessScope.Project);++ expect((await removeFromProject([identifier])).statusCode).toBe(200);++ await expect(projectMemberships(user.id)).resolves.toHaveLength(0);+ });++ test("removal tolerates the same person named twice", async () => {+ const email = mailbox();+ const identifier = upn();+ const user = await seedUser(email);+ await seedAlias({ userId: user.id, externalId: identifier });+ await seedMembership(user.id, AccessScope.Project);++ expect((await asIdentity("DELETE", { emails: [email], usernames: [identifier] })).statusCode).toBe(200);++ await expect(projectMemberships(user.id)).resolves.toHaveLength(0);+ });++ test("removal still rejects someone who is not a member", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier });++ expect((await removeFromProject([identifier])).statusCode).toBe(400);+ });++ test("membership read-back works by identifier", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier });+ await seedMembership(user.id, AccessScope.Project);++ const res = await readMembership(identifier);++ expect(res.statusCode).toBe(200);+ expect(res.json().membership.user.id).toBe(user.id);+ });+ });++ describe("resolution boundaries", () => {+ beforeEach(() => setAuthEnforced(true));++ const expectsNoResolve = async (identifier: string, userId: string) => {+ expect((await addToProject([identifier])).statusCode).toBe(200);+ const shadow = await requireUser(identifier);+ createdUserIds.push(shadow.id);+ await expect(projectMemberships(userId)).resolves.toHaveLength(0);+ };++ test("an alias in another org does not resolve", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ const [otherOrg] = await testDb(TableName.Organization)+ .insert({ name: "other", slug: `other-${crypto.randomUUID()}` })+ .returning("*");+ createdOrgIds.push(otherOrg.id);+ await seedAlias({ userId: user.id, externalId: identifier, orgId: otherOrg.id });++ await expectsNoResolve(identifier, user.id);+ });++ test("a global social alias does not resolve", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier, orgId: null, aliasType: UserAliasType.GOOGLE });++ await expectsNoResolve(identifier, user.id);+ });++ test("a differently-cased identifier does not resolve", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier.toUpperCase() });++ await expectsNoResolve(identifier, user.id);+ });++ test("a ghost user is never reachable by an identifier", async () => {+ const identifier = upn();+ const ghost = await seedUser(mailbox(), { isGhost: true });+ await seedAlias({ userId: ghost.id, externalId: identifier });++ await expectsNoResolve(identifier, ghost.id);+ });++ test("an identifier reaching two accounts is rejected rather than guessed", async () => {+ const identifier = upn();+ const a = await seedUser(mailbox());+ const b = await seedUser(mailbox());+ await seedAlias({ userId: a.id, externalId: identifier });+ await seedAlias({ userId: b.id, externalId: identifier });++ const res = await addToProject([identifier]);++ expect(res.statusCode).toBe(400);+ expect(res.json().message).toContain(identifier);+ await expect(findUser(identifier)).resolves.toBeUndefined();+ });+ });++ // The majority of installs have no SSO at all. Nothing here should touch the alias path, and the+ // failure messages a plain org already gets must not change shape.+ describe("org with no SSO configured", () => {+ test("a plain email invite behaves exactly as before", async () => {+ const email = `plain-${crypto.randomUUID()}@no-sso.example`;++ expect((await inviteToOrg([email])).statusCode).toBe(200);++ const user = await requireUser(email);+ expect(user).toMatchObject({ username: email, email, isAccepted: false });+ createdUserIds.push(user.id);+ await expect(orgMemberships(user.id)).resolves.toHaveLength(1);+ });++ test("a non-email identifier still fails with the original validation error", async () => {+ const res = await asIdentity("POST", { usernames: ["not-an-email-at-all"], emails: [], roleSlugs: ["member"] });++ expect(res.statusCode).toBe(400);+ expect(res.json().message).toContain("Invalid emails");+ });++ test("removing someone who was never a member still fails the same way", async () => {+ const res = await removeFromProject([`ghost-${crypto.randomUUID()}@no-sso.example`]);++ expect(res.statusCode).toBe(400);+ expect(res.json().message).toContain("not part of project");+ });++ test("membership read-back for an unknown user still 404s", async () => {+ const res = await readMembership(`nobody-${crypto.randomUUID()}@no-sso.example`);++ expect(res.statusCode).toBe(404);+ });+ });++ describe("org invite by a user session, enforcement off", () => {+ test("a new person still gets a placeholder keyed on their email", async () => {+ const email = mailbox();++ expect((await inviteToOrg([email])).statusCode).toBe(200);++ const user = await requireUser(email);+ expect(user).toMatchObject({ email, isAccepted: false });+ createdUserIds.push(user.id);+ await expect(orgMemberships(user.id)).resolves.toHaveLength(1);+ });++ test("an existing member resolves by username and gains no duplicate", async () => {+ const email = mailbox();+ const user = await seedUser(email);+ await seedMembership(user.id, AccessScope.Organization);++ expect((await inviteToOrg([email])).statusCode).toBe(200);++ await expect(orgMemberships(user.id)).resolves.toHaveLength(1);+ await expect(usersByEmail(email)).resolves.toHaveLength(1);+ });++ test("an identifier resolves through the alias and can carry a project grant", async () => {+ const identifier = upn();+ const user = await seedUser(mailbox());+ await seedAlias({ userId: user.id, externalId: identifier });++ expect((await inviteToOrg([identifier], [PROJECT_ID])).statusCode).toBe(200);++ await expect(findUser(identifier)).resolves.toBeUndefined();+ await expect(projectMemberships(user.id)).resolves.toHaveLength(1);+ });+ });+});