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
only accept canonical to external id if case doesnt match create new account
Thiago Araujo da Silvac148d34f8eb4
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 85a26a9bbc..58e6176f19 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -363,8 +363,13 @@ Four invariants, each load-bearing:lowercase their input (`sanitizeEmail`, and the `.refine` on `usernames`), an IdP that assertsmixed-case identifiers cannot be provisioned against at all. Supporting those means relaxing thatinput validation so the exact identifier survives to the query, not loosening the comparison.- Note the one deliberate exception: `adoptProvisionedShadowUser` *does* lowercase, because it looks- the identifier up in the `users.username` namespace, where lowercase is canonical.+ `adoptProvisionedShadowUser` does not fold either. It derives its lookup key with `sanitizeEmail`+ because it searches the `users.username` namespace, where lowercase is canonical, but it then+ **refuses any identifier that is not already canonical** rather than adopting on the folded match.+ It once did adopt, and that was a real hole: a subject differing only by case is a different+ subject, so it could take over the placeholder provisioned for another one and inherit its grants.+ Folding bought nothing anyway, since the alias written afterwards is verbatim and this exact-match+ lookup could never find it again, stranding the grant where provisioning cannot manage it.- **Ambiguity is an error.** Nothing constrains `(externalId, aliasType)` to be unique for theorg-scoped types (only the social ones have a partial unique index), so an identifier can reach twousers. Picking one would be a guess about which human it names, and the cost of guessing wrong is@@ -378,7 +383,8 @@ in, leaving a placeholder account keyed on the identifier instead of the mailbox`adoptProvisionedShadowUser` (same file, wired into `oidcLogin`'s no-alias branch) adopts that rowand rewrites it to the asserted mailbox rather than creating a second account. It refuses anything ahuman has claimed (accepted, email-verified, holding a password), anything already bound to an IdP-(any alias, any org), ghosts, and anything without a membership in the org doing the login.+(any alias, any org), ghosts, anything whose identifier is not already canonical (see above), and+anything without a membership in the org doing the login.It also refuses a placeholder that holds an org membership **outside** the login org's own sub-orgfamily, and that one is the security-critical check rather than a tidiness one. The username lookup@@ -403,6 +409,12 @@ is whoever won the race rather than a rewritten placeholder. `adoptProvisionedShline by returning `adoptedFromUsername: null` for the yield, and the caller keys the audit log onit.+That trail is best-effort, not guaranteed. `audit-log-queue.ts` drops every entry at push time when+`plan.auditLogsRetentionDays` is falsy, which is the default for a self-hosted instance with no+audit-log entitlement, so on those deployments only the `logger.info` line survives an adoption.+Do not special-case this event past the retention gate; treat the application log as the floor and+the audit event as the addition for licensed instances.+### Permission System (CASL)Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives in `src/ee/services/permission/`: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.tsindex 42b2b50feb..12f6c5a03d 100644--- a/backend/e2e-test/routes/v1/sso-alias-tenant-isolation.spec.ts+++ b/backend/e2e-test/routes/v1/sso-alias-tenant-isolation.spec.ts@@ -1,7 +1,6 @@import crypto from "node:crypto";-import { TableName } from "@app/db/schemas";-import { AccessScope, OrgMembershipStatus } from "@app/db/schemas";+import { AccessScope, OrgMembershipStatus, TableName } 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";@@ -137,10 +136,7 @@ describe("SSO alias resolution is tenant scoped", () => {await makeUserWithAlias({ externalId: identifier, orgId: org.id, aliasType });}- const { resolved } = await resolveAs(- org.id,- Object.values(ids)- );+ 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));@@ -269,6 +265,37 @@ describe("SSO alias resolution is tenant scoped", () => {email: asserted});});++ // `sub` is case-sensitive per OIDC Core, so this is a second subject the IdP could hand to a+ // different human. Folding it onto the placeholder would give that human whatever the first+ // subject was provisioned for, and the resulting alias would be stored verbatim, leaving the+ // grant unreachable from the provisioning side (which matches externalId exactly) afterwards.+ test("a subject differing only by case cannot adopt another subject's placeholder", async () => {+ const org = await makeOrg();+ const identifier = `ph-${crypto.randomUUID()}@tenant.example`;+ const placeholder = await seedPlaceholder(identifier, org.id);++ const adopted = await adoptAs(org.id, identifier.toUpperCase(), `other-${crypto.randomUUID()}@tenant.example`);++ expect(adopted).toBeNull();+ await expect(testDb(TableName.Users).where({ id: placeholder.id }).first()).resolves.toMatchObject({+ username: identifier,+ email: identifier+ });+ });++ test("the placeholder stays adoptable by the subject it was actually provisioned for", 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);++ expect(await adoptAs(org.id, identifier.toUpperCase(), `other-${crypto.randomUUID()}@tenant.example`)).toBeNull();+ const adopted = await adoptAs(org.id, identifier, asserted);++ expect(adopted?.user.id).toBe(placeholder.id);+ expect(adopted?.adoptedFromUsername).toBe(identifier);+ });});test("a batch resolves only the in-scope members of a mixed set", async () => {diff --git a/backend/src/ee/services/pam-membership/pam-membership-service.test.ts b/backend/src/ee/services/pam-membership/pam-membership-service.test.tsnew file mode 100644index 0000000000..ab2de32e3e--- /dev/null+++ b/backend/src/ee/services/pam-membership/pam-membership-service.test.ts@@ -0,0 +1,133 @@+import { describe, expect, test, vi } from "vitest";++import { AccessScope } from "@app/db/schemas";+import { ActorType } from "@app/services/auth/auth-type";+import { UserAliasType } from "@app/services/user-alias/user-alias-types";++import { PamProductRole } from "../pam/pam-enums";+import { pamMembershipServiceFactory } from "./pam-membership-service";++const ORG_ID = "org-1";+const PROJECT_ID = "project-1";+const IDENTIFIER = "[email protected]";++const ctx = {+ actor: ActorType.USER,+ actorId: "actor-1",+ actorOrgId: ORG_ID,+ actorAuthMethod: undefined+} as unknown as Parameters<ReturnType<typeof pamMembershipServiceFactory>["addProductUserMembers"]>[0];++const user = (id: string, username: string) => ({ id, username, isGhost: false });++// Only the collaborators addProductUserMembers touches on the add path; everything else is left+// undefined so an unexpected reach shows up as a crash rather than a silent pass.+const buildService = ({+ usersByUsername = [] as ReturnType<typeof user>[],+ aliases = [] as { externalId: string; userId: string }[],+ orgMemberUserIds = [] as string[]+} = {}) => {+ const created: { actorUserId: string; role: string }[] = [];+ const deps = {+ permissionService: { getProjectPermission: vi.fn().mockResolvedValue({ hasRole: () => true }) },+ userDAL: {+ find: vi.fn(({ $in }: { $in: { username?: string[]; id?: string[] } }) => {+ if ($in.username) return Promise.resolve(usersByUsername.filter((u) => $in.username!.includes(u.username)));+ return Promise.resolve(usersByUsername.filter((u) => $in.id!.includes(u.id)));+ })+ },+ userAliasDAL: {+ findBySsoExternalIds: vi.fn(+ ({ externalIds }: { externalIds: string[]; orgIds: string[]; aliasTypes: string[] }) =>+ Promise.resolve(aliases.filter((a) => externalIds.includes(a.externalId)))+ )+ },+ orgDAL: { findById: vi.fn().mockResolvedValue({ id: ORG_ID, rootOrgId: null }) },+ membershipDAL: {+ find: vi.fn(({ scope }: { scope: string }) =>+ Promise.resolve(scope === AccessScope.Organization ? orgMemberUserIds.map((id) => ({ actorUserId: id })) : [])+ ),+ transaction: vi.fn((cb: (tx: unknown) => unknown) => Promise.resolve(cb({}))),+ create: vi.fn(({ actorUserId }: { actorUserId: string }) =>+ Promise.resolve({ id: `mem-${actorUserId}`, actorUserId, createdAt: new Date() })+ )+ },+ membershipRoleDAL: {+ create: vi.fn(({ role }: { role: string }) => {+ created.push({ actorUserId: "", role });+ return Promise.resolve({ role });+ })+ },+ projectAccessRequestDAL: { delete: vi.fn().mockResolvedValue(undefined) },+ usageMeteringService: { emitForProject: vi.fn() }+ };++ const service = pamMembershipServiceFactory(deps as unknown as Parameters<typeof pamMembershipServiceFactory>[0]);+ return { service, deps };+};++const add = (service: ReturnType<typeof buildService>["service"], emails: string[]) =>+ service.addProductUserMembers({+ ...ctx,+ projectId: PROJECT_ID,+ userIds: [],+ emails,+ role: PamProductRole.Member+ });++describe("pamMembership addProductUserMembers", () => {+ // The invite this call accompanies resolves IdP identifiers through SSO aliases, so PAM has to+ // as well; otherwise it rejects the very user the org invite just added.+ test("attaches a member named by an IdP identifier that only their SSO alias carries", async () => {+ const member = user("user-1", "[email protected]");+ const { service, deps } = buildService({+ usersByUsername: [member],+ aliases: [{ externalId: IDENTIFIER, userId: member.id }],+ orgMemberUserIds: [member.id]+ });++ const { memberships } = await add(service, [IDENTIFIER]);++ expect(memberships).toHaveLength(1);+ expect(memberships[0].userId).toBe(member.id);+ // The scoping arguments are the security boundary, so assert them rather than just the outcome.+ const [[lookup]] = deps.userAliasDAL.findBySsoExternalIds.mock.calls;+ expect(lookup.externalIds).toEqual([IDENTIFIER]);+ expect(lookup.orgIds).toEqual([ORG_ID]);+ expect(lookup.aliasTypes).toContain(UserAliasType.OIDC);+ });++ test("names the same person by both email and identifier without attaching them twice", async () => {+ const member = user("user-1", "[email protected]");+ const { service } = buildService({+ usersByUsername: [member],+ aliases: [{ externalId: IDENTIFIER, userId: member.id }],+ orgMemberUserIds: [member.id]+ });++ const { memberships } = await add(service, [member.username, IDENTIFIER]);++ expect(memberships).toHaveLength(1);+ });++ test("refuses an identifier that reaches two accounts rather than guessing", async () => {+ const one = user("user-1", "[email protected]");+ const two = user("user-2", "[email protected]");+ const { service } = buildService({+ usersByUsername: [one, two],+ aliases: [+ { externalId: IDENTIFIER, userId: one.id },+ { externalId: IDENTIFIER, userId: two.id }+ ],+ orgMemberUserIds: [one.id, two.id]+ });++ await expect(add(service, [IDENTIFIER])).rejects.toThrow(/match more than one SSO account/);+ });++ test("still rejects an identifier nothing resolves, naming what the caller sent", async () => {+ const { service } = buildService();++ await expect(add(service, [IDENTIFIER])).rejects.toThrow(new RegExp(`'${IDENTIFIER}'`));+ });+});diff --git a/backend/src/services/user-alias/user-alias-fns.test.ts b/backend/src/services/user-alias/user-alias-fns.test.tsindex 30dc20299b..25ec9d915d 100644--- a/backend/src/services/user-alias/user-alias-fns.test.ts+++ b/backend/src/services/user-alias/user-alias-fns.test.ts@@ -160,12 +160,20 @@ describe("adoptProvisionedShadowUser", () => {);});- test("looks the placeholder up by the sanitized identifier, so a mixed-case claim still matches", async () => {+ // `sub` is case-sensitive, so this is a different subject from EXTERNAL_ID, not the same person+ // typed differently. Adopting on a folded match would hand it the other subject's access.+ test("declines an identifier that is not already canonical, rather than folding it onto a placeholder", async () => {const deps = buildDeps();- await adopt(deps, "[email protected]");+ expect(await adopt(deps, "[email protected]")).toBeNull();+ expect(deps.userDAL.findOne).not.toHaveBeenCalled();+ });- expect(deps.userDAL.findOne).toHaveBeenCalledWith({ username: EXTERNAL_ID }, deps.tx);+ test("declines an identifier padded with whitespace, which sanitizing would otherwise trim into a match", async () => {+ const deps = buildDeps();++ expect(await adopt(deps, ` ${EXTERNAL_ID} `)).toBeNull();+ expect(deps.userDAL.findOne).not.toHaveBeenCalled();});test("declines when the identifier is already the asserted email", async () => {diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.tsindex 91c7395949..3310e7bdee 100644--- a/backend/src/services/user-alias/user-alias-fns.ts+++ b/backend/src/services/user-alias/user-alias-fns.ts@@ -230,11 +230,13 @@ export const adoptProvisionedShadowUser = async ({orgDAL,tx}: TAdoptProvisionedShadowUserDTO): Promise<TAdoptProvisionedShadowUserResult | null> => {- // We fold case here even though resolveUsersBySsoExternalId doesn't, because this is a username- // lookup and usernames are canonically lowercase (validateEmail rejects uppercase ones). The- // placeholder's username came from lowercasing the provisioner's input, so match that form.+ // Only an identifier that is already canonical can name the placeholder, whose username came from+ // lowercasing the provisioner's input. A differently-cased identifier is a *different* subject+ // (OIDC Core defines `sub` as case-sensitive), so folding onto that match would hand it whatever+ // the other subject was granted, and would not work end to end anyway: the alias written here is+ // verbatim, and resolveUsersBySsoExternalId never folds when looking it up again.const shadowUsername = sanitizeEmail(externalId);- if (!shadowUsername || shadowUsername === assertedEmail) return null;+ if (!shadowUsername || shadowUsername !== externalId || shadowUsername === assertedEmail) return null;const candidate = await userDAL.findOne({ username: shadowUsername }, tx);if (!candidate) return null;