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
/* eslint-disable no-await-in-loop */
import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
import RE2 from "re2";
import {
AccessScope,
OrganizationActionScope,
OrgMembershipRole,
OrgMembershipStatus,
TableName,
TGroups,
TSamlConfigs,
TSamlConfigsUpdate,
TUsers
} from "@app/db/schemas";
import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { getEnforcedIdentityLimit, throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { recordSsoConfigChangeMetric, SsoConfigAction, SsoProvider } from "@app/lib/telemetry/metrics";
import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { TAlertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { AuthMethod } from "@app/services/auth/auth-type";
import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";
import { TIdentityMetadataDALFactory } from "@app/services/identity/identity-metadata-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { getDefaultOrgMembershipRole } from "@app/services/org/org-role-fns";
import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
import { LoginMethod } from "@app/services/super-admin/super-admin-types";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
import { ensureSsoAccountVerified, isStaleSsoAlias, syncSsoUserProfile } from "@app/services/user-alias/user-alias-fns";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";
import {
findOrgIdByVerifiedDomain,
isIdpAuthoritativeForDomain,
verifyEmailDomainOwnership
} from "../email-domain/email-domain-fns";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
import { TGroupDALFactory } from "../group/group-dal";
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "../group/group-fns";
import { TUserGroupMembershipDALFactory } from "../group/user-group-membership-dal";
import { TLicenseServiceFactory } from "../license/license-service";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
import { OrgPermissionSsoActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { getSamlAssertionReplayDetails, getSamlAssertionReplayWindow } from "./saml-assertion-fns";
import { TSamlConfigDALFactory } from "./saml-config-dal";
import { SamlProviders, TSamlConfigServiceFactory } from "./saml-config-types";
// SAML providers that support group sync
const GROUP_SYNC_SUPPORTED_PROVIDERS = [SamlProviders.GOOGLE_SAML] as SamlProviders[];
type TSamlConfigServiceFactoryDep = {
samlConfigDAL: Pick<TSamlConfigDALFactory, "create" | "findOne" | "update" | "findById">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
userDAL: Pick<
TUserDALFactory,
| "create"
| "findOne"
| "find"
| "transaction"
| "updateById"
| "findById"
| "findUserEncKeyByUserId"
| "findUserEncKeyByUserIdsBatch"
>;
userAliasDAL: Pick<TUserAliasDALFactory, "create" | "findOne" | "updateById">;
orgDAL: Pick<
TOrgDALFactory,
| "createMembership"
| "updateMembershipById"
| "findMembership"
| "findOrgById"
| "findOne"
| "updateById"
| "lockActorsForOrgAccess"
>;
identityMetadataDAL: Pick<TIdentityMetadataDALFactory, "delete" | "insertMany" | "transaction">;
membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActors">;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "find">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getOrgSeatUsage" | "updateSubscriptionOrgMemberCount">;
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
smtpService: Pick<TSmtpService, "sendMail">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
userGroupMembershipDAL: Pick<
TUserGroupMembershipDALFactory,
"find" | "delete" | "transaction" | "insertMany" | "filterProjectsByUserMembership"
>;
groupDAL: Pick<TGroupDALFactory, "create" | "findOne" | "find" | "transaction" | "findGroupOrgIds">;
projectDAL: Pick<TProjectDALFactory, "findById" | "findProjectGhostUser">;
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete" | "findLatestProjectKey" | "insertMany">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "pruneOutOfScopeRecipients">;
eventEmitter: TEventEmitter;
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find" | "create">;
loginService: Pick<TAuthLoginFactory, "processProviderCallback">;
emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
pamAccountDAL: Pick<TPamAccountDALFactory, "find">;
pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "update">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
};
export const samlConfigServiceFactory = ({
samlConfigDAL,
auditLogService,
orgDAL,
userDAL,
userAliasDAL,
groupDAL,
userGroupMembershipDAL,
projectDAL,
projectBotDAL,
projectKeyDAL,
alertChannelRecipientDAL,
eventEmitter,
additionalPrivilegeDAL,
permissionService,
licenseService,
tokenService,
smtpService,
identityMetadataDAL,
kmsService,
membershipDAL,
membershipRoleDAL,
membershipGroupDAL,
loginService,
emailDomainDAL,
telemetryService,
usageMeteringService,
keyStore,
pamAccountDAL,
pamSessionDAL,
gatewayV2Service
}: TSamlConfigServiceFactoryDep): TSamlConfigServiceFactory => {
const parseSamlGroups = (groupsValue: string): string[] => {
let samlGroups: string[] = [];
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const parsed = JSON.parse(groupsValue);
if (Array.isArray(parsed)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
samlGroups = parsed;
} else if (typeof parsed === "string") {
samlGroups = parsed
.split(",")
.map((g) => g.trim())
.filter(Boolean);
}
} catch {
samlGroups = groupsValue
.split(",")
.map((g) => g.trim())
.filter(Boolean);
}
return samlGroups;
};
const syncUserGroupMemberships = async ({
userId,
orgId,
samlGroups,
tx
}: {
userId: string;
orgId: string;
samlGroups: string[];
tx?: Knex;
}) => {
const pamCancellations: (() => void)[] = [];
const processGroupSync = async (transaction: Knex) => {
const currentGroupMemberships = await userGroupMembershipDAL.find(
{
userId
},
{ tx: transaction }
);
const orgGroups = await groupDAL.find({ orgId }, { tx: transaction });
const orgGroupsMap = new Map(orgGroups.map((g: TGroups) => [g.name, g]));
const orgGroupIds = new Set(orgGroups.map((g) => g.id));
const currentOrgGroupMemberships = currentGroupMemberships.filter((m) => orgGroupIds.has(m.groupId));
const currentGroupNames = new Set(
currentOrgGroupMemberships
.map((m) => {
const group = orgGroups.find((g) => g.id === m.groupId);
return group?.name;
})
.filter(Boolean)
);
const targetGroupNames = new Set(samlGroups);
const groupsToAdd = samlGroups.filter((groupName) => !currentGroupNames.has(groupName));
const groupsToRemove = Array.from(currentGroupNames).filter(
(groupName) => groupName && !targetGroupNames.has(groupName)
);
// eslint-disable-next-line no-await-in-loop
for (const groupName of groupsToAdd) {
if (!orgGroupsMap.has(groupName)) {
const newGroup = await groupDAL.create(
{
name: groupName,
slug: `${groupName.toLowerCase().replace(new RE2("[^a-z0-9]", "g"), "-")}-${Date.now()}`,
orgId
},
transaction
);
orgGroupsMap.set(groupName, newGroup);
const orgMembership = await membershipGroupDAL.create(
{
actorGroupId: newGroup.id,
scope: AccessScope.Organization,
scopeOrgId: orgId
},
transaction
);
await membershipRoleDAL.create(
{
membershipId: orgMembership.id,
role: OrgMembershipRole.NoAccess,
customRoleId: null
},
transaction
);
}
}
// eslint-disable-next-line no-await-in-loop
for (const groupName of groupsToAdd) {
const group = orgGroupsMap.get(groupName);
if (group) {
await addUsersToGroupByUserIds({
userIds: [userId],
group,
userDAL,
userGroupMembershipDAL,
orgDAL,
projectKeyDAL,
projectDAL,
projectBotDAL,
membershipGroupDAL,
usageMeteringService,
shouldFailOnMissingMembers: false,
tx: transaction
});
}
}
// eslint-disable-next-line no-await-in-loop
for (const groupName of groupsToRemove) {
if (groupName) {
const group = orgGroupsMap.get(groupName);
if (group) {
const { sendPamCancellations } = await removeUsersFromGroupByUserIds({
userIds: [userId],
group,
userDAL,
userGroupMembershipDAL,
membershipGroupDAL,
groupDAL,
projectKeyDAL,
additionalPrivilegeDAL,
usageMeteringService,
alertChannelRecipientDAL,
eventEmitter,
membershipDAL,
membershipRoleDAL,
pamAccountDAL,
pamSessionDAL,
gatewayV2Service,
shouldFailOnMissingMembers: false,
tx: transaction
});
pamCancellations.push(sendPamCancellations);
}
}
}
};
if (tx) {
await processGroupSync(tx);
} else {
await userDAL.transaction(processGroupSync);
}
return () => pamCancellations.forEach((send) => send());
};
const createSamlCfg: TSamlConfigServiceFactory["createSamlCfg"] = async ({
idpCert,
actor,
actorAuthMethod,
actorOrgId,
orgId,
issuer,
actorId,
isActive,
entryPoint,
authProvider,
enableGroupSync,
mfaSignalAttribute,
mfaAuthnContexts
}) => {
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.ParentOrganization,
actor,
actorId,
orgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Create, OrgPermissionSubjects.Sso);
const plan = await licenseService.getPlan(orgId);
if (!plan.samlSSO)
throw new BadRequestError({
message:
"Failed to create SAML SSO configuration due to plan restriction. Upgrade plan to create SSO configuration."
});
const org = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));
if (!org) {
throw new NotFoundError({ message: `Could not find organization with ID "${orgId}"` });
}
if (org.googleSsoAuthEnforced && isActive) {
throw new BadRequestError({
message:
"You cannot enable SAML SSO while Google OAuth is enforced. Disable Google OAuth enforcement to enable SAML SSO."
});
}
if (enableGroupSync && !GROUP_SYNC_SUPPORTED_PROVIDERS.includes(authProvider)) {
throw new BadRequestError({
message: "Group sync is not supported for this SAML provider."
});
}
if (enableGroupSync && !plan.groups) {
throw new BadRequestError({
message: "Failed to enable SAML group sync due to plan restriction. Upgrade plan to enable group sync."
});
}
const { encryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId
});
const samlConfig = await samlConfigDAL.create({
orgId,
authProvider,
isActive,
encryptedSamlCertificate: encryptor({ plainText: Buffer.from(idpCert) }).cipherTextBlob,
encryptedSamlEntryPoint: encryptor({ plainText: Buffer.from(entryPoint) }).cipherTextBlob,
encryptedSamlIssuer: encryptor({ plainText: Buffer.from(issuer) }).cipherTextBlob,
enableGroupSync: enableGroupSync || false,
mfaSignalAttribute,
mfaAuthnContexts
});
recordSsoConfigChangeMetric({ provider: SsoProvider.Saml, action: SsoConfigAction.Create, orgId });
return samlConfig;
};
const updateSamlCfg: TSamlConfigServiceFactory["updateSamlCfg"] = async ({
orgId,
actor,
actorOrgId,
actorAuthMethod,
idpCert,
actorId,
issuer,
isActive,
entryPoint,
authProvider,
enableGroupSync,
mfaSignalAttribute,
mfaAuthnContexts
}) => {
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.ParentOrganization,
actor,
actorId,
orgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Edit, OrgPermissionSubjects.Sso);
const plan = await licenseService.getPlan(orgId);
if (!plan.samlSSO)
throw new BadRequestError({
message:
"Failed to update SAML SSO configuration due to plan restriction. Upgrade plan to update SSO configuration."
});
const org = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));
if (!org) {
throw new NotFoundError({ message: `Could not find organization with ID "${orgId}"` });
}
if (org.googleSsoAuthEnforced && isActive) {
throw new BadRequestError({
message:
"Cannot enable SAML SSO while Google OAuth is enforced. Disable Google OAuth enforcement to enable SAML SSO."
});
}
if (enableGroupSync && authProvider && !GROUP_SYNC_SUPPORTED_PROVIDERS.includes(authProvider)) {
throw new BadRequestError({
message: "Group sync is not supported for this SAML provider."
});
}
if (enableGroupSync && !plan.groups) {
throw new BadRequestError({
message: "Failed to enable SAML group sync due to plan restriction. Upgrade plan to enable group sync."
});
}
const isMfaSignalOnlyUpdate = [authProvider, isActive, entryPoint, issuer, idpCert, enableGroupSync].every(
(value) => value === undefined
);
const updateQuery: TSamlConfigsUpdate = {
authProvider,
isActive,
...(!isMfaSignalOnlyUpdate && { lastUsed: null })
};
if (enableGroupSync !== undefined) {
updateQuery.enableGroupSync = enableGroupSync;
}
if (mfaSignalAttribute !== undefined) {
updateQuery.mfaSignalAttribute = mfaSignalAttribute;
}
if (mfaAuthnContexts !== undefined) {
updateQuery.mfaAuthnContexts = mfaAuthnContexts;
}
const { encryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId
});
if (entryPoint !== undefined) {
updateQuery.encryptedSamlEntryPoint = encryptor({ plainText: Buffer.from(entryPoint) }).cipherTextBlob;
}
if (issuer !== undefined) {
updateQuery.encryptedSamlIssuer = encryptor({ plainText: Buffer.from(issuer) }).cipherTextBlob;
}
if (idpCert !== undefined) {
updateQuery.encryptedSamlCertificate = encryptor({ plainText: Buffer.from(idpCert) }).cipherTextBlob;
}
const [ssoConfig] = await samlConfigDAL.update({ orgId }, updateQuery);
if (!isMfaSignalOnlyUpdate) {
await orgDAL.updateById(orgId, { authEnforced: false, scimEnabled: false });
}
recordSsoConfigChangeMetric({ provider: SsoProvider.Saml, action: SsoConfigAction.Update, orgId });
return ssoConfig;
};
const getSaml: TSamlConfigServiceFactory["getSaml"] = async (dto) => {
let samlConfig: TSamlConfigs | undefined;
if (dto.type === "org") {
samlConfig = await samlConfigDAL.findOne({ orgId: dto.orgId });
if (!samlConfig) {
throw new NotFoundError({
message: `SAML configuration for organization with ID '${dto.orgId}' not found`
});
}
} else if (dto.type === "domain") {
const verifiedDomain = await findOrgIdByVerifiedDomain({ domain: dto.domain, emailDomainDAL });
if (!verifiedDomain) {
throw new NotFoundError({ message: `No verified domain found for '${dto.domain}'` });
}
samlConfig = await samlConfigDAL.findOne({ orgId: verifiedDomain.orgId, isActive: true });
} else if (dto.type === "orgSlug") {
const org = await orgDAL.findOne({ slug: dto.orgSlug, rootOrgId: null });
if (!org) {
throw new NotFoundError({ message: `Organization with slug '${dto.orgSlug}' not found` });
}
samlConfig = await samlConfigDAL.findOne({ orgId: org.id, isActive: true });
} else if (dto.type === "ssoId") {
// TODO:
// We made this change because saml config ids were not moved over during the migration
// This will patch this issue.
// Remove in the future
const UUIDToMongoId: Record<string, string> = {
"64c81ff7905fadcfead01e9a": "0978bcbe-8f94-4d95-8600-009787262613",
"652d4777c74d008c85c8bed5": "42044bf5-119e-443e-a51b-0308ac7e45ea",
"6527df39771217236f8721f6": "6311ec4b-d692-4422-b52a-337f719ae6b0",
"650374a561d12cd3d835aeb8": "6453516c-930d-4ff0-ad3b-496ba6eb80ca",
"655d67d10a0f4d307c8b1536": "73b9f1b1-f946-4f18-9a2d-310f157f7df5",
"64f23239a5d4ed17f1e544c4": "9256337f-e3da-43d7-8266-39c9276e8426",
"65348e49db355e6e4782571f": "b8a227c7-843e-410e-8982-b4976a599b69",
"657a219fc8a80c2eff97eb38": "fcab1573-ae7f-4fcf-9645-646207acf035"
};
const id = UUIDToMongoId[dto.id] ?? dto.id;
samlConfig = await samlConfigDAL.findById(id);
}
if (!samlConfig) throw new NotFoundError({ message: `Failed to find SSO data` });
// when dto is type id means it's internally used
if (dto.type === "org") {
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.ParentOrganization,
actor: dto.actor,
actorId: dto.actorId,
orgId: samlConfig.orgId,
actorAuthMethod: dto.actorAuthMethod,
actorOrgId: dto.actorOrgId
});
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionSsoActions.Read, OrgPermissionSubjects.Sso);
}
const { decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: samlConfig.orgId
});
let entryPoint = "";
if (samlConfig.encryptedSamlEntryPoint) {
entryPoint = decryptor({ cipherTextBlob: samlConfig.encryptedSamlEntryPoint }).toString();
}
let issuer = "";
if (samlConfig.encryptedSamlIssuer) {
issuer = decryptor({ cipherTextBlob: samlConfig.encryptedSamlIssuer }).toString();
}
let cert = "";
if (samlConfig.encryptedSamlCertificate) {
cert = decryptor({ cipherTextBlob: samlConfig.encryptedSamlCertificate }).toString();
}
return {
id: samlConfig.id,
organization: samlConfig.orgId,
orgId: samlConfig.orgId,
authProvider: samlConfig.authProvider,
isActive: samlConfig.isActive,
entryPoint,
issuer,
cert,
lastUsed: samlConfig.lastUsed,
enableGroupSync: samlConfig.enableGroupSync,
mfaSignalAttribute: samlConfig.mfaSignalAttribute,
mfaAuthnContexts: samlConfig.mfaAuthnContexts
};
};
// Called with the assertion node-saml has already verified, before any login logic. The ID is claimed in
// Redis, which every instance shares, until the assertion expires, so a captured response cannot start a
// second session; that matters most when the org trusts the MFA it carries. This covers IdP-initiated logins
// too, which InResponseTo validation would not.
const consumeSamlAssertion: TSamlConfigServiceFactory["consumeSamlAssertion"] = async ({
samlConfigId,
parsedAssertion
}) => {
const { assertionId, issuedAt, expiresAt } = getSamlAssertionReplayDetails(parsedAssertion);
if (!assertionId) {
throw new BadRequestError({
message:
"The SAML response from your identity provider has no assertion ID, so Infisical cannot make sure it is used only once. Check the SAML app settings in your identity provider."
});
}
const replayWindow = getSamlAssertionReplayWindow({ expiresAt, issuedAt });
if (!replayWindow.accepted) {
throw new BadRequestError({
message:
replayWindow.reason === "expired"
? "This SAML response has expired. Sign in again through your identity provider."
: "The SAML response from your identity provider has no expiry (NotOnOrAfter) or issue time (IssueInstant), so Infisical cannot make sure it is used only once. Check the SAML app settings in your identity provider."
});
}
const assertionIdHash = crypto.nativeCrypto.createHash("sha256").update(assertionId).digest("hex");
const claimed = await keyStore.setItemWithExpiryNX(
KeyStorePrefixes.SamlAssertionReplay(samlConfigId, assertionIdHash),
replayWindow.ttlSeconds,
"1"
);
if (!claimed) {
logger.warn(
{ samlConfigId, assertionIdHash },
`Rejected a SAML assertion that was already used [samlConfigId=${samlConfigId}] [assertionIdHash=${assertionIdHash}]`
);
throw new BadRequestError({
message: "This SAML response was already used. Sign in again through your identity provider."
});
}
};
const samlLogin: TSamlConfigServiceFactory["samlLogin"] = async ({
externalId,
email,
firstName,
lastName,
authProvider,
orgId,
ip,
userAgent,
callbackPort,
metadata,
idpMfa
}) => {
const serverCfg = await getServerCfg();
if (serverCfg.enabledLoginMethods && !serverCfg.enabledLoginMethods.includes(LoginMethod.SAML)) {
throw new ForbiddenRequestError({
message: "Login with SAML is disabled by administrator."
});
}
let userAlias = await userAliasDAL.findOne({
externalId,
orgId,
aliasType: UserAliasType.SAML
});
const ownedDomain = await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
const organization = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));
if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
// The IdP is authoritative, and the separate email-verification step is skipped, only when the
// org enforces SSO and owns the asserted domain. Enforcement alone would promote an alias for
// any address the IdP asserts; ownership is what makes the assertion proof of the mailbox.
const isIdpAuthoritative = isIdpAuthoritativeForDomain({ isAuthEnforced: organization.authEnforced, ownedDomain });
const samlConfig = await samlConfigDAL.findOne({ orgId });
const groupsMetadata = metadata?.find(({ key }) => key === "groups");
const plan = await licenseService.getPlan(orgId);
const shouldSyncGroups = !!samlConfig?.enableGroupSync && !!plan.groups;
const identityLimit = getEnforcedIdentityLimit(plan);
let user: TUsers;
let sendPamCancellations = () => {};
if (userAlias) {
const foundUser = await userDAL.findById(userAlias.userId);
// Verify the existing user's stored email domain + cross-org check
await verifyEmailDomainOwnership({
email: foundUser.username,
orgId,
emailDomainDAL
});
// A stale, still-unverified alias may point at another user's account. Don't mutate that
// account's org membership / identity metadata / group state until the IdP proves control of
// it (the email-verification fallback below issues no session). This guard must run before the
// mutations, not just before ensureSsoAccountVerified at the end.
const isStaleAlias = isStaleSsoAlias({ user: foundUser, userAlias, assertedEmail: sanitizedEmail });
user = await userDAL.transaction(async (tx) => {
if (isStaleAlias) {
return foundUser;
}
const [orgMembership] = await orgDAL.findMembership(
{
[`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,
[`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
[`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
},
{ tx }
);
if (!orgMembership) {
const { role, roleId } = await getDefaultOrgMembershipRole(organization.defaultMembershipRole);
const membership = await orgDAL.createMembership(
{
actorUserId: userAlias.userId,
inviteEmail: sanitizedEmail,
scopeOrgId: orgId,
scope: AccessScope.Organization,
status: OrgMembershipStatus.Invited,
isActive: true
},
tx
);
await membershipRoleDAL.create(
{
membershipId: membership.id,
role,
customRoleId: roleId
},
tx
);
} else if (!orgMembership.isActive) {
throw new ForbiddenRequestError({ message: "User organization membership is inactive" });
}
if (metadata && foundUser.id) {
await identityMetadataDAL.delete({ userId: foundUser.id, orgId }, tx);
if (metadata.length) {
await identityMetadataDAL.insertMany(
metadata.map(({ key, value }) => ({
userId: foundUser.id,
orgId,
key,
value
})),
tx
);
}
}
if (shouldSyncGroups && metadata && foundUser.id) {
const samlGroups = groupsMetadata?.value ? parseSamlGroups(groupsMetadata.value) : [];
sendPamCancellations = await syncUserGroupMemberships({
userId: foundUser.id,
orgId,
samlGroups,
tx
});
}
return foundUser;
});
} else {
let isNewUser = false;
user = await userDAL.transaction(async (tx) => {
let newUser: TUsers | undefined;
newUser = await userDAL.findOne({ username: sanitizedEmail }, tx);
if (!newUser) {
newUser = await userDAL.create(
{
username: sanitizedEmail,
email: sanitizedEmail,
isEmailVerified: isIdpAuthoritative,
isAccepted: isIdpAuthoritative,
firstName,
lastName,
authMethods: [],
isGhost: false
},
tx
);
isNewUser = true;
} else if (!newUser.firstName && firstName) {
newUser = await userDAL.updateById(newUser.id, { firstName, ...(lastName ? { lastName } : {}) }, tx);
}
userAlias = await userAliasDAL.create(
{
userId: newUser.id,
aliasType: UserAliasType.SAML,
externalId,
emails: sanitizedEmail ? [sanitizedEmail] : [],
orgId,
isEmailVerified: isIdpAuthoritative
},
tx
);
const [orgMembership] = await orgDAL.findMembership(
{
[`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,
[`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
[`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
},
{ tx }
);
if (!orgMembership) {
await throwOnPlanSeatLimitReached({
licenseService,
orgId,
identityLimit,
tx,
aliasType: UserAliasType.SAML
});
const { role, roleId } = await getDefaultOrgMembershipRole(organization.defaultMembershipRole);
const membership = await orgDAL.createMembership(
{
actorUserId: newUser.id,
scopeOrgId: orgId,
scope: AccessScope.Organization,
status: OrgMembershipStatus.Invited,
isActive: true,
inviteEmail: sanitizedEmail
},
tx
);
await membershipRoleDAL.create(
{
membershipId: membership.id,
role,
customRoleId: roleId
},
tx
);
}
if (metadata && newUser.id) {
await identityMetadataDAL.delete({ userId: newUser.id, orgId }, tx);
if (metadata.length) {
await identityMetadataDAL.insertMany(
metadata.map(({ key, value }) => ({
userId: newUser?.id,
orgId,
key,
value
})),
tx
);
}
}
if (shouldSyncGroups && metadata && newUser.id) {
const samlGroups = groupsMetadata?.value ? parseSamlGroups(groupsMetadata.value) : [];
sendPamCancellations = await syncUserGroupMemberships({
userId: newUser.id,
orgId,
samlGroups,
tx
});
}
return newUser;
});
if (isNewUser) {
void telemetryService.sendPostHogEvents({
event: PostHogEventTypes.UserSignedUp,
distinctId: user.username ?? "",
organizationId: orgId,
properties: {
username: user.username,
email: user.email ?? "",
signupMethod: "saml"
}
});
}
}
sendPamCancellations();
await licenseService.updateSubscriptionOrgMemberCount(organization.id);
await samlConfigDAL.update({ orgId }, { lastUsed: new Date() });
// When the IdP is authoritative, mark the user + alias as verified/accepted before issuing a session.
if (isIdpAuthoritative) {
({ user, userAlias } = await ensureSsoAccountVerified({
user,
userAlias,
assertedEmail: sanitizedEmail,
userDAL,
userAliasDAL
}));
}
// The IdP is authoritative for identity in an org that enforces SSO, so a mailbox or name
// changed there is carried onto the account rather than left to go stale.
user = await syncSsoUserProfile({
user,
userAlias,
assertedEmail: sanitizedEmail,
assertedFirstName: firstName,
assertedLastName: lastName,
orgId,
isIdpAuthoritative,
userDAL,
userAliasDAL,
emailDomainDAL,
auditLogService
});
if (user.email && (!userAlias.isEmailVerified || !user.isAccepted)) {
const token = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_VERIFICATION,
userId: user.id,
aliasId: userAlias.id
});
await smtpService.sendMail({
template: SmtpTemplates.EmailVerification,
subjectLine: `Infisical confirmation code: ${token}`,
recipients: [user.email],
substitutions: {
code: token
}
});
}
const callbackResult = await loginService.processProviderCallback({
user,
authMethod: authProvider as AuthMethod,
isEmailVerified: Boolean(userAlias.isEmailVerified),
aliasId: userAlias.id,
ip,
userAgent,
organizationId: organization.id,
callbackPort,
idpMfa
});
return { ...callbackResult, userId: user.id, orgId: organization.id, orgName: organization.name };
};
return {
createSamlCfg,
updateSamlCfg,
getSaml,
samlLogin,
consumeSamlAssertion
};
};