Skip to content

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

bind SSO session to the root org that issued that

Thiago Araujo da Silva729ff7d90548
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index acec565eba..e5034b5b45 100644
--- a/backend/AGENTS.md
+++ b/backend/AGENTS.md
@@ -298,6 +298,22 @@ If you encounter `API_KEY` or `SERVICE_TOKEN` in existing code, do not replicate
Token detection logic in `inject-identity.ts` checks `x-api-key` header first, then parses `Authorization: Bearer` and inspects JWT `authTokenType` field to determine mode.
+#### SSO session binding
+
+A session minted by a SAML, OIDC or LDAP login carries `issuingRootOrgId`, the root org whose IdP
+issued it (`processProviderCallback` sets it; own-credential sessions never have it). An org that
+enforces SSO admits only sessions its own IdP issued: `validateOrgSSO` compares the claim with the
+org's root org on every user permission check, reading it from `userAuthInfo` in the request context
+(only when the check is for the requester), so it covers `selectOrganization`, OAuth consent, and a
+session that was already open when enforcement was turned on. Members who can bypass SSO are let
+through, and a token with no claim (issued before it existed) is taken at its auth method.
+
+**Every path that issues or re-issues a user token must carry the claim forward** (MFA, refresh,
+signup, org deletion, delegated OAuth codes and tokens). A dropped claim reads as a pre-claim token
+and passes every org's enforcement. `selectOrganization` audits the refusal
+(`SELECT_ORGANIZATION_REFUSED`) by catching the `FOREIGN_SSO_SESSION_ERROR_NAME` error
+`getOrgPermission` throws.
+
#### Delegated OAuth tokens
Two grants issue them: the authorization code flow (consented `scopes`) and the RFC 8693 token exchange
@@ -562,7 +578,8 @@ exists, and every audit entry written from then on records it. `syncSsoUserProfi
and is called from all three login services right after `ensureSsoAccountVerified`, outside the
caller's transaction, with its result flowing into the session.
-The gate is `organization.authEnforced` **and** a verified alias, and both halves matter. Enforcement
+The gate is `isIdpAuthoritative` (`isIdpAuthoritativeForDomain`: the org enforces SSO and owns the
+asserted domain) **and** a verified alias, and both halves matter. Enforcement on an owned domain
is the org saying the IdP is authoritative for identity, which is the same claim that already skips
email verification at signup. The verified alias is the proof that the IdP controls *this* account:
an unverified alias asserting an unrecognized email is exactly what `isStaleSsoAlias` exists to
diff --git a/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.ts b/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.ts
new file mode 100644
index 0000000000..a6fc32360e
--- /dev/null
+++ b/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.ts
@@ -0,0 +1,305 @@
+import crypto from "node:crypto";
+
+import { decode } from "jsonwebtoken";
+import { Knex } from "knex";
+
+import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { AuthMethod, ProviderAuthResult } from "@app/services/auth/auth-type";
+import { OauthGrantType } from "@app/services/oauth-client/oauth-client-types";
+
+import { loginUser, selectOrg } from "../../testUtils/auth";
+import { cleanupEmailDomains, seedVerifiedEmailDomain } from "../../testUtils/email-domains";
+
+const ORG_A_ID = seedData1.organization.id;
+const ORG_A_DOMAIN = "binding-org-a.local";
+const ORG_B_DOMAIN = "binding-org-b.local";
+const REDIRECT_URI = "https://app.example.com/callback";
+
+const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+const getServices = () => (globalThis as any).testServices;
+
+const decodeClaims = (token: string) => decode(token) as { authMethod?: string; issuingRootOrgId?: string };
+
+// An SSO session is bound to the root org whose IdP issued it: enforced orgs admit only sessions
+// their own IdP minted, while non-enforced orgs and the issuing org keep today's rules.
+describe("Auth SSO session binding", () => {
+ let orgBId: string;
+ const createdUserIds: string[] = [];
+ const createdClientIds: string[] = [];
+
+ const setAuthEnforced = (orgId: string, authEnforced: boolean) =>
+ getDb()(TableName.Organization).where({ id: orgId }).update({ authEnforced });
+
+ // Org B enforces SSO, so its IdP login skips mailbox verification and mints a session directly.
+ const loginThroughOrgBIdp = async () => {
+ const result = await getServices().saml.samlLogin({
+ externalId: `binding-${crypto.randomUUID()}`,
+ email: `member-${crypto.randomUUID()}@${ORG_B_DOMAIN}`,
+ firstName: "Bound",
+ lastName: "Session",
+ authProvider: AuthMethod.OKTA_SAML,
+ orgId: orgBId,
+ ip: "127.0.0.1",
+ userAgent: "test-agent"
+ });
+ createdUserIds.push(result.userId);
+ if (result.result !== ProviderAuthResult.SESSION) {
+ throw new Error(`Expected a session from the enforced org's IdP, got ${result.result}`);
+ }
+ return { userId: result.userId as string, tokens: result.tokens as { access: string; refresh: string } };
+ };
+
+ const addMemberToOrgA = async (userId: string) => {
+ const db = getDb();
+ const [membership] = await db(TableName.Membership)
+ .insert({
+ scope: AccessScope.Organization,
+ actorUserId: userId,
+ scopeOrgId: ORG_A_ID,
+ status: OrgMembershipStatus.Accepted,
+ isActive: true
+ })
+ .returning("*");
+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Member });
+ };
+
+ beforeAll(async () => {
+ const db = getDb();
+ await seedVerifiedEmailDomain(ORG_A_ID, ORG_A_DOMAIN, db);
+
+ const [orgB] = await db(TableName.Organization)
+ .insert({ name: "Session Binding Org B", slug: `binding-org-b-${crypto.randomUUID().slice(0, 8)}` })
+ .returning("*");
+ orgBId = orgB.id;
+ await seedVerifiedEmailDomain(orgBId, ORG_B_DOMAIN, db);
+ await setAuthEnforced(orgBId, true);
+ });
+
+ afterEach(async () => {
+ await setAuthEnforced(ORG_A_ID, false);
+ await Promise.all(
+ createdClientIds.splice(0).map((id) =>
+ testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/oauth/clients/${id}`,
+ headers: { authorization: `Bearer ${jwtAuthToken}` }
+ })
+ )
+ );
+ });
+
+ afterAll(async () => {
+ const db = getDb();
+ if (createdUserIds.length > 0) {
+ await db(TableName.UserAliases).whereIn("userId", createdUserIds).del();
+ await db(TableName.Membership).whereIn("actorUserId", createdUserIds).del();
+ await db(TableName.Users).whereIn("id", createdUserIds).where("id", "!=", seedData1.id).del();
+ }
+ await cleanupEmailDomains(ORG_A_ID, db);
+ await cleanupEmailDomains(orgBId, db);
+ await db(TableName.Organization).where({ id: orgBId }).del();
+ });
+
+ test("An IdP login stamps the issuing root org on the pre-organization session", async () => {
+ const { tokens } = await loginThroughOrgBIdp();
+
+ expect(decodeClaims(tokens.access)).toMatchObject({
+ authMethod: AuthMethod.OKTA_SAML,
+ issuingRootOrgId: orgBId
+ });
+ expect(decodeClaims(tokens.refresh).issuingRootOrgId).toBe(orgBId);
+ });
+
+ test("A password login carries no issuing org", async () => {
+ const { accessToken } = await loginUser(seedData1.email, seedData1.password);
+
+ expect(decodeClaims(accessToken).issuingRootOrgId).toBeUndefined();
+ });
+
+ test("The issuing org admits its own IdP session and keeps the claim on the org-scoped token", async () => {
+ const { tokens } = await loginThroughOrgBIdp();
+
+ const { statusCode, payload } = await selectOrg(tokens.access, orgBId);
+
+ expect(statusCode).toBe(200);
+ expect(decodeClaims(payload.token)).toMatchObject({ organizationId: orgBId, issuingRootOrgId: orgBId });
+ });
+
+ test("Another org that enforces SSO refuses a session its IdP did not issue", async () => {
+ const { userId, tokens } = await loginThroughOrgBIdp();
+ await addMemberToOrgA(userId);
+ await setAuthEnforced(ORG_A_ID, true);
+
+ const { statusCode, payload } = await selectOrg(tokens.access, ORG_A_ID);
+
+ expect(statusCode).toBe(403);
+ expect(payload.message).toMatch(/another organization's identity provider/);
+ });
+
+ test("A session another org's IdP issued stops working once the org starts enforcing SSO", async () => {
+ const { userId, tokens } = await loginThroughOrgBIdp();
+ await addMemberToOrgA(userId);
+ const { payload: selected } = await selectOrg(tokens.access, ORG_A_ID);
+ const listMemberships = () =>
+ testServer.inject({
+ method: "GET",
+ url: `/api/v2/organizations/${ORG_A_ID}/memberships`,
+ headers: { authorization: `Bearer ${selected.token}` }
+ });
+ expect((await listMemberships()).statusCode).toBe(200);
+
+ await setAuthEnforced(ORG_A_ID, true);
+ const refused = await listMemberships();
+
+ expect(refused.statusCode).toBe(403);
+ expect(refused.json().message).toMatch(/another organization's identity provider/);
+ });
+
+ test("An enforced org's OAuth application refuses consent from a session another org's IdP issued", async () => {
+ const created = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/oauth/clients",
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: {
+ name: `binding-consent-${crypto.randomUUID()}`,
+ grantTypes: [OauthGrantType.AuthorizationCode],
+ redirectUris: [REDIRECT_URI]
+ }
+ });
+ expect(created.statusCode).toBe(200);
+ const { client } = created.json<{ client: { id: string; clientId: string } }>();
+ createdClientIds.push(client.id);
+
+ const { userId, tokens } = await loginThroughOrgBIdp();
+ await addMemberToOrgA(userId);
+ await setAuthEnforced(ORG_A_ID, true);
+ // Consent needs an org-scoped session; this one is scoped to the org whose IdP issued it.
+ const { payload: selected } = await selectOrg(tokens.access, orgBId);
+
+ const consented = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/oauth/authorize/consent",
+ headers: { authorization: `Bearer ${selected.token}` },
+ body: { client_id: client.clientId, redirect_uri: REDIRECT_URI }
+ });
+
+ expect(consented.statusCode).toBe(403);
+ expect(consented.json().message).toMatch(/another organization's identity provider/);
+ });
+
+ test("Delegated OAuth tokens carry the issuing org", async () => {
+ const created = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/oauth/clients",
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: {
+ name: `binding-delegated-${crypto.randomUUID()}`,
+ grantTypes: [OauthGrantType.AuthorizationCode, OauthGrantType.RefreshToken],
+ redirectUris: [REDIRECT_URI]
+ }
+ });
+ expect(created.statusCode).toBe(200);
+ const { client, clientSecret } = created.json<{
+ client: { id: string; clientId: string };
+ clientSecret: string;
+ }>();
+ createdClientIds.push(client.id);
+
+ const { userId, tokens } = await loginThroughOrgBIdp();
+ await addMemberToOrgA(userId);
+ const { payload: selected } = await selectOrg(tokens.access, ORG_A_ID);
+
+ const consented = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/oauth/authorize/consent",
+ headers: { authorization: `Bearer ${selected.token}` },
+ body: { client_id: client.clientId, redirect_uri: REDIRECT_URI }
+ });
+ expect(consented.statusCode).toBe(200);
+ const code = new URL(consented.json<{ callbackUrl: string }>().callbackUrl).searchParams.get("code");
+
+ const issued = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/oauth/token",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ payload: new URLSearchParams({
+ grant_type: OauthGrantType.AuthorizationCode,
+ code: code as string,
+ redirect_uri: REDIRECT_URI,
+ client_id: client.clientId,
+ client_secret: clientSecret
+ }).toString()
+ });
+ expect(issued.statusCode).toBe(200);
+ const { access_token: accessToken, refresh_token: refreshToken } = issued.json<{
+ access_token: string;
+ refresh_token: string;
+ }>();
+ expect(decodeClaims(accessToken).issuingRootOrgId).toBe(orgBId);
+ expect(decodeClaims(refreshToken).issuingRootOrgId).toBe(orgBId);
+ });
+
+ test("Another org that does not enforce SSO admits the session as today", async () => {
+ const { userId, tokens } = await loginThroughOrgBIdp();
+ await addMemberToOrgA(userId);
+
+ const { statusCode, payload } = await selectOrg(tokens.access, ORG_A_ID);
+
+ expect(statusCode).toBe(200);
+ expect(decodeClaims(payload.token)).toMatchObject({ organizationId: ORG_A_ID, issuingRootOrgId: orgBId });
+ });
+
+ test("A password session is still refused at an enforced org as today", async () => {
+ const { accessToken } = await loginUser(seedData1.email, seedData1.password);
+ await setAuthEnforced(ORG_A_ID, true);
+
+ const { statusCode, payload } = await selectOrg(accessToken, ORG_A_ID);
+
+ expect(statusCode).toBe(403);
+ expect(payload.message).toMatch(/Login with SAML SSO/);
+ });
+
+ test("Deleting an organization re-issues tokens that keep the issuing org", async () => {
+ const { tokens } = await loginThroughOrgBIdp();
+
+ const createRes = await testServer.inject({
+ method: "POST",
+ url: "/api/v2/organizations",
+ headers: { authorization: `Bearer ${tokens.access}` },
+ body: { name: `binding-throwaway-${crypto.randomUUID().slice(0, 8)}` }
+ });
+ expect(createRes.statusCode).toBe(200);
+ const throwawayOrgId = createRes.json().organization.id as string;
+
+ const { payload: selected } = await selectOrg(tokens.access, throwawayOrgId);
+ const deleteRes = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/organizations/${throwawayOrgId}`,
+ headers: { authorization: `Bearer ${selected.token}`, "user-agent": "test-agent" }
+ });
+
+ expect(deleteRes.statusCode).toBe(200);
+ expect(decodeClaims(deleteRes.json().accessToken)).toMatchObject({
+ authMethod: AuthMethod.OKTA_SAML,
+ issuingRootOrgId: orgBId
+ });
+ });
+
+ test("Token refresh carries the issuing org forward", async () => {
+ const { tokens } = await loginThroughOrgBIdp();
+
+ const res = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/auth/token",
+ cookies: { jid: tokens.refresh }
+ });
+
+ expect(res.statusCode).toBe(200);
+ const payload = res.json() as { token: string; refreshToken?: string };
+ expect(decodeClaims(payload.token).issuingRootOrgId).toBe(orgBId);
+ expect(payload.refreshToken).toBeDefined();
+ expect(decodeClaims(payload.refreshToken as string).issuingRootOrgId).toBe(orgBId);
+ });
+});
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 09e0b78215..20e0b48d65 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -223,6 +223,7 @@ declare module "@fastify/request-context" {
userAuthInfo?: {
userId: string;
email: string;
+ issuingRootOrgId?: string;
};
projectDetails?: {
id: string;
diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts
index 9135d53b9d..e82de2c683 100644
--- a/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts
+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts
@@ -61,6 +61,7 @@ describe("audit log event classes", () => {
[EventType.USER_LOGIN, AuditLogEventClass.Authentication],
[EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH_FAILED, AuditLogEventClass.Authentication],
[EventType.SELECT_ORGANIZATION, AuditLogEventClass.Authentication],
+ [EventType.SELECT_ORGANIZATION_REFUSED, AuditLogEventClass.Authentication],
[EventType.GATEWAY_CONNECT, AuditLogEventClass.Authentication],
[EventType.PERMISSION_DENIED, AuditLogEventClass.Authorization]
])("classifies %s as %s", (eventType, expected) => {
diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.ts
index 3f2b2512c7..353093234c 100644
--- a/backend/src/ee/services/audit-log/audit-log-event-classes.ts
+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.ts
@@ -64,6 +64,7 @@ const AUTHENTICATION_EVENT_TYPES: readonly EventType[] = [
EventType.ORG_ADMIN_BYPASS_SSO,
EventType.USER_LOGIN,
EventType.SELECT_ORGANIZATION,
+ EventType.SELECT_ORGANIZATION_REFUSED,
EventType.SELECT_SUB_ORGANIZATION,
EventType.KMIP_SERVER_CONNECT,
EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index a1c097bffb..7461aaa08a 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -488,6 +488,7 @@ export enum EventType {
ORG_ADMIN_BYPASS_SSO = "org-admin-bypassed-sso",
USER_LOGIN = "user-login",
SELECT_ORGANIZATION = "select-organization",
+ SELECT_ORGANIZATION_REFUSED = "select-organization-refused",
SELECT_SUB_ORGANIZATION = "select-sub-organization",
CREATE_CERTIFICATE_POLICY = "create-certificate-policy",
UPDATE_CERTIFICATE_POLICY = "update-certificate-policy",
@@ -3753,6 +3754,16 @@ interface SelectOrganizationEvent {
};
}
+// The session was issued by another root org's IdP, which does not satisfy this org's enforcement.
+interface SelectOrganizationRefusedEvent {
+ type: EventType.SELECT_ORGANIZATION_REFUSED;
+ metadata: {
+ organizationId: string;
+ organizationName: string;
+ issuingOrganizationId: string;
+ };
+}
+
interface SelectSubOrganizationEvent {
type: EventType.SELECT_SUB_ORGANIZATION;
metadata: {
@@ -9036,6 +9047,7 @@ export type Event =
| CertificateIssuanceFailedEvent
| UserLoginEvent
| SelectOrganizationEvent
+ | SelectOrganizationRefusedEvent
| SelectSubOrganizationEvent
| ApprovalPolicyCreateEvent
| ApprovalPolicyUpdateEvent
diff --git a/backend/src/ee/services/email-domain/email-domain-fns.test.ts b/backend/src/ee/services/email-domain/email-domain-fns.test.ts
new file mode 100644
index 0000000000..8fafc4f838
--- /dev/null
+++ b/backend/src/ee/services/email-domain/email-domain-fns.test.ts
@@ -0,0 +1,70 @@
+import { BadRequestError } from "@app/lib/errors";
+
+import { isIdpAuthoritativeForDomain, verifyEmailDomainOwnership } from "./email-domain-fns";
+import { EmailDomainStatus } from "./email-domain-types";
+
+const ownedDomain = { id: "domain-1", orgId: "org-1", domain: "acme.com", status: EmailDomainStatus.Verified };
+
+const makeEmailDomainDAL = (records: { orgId: string; domain: string }[]) => ({
+ findOne: vi
+ .fn()
+ .mockImplementation(({ domain, orgId }: { domain: string; orgId: string }) =>
+ records.find((record) => record.domain === domain && record.orgId === orgId)
+ )
+});
+
+describe("verifyEmailDomainOwnership", () => {
+ test("returns the verified domain record when the org owns the domain", async () => {
+ const emailDomainDAL = makeEmailDomainDAL([ownedDomain]);
+
+ await expect(
+ verifyEmailDomainOwnership({ email: "[email protected]", orgId: "org-1", emailDomainDAL })
+ ).resolves.toEqual(ownedDomain);
+ expect(emailDomainDAL.findOne).toHaveBeenCalledWith({
+ domain: "acme.com",
+ status: EmailDomainStatus.Verified,
+ orgId: "org-1"
+ });
+ });
+
+ test("refuses an address on a domain the org has not verified", async () => {
+ const emailDomainDAL = makeEmailDomainDAL([ownedDomain]);
+
+ await expect(
+ verifyEmailDomainOwnership({ email: "[email protected]", orgId: "org-1", emailDomainDAL })
+ ).rejects.toBeInstanceOf(BadRequestError);
+ });
+
+ test("refuses an address on a domain another org verified", async () => {
+ const emailDomainDAL = makeEmailDomainDAL([ownedDomain]);
+
+ await expect(
+ verifyEmailDomainOwnership({ email: "[email protected]", orgId: "org-2", emailDomainDAL })
+ ).rejects.toBeInstanceOf(BadRequestError);
+ });
+
+ test("refuses an address with no domain part", async () => {
+ const emailDomainDAL = makeEmailDomainDAL([ownedDomain]);
+
+ await expect(verifyEmailDomainOwnership({ email: "jane", orgId: "org-1", emailDomainDAL })).rejects.toBeInstanceOf(
+ BadRequestError
+ );
+ expect(emailDomainDAL.findOne).not.toHaveBeenCalled();
+ });
+});
+
+describe("isIdpAuthoritativeForDomain", () => {
+ test("is authoritative only when the org enforces SSO and owns the domain", () => {
+ expect(isIdpAuthoritativeForDomain({ isAuthEnforced: true, ownedDomain })).toBe(true);
+ });
+
+ test.each([
+ ["enforcement without the domain", { isAuthEnforced: true, ownedDomain: undefined }],
+ ["enforcement with a null domain", { isAuthEnforced: true, ownedDomain: null }],
+ ["the domain without enforcement", { isAuthEnforced: false, ownedDomain }],
+ ["the domain with enforcement unset", { isAuthEnforced: null, ownedDomain }],
+ ["neither", { isAuthEnforced: false, ownedDomain: undefined }]
+ ] as const)("is not authoritative with %s", (_label, input) => {
+ expect(isIdpAuthoritativeForDomain(input)).toBe(false);
+ });
+});
diff --git a/backend/src/ee/services/email-domain/email-domain-fns.ts b/backend/src/ee/services/email-domain/email-domain-fns.ts
index 2a7df87c2e..d281a1e9bb 100644
--- a/backend/src/ee/services/email-domain/email-domain-fns.ts
+++ b/backend/src/ee/services/email-domain/email-domain-fns.ts
@@ -1,12 +1,12 @@
-// import { AccessScope, TableName } from "@app/db/schemas";
+import { TEmailDomains } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { TEmailDomainDALFactory } from "./email-domain-dal";
import { EmailDomainStatus } from "./email-domain-types";
/**
- * Given an email and orgId, verifies the org is allowed to manage a user with this email.
- *
+ * Given an email and orgId, verifies the org is allowed to manage a user with this email and
+ * returns the verified domain record.
*/
export const verifyEmailDomainOwnership = async ({
email,
@@ -16,7 +16,7 @@ export const verifyEmailDomainOwnership = async ({
email: string;
orgId: string;
emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;
-}) => {
+}): Promise<TEmailDomains> => {
const emailDomain = email.split("@")?.[1];
if (!emailDomain) throw new BadRequestError({ message: "Invalid email address" });
@@ -32,8 +32,23 @@ export const verifyEmailDomainOwnership = async ({
"The email you attempted to login in with is not a part of the accepted domains of the selected organization. Please consult with your organization admin for further assistance."
});
}
+
+ return verifiedDomain;
};
+/**
+ * Whether an org may treat its IdP's assertion as proof of the user's mailbox. Only the org that
+ * verified the domain may: SSO enforcement on its own is the org vouching for an address it does
+ * not necessarily own, so it never counts without the domain.
+ */
+export const isIdpAuthoritativeForDomain = ({
+ isAuthEnforced,
+ ownedDomain
+}: {
+ isAuthEnforced?: boolean | null;
+ ownedDomain?: Pick<TEmailDomains, "id"> | null;
+}) => Boolean(isAuthEnforced) && Boolean(ownedDomain);
+
/**
* Given a domain string, finds the verified email domain record
* and returns its orgId. Returns undefined if no verified record exists.
diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.ts
index e96fce6336..5070a2585b 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -57,7 +57,7 @@ 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 { verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
+import { isIdpAuthoritativeForDomain, verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
@@ -503,7 +503,7 @@ export const ldapConfigServiceFactory = ({
});
}
- await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
+ const ownedDomain = await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
@@ -516,7 +516,11 @@ export const ldapConfigServiceFactory = ({
const organization = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));
if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
- const skipEmailVerification = Boolean(organization.authEnforced) || Boolean(serverCfg.trustLdapEmails);
+ // The IdP is authoritative only when the org enforces SSO and owns the asserted domain. The
+ // instance-level trustLdapEmails flag is a server admin's own decision to skip verification and
+ // is kept apart from it.
+ const isIdpAuthoritative = isIdpAuthoritativeForDomain({ isAuthEnforced: organization.authEnforced, ownedDomain });
+ const skipEmailVerification = isIdpAuthoritative || Boolean(serverCfg.trustLdapEmails);
// A stale, still-unverified alias may point at another user's account. Don't mutate that
// account's org membership / group state until the IdP proves control of it (the
@@ -775,7 +779,7 @@ export const ldapConfigServiceFactory = ({
assertedFirstName: firstName,
assertedLastName: lastName,
orgId,
- isAuthEnforced: Boolean(organization.authEnforced),
+ isIdpAuthoritative,
userDAL,
userAliasDAL,
emailDomainDAL,
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 9fb17cae91..0dbd1ecc0a 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -69,7 +69,11 @@ 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, verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
+import {
+ findOrgIdByVerifiedDomain,
+ isIdpAuthoritativeForDomain,
+ verifyEmailDomainOwnership
+} from "../email-domain/email-domain-fns";
import { TOidcConfigDALFactory } from "./oidc-config-dal";
import { resolveOidcGroupMembershipChanges } from "./oidc-config-fns";
import {
@@ -239,7 +243,7 @@ export const oidcConfigServiceFactory = ({
});
}
- await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
+ const ownedDomain = await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
@@ -252,10 +256,10 @@ export const oidcConfigServiceFactory = ({
const organization = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));
if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
- // When the org enforces SSO, the verified domain + IdP are authoritative, so we skip the
- // separate email-verification step (the email-domain ownership check above already proves the
- // org owns this domain, and password signup is blocked for enforced domains).
- const skipEmailVerification = Boolean(organization.authEnforced);
+ // 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 });
let user: TUsers;
// A stale, still-unverified alias may point at another user's account. Don't mutate that
@@ -356,8 +360,8 @@ export const oidcConfigServiceFactory = ({
lastName,
authMethods: [],
isGhost: false,
- isEmailVerified: skipEmailVerification,
- isAccepted: skipEmailVerification
+ isEmailVerified: isIdpAuthoritative,
+ isAccepted: isIdpAuthoritative
},
tx
);
@@ -373,7 +377,7 @@ export const oidcConfigServiceFactory = ({
externalId,
emails: sanitizedEmail ? [sanitizedEmail] : [],
orgId,
- isEmailVerified: skipEmailVerification
+ isEmailVerified: isIdpAuthoritative
},
tx
);
@@ -544,8 +548,8 @@ export const oidcConfigServiceFactory = ({
await oidcConfigDAL.update({ orgId }, { lastUsed: new Date() });
- // When SSO is enforced, mark the user + alias as verified/accepted before issuing a session.
- if (skipEmailVerification) {
+ // When the IdP is authoritative, mark the user + alias as verified/accepted before issuing a session.
+ if (isIdpAuthoritative) {
({ user, userAlias } = await ensureSsoAccountVerified({
user,
userAlias,
@@ -564,7 +568,7 @@ export const oidcConfigServiceFactory = ({
assertedFirstName: firstName,
assertedLastName: lastName,
orgId,
- isAuthEnforced: Boolean(organization.authEnforced),
+ isIdpAuthoritative,
userDAL,
userAliasDAL,
emailDomainDAL,
diff --git a/backend/src/ee/services/permission/permission-fns.test.ts b/backend/src/ee/services/permission/permission-fns.test.ts
index 842b5898a4..f54706dfff 100644
--- a/backend/src/ee/services/permission/permission-fns.test.ts
+++ b/backend/src/ee/services/permission/permission-fns.test.ts
@@ -2,15 +2,18 @@ import { createMongoAbility, ForbiddenError, MongoAbility, RawRuleOf, subject }
import { describe, expect, test } from "vitest";
import { conditionsMatcher } from "@app/lib/casl";
-import { ActorType } from "@app/services/auth/auth-type";
+import { ForbiddenRequestError } from "@app/lib/errors";
+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import {
checkForInvalidPermissionCombination,
expandLegacyForbidActions,
+ FOREIGN_SSO_SESSION_ERROR_NAME,
getProjectPermissionFingerprint,
handlebarsClient,
interpolatePermissionRules,
- throwIfMissingSecretReadValueOrDescribePermission
+ throwIfMissingSecretReadValueOrDescribePermission,
+ validateOrgSSO
} from "./permission-fns";
import {
ProjectPermissionActions,
@@ -455,3 +458,69 @@ describe("checkForInvalidPermissionCombination", () => {
).not.toThrow();
});
});
+
+describe("validateOrgSSO session binding", () => {
+ const enforcedOrg = {
+ isOrgSsoEnforced: true,
+ isOrgGoogleSsoEnforced: false,
+ isOrgSsoBypassEnabled: false,
+ isAdmin: false,
+ rootOrgId: "org-a"
+ };
+
+ const refusal = (fn: () => void) => {
+ try {
+ fn();
+ } catch (error) {
+ return error;
+ }
+ return undefined;
+ };
+
+ test("admits an SSO session the org's own IdP issued", () => {
+ expect(() =>
+ validateOrgSSO({ ...enforcedOrg, actorAuthMethod: AuthMethod.OKTA_SAML, issuingRootOrgId: "org-a" })
+ ).not.toThrow();
+ });
+
+ test.each([AuthMethod.OKTA_SAML, AuthMethod.OIDC] as const)(
+ "refuses a %s session another org's IdP issued",
+ (actorAuthMethod) => {
+ const error = refusal(() => validateOrgSSO({ ...enforcedOrg, actorAuthMethod, issuingRootOrgId: "org-b" }));
+
+ expect(error).toBeInstanceOf(ForbiddenRequestError);
+ expect((error as ForbiddenRequestError).name).toBe(FOREIGN_SSO_SESSION_ERROR_NAME);
+ }
+ );
+
+ test("takes a token issued before the claim existed at its method", () => {
+ expect(() => validateOrgSSO({ ...enforcedOrg, actorAuthMethod: AuthMethod.OKTA_SAML })).not.toThrow();
+ });
+
+ test("admits a foreign session where the org does not enforce SSO", () => {
+ expect(() =>
+ validateOrgSSO({
+ ...enforcedOrg,
+ isOrgSsoEnforced: false,
+ actorAuthMethod: AuthMethod.OKTA_SAML,
+ issuingRootOrgId: "org-b"
+ })
+ ).not.toThrow();
+ });
+
+ test("lets a member who may bypass SSO through with a foreign session", () => {
+ expect(() =>
+ validateOrgSSO({
+ ...enforcedOrg,
+ isOrgSsoBypassEnabled: true,
+ isAdmin: true,
+ actorAuthMethod: AuthMethod.OKTA_SAML,
+ issuingRootOrgId: "org-b"
+ })
+ ).not.toThrow();
+ });
+
+ test("skips the check for a call made without an auth method", () => {
+ expect(() => validateOrgSSO({ ...enforcedOrg, actorAuthMethod: null, issuingRootOrgId: "org-b" })).not.toThrow();
+ });
+});
diff --git a/backend/src/ee/services/permission/permission-fns.ts b/backend/src/ee/services/permission/permission-fns.ts
index 9d070c160e..d5e94e16ae 100644
--- a/backend/src/ee/services/permission/permission-fns.ts
+++ b/backend/src/ee/services/permission/permission-fns.ts
@@ -265,13 +265,27 @@ function isAuthMethodSaml(actorAuthMethod: ActorAuthMethod) {
].includes(actorAuthMethod);
}
-function validateOrgSSO(
- actorAuthMethod: ActorAuthMethod,
- isOrgSsoEnforced: TOrganizations["authEnforced"],
- isOrgGoogleSsoEnforced: TOrganizations["googleSsoAuthEnforced"],
- isOrgSsoBypassEnabled: TOrganizations["bypassOrgAuthEnabled"],
- isAdmin: boolean
-) {
+export const FOREIGN_SSO_SESSION_ERROR_NAME = "ForeignSsoSession";
+
+function validateOrgSSO({
+ actorAuthMethod,
+ isOrgSsoEnforced,
+ isOrgGoogleSsoEnforced,
+ isOrgSsoBypassEnabled,
+ isAdmin,
+ issuingRootOrgId,
+ rootOrgId
+}: {
+ actorAuthMethod: ActorAuthMethod;
+ isOrgSsoEnforced: TOrganizations["authEnforced"];
+ isOrgGoogleSsoEnforced: TOrganizations["googleSsoAuthEnforced"];
+ isOrgSsoBypassEnabled: TOrganizations["bypassOrgAuthEnabled"];
+ isAdmin: boolean;
+ // Root org whose IdP issued the session, when the session is the request's own; tokens issued
+ // before the claim existed carry none and are taken at their auth method.
+ issuingRootOrgId?: string;
+ rootOrgId: string;
+}) {
if (actorAuthMethod === undefined) {
throw new UnauthorizedError({ name: "No auth method defined" });
}
@@ -300,6 +314,16 @@ function validateOrgSSO(
"Organization authentication is enforced. Cannot access org-scoped resource. Login with SAML SSO to access this resource."
});
}
+
+ // A session another org's IdP minted would otherwise satisfy this org's enforcement without its
+ // IdP, MFA or deprovisioning ever seeing the login.
+ if (isOrgSsoEnforced && actorAuthMethod !== null && issuingRootOrgId && issuingRootOrgId !== rootOrgId) {
+ throw new ForbiddenRequestError({
+ name: FOREIGN_SSO_SESSION_ERROR_NAME,
+ message:
+ "This organization requires its own SSO. Your session was issued by another organization's identity provider; log in again through this organization's SSO."
+ });
+ }
}
const escapeHandlebarsMissingDict = (obj: Record<string, string>, key: string) => {
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index 33587ef9e4..48eef05625 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -114,6 +114,13 @@ const getDelegatedOauthScopes = (): OauthScope[] | undefined => {
return raw.filter(isValidOauthScope);
};
+// The issuing org belongs to the request's own session, so it only applies when the permission
+// being resolved is the requester's; a check made on another user's behalf has no session of its own.
+const getSessionIssuingRootOrgId = (actorId: string) => {
+ const userAuthInfo = requestContext.get(RequestContextKey.UserAuthInfo);
+ return userAuthInfo?.userId === actorId ? userAuthInfo.issuingRootOrgId : undefined;
+};
+
const buildOrgPermissionRules = (orgUserRoles: TBuildOrgPermissionDTO) => {
const rules = orgUserRoles
.map(({ role, permissions }) => {
@@ -448,13 +455,15 @@ export const permissionServiceFactory = ({
// SSO enforcement applies only to users. Evaluate it against the full ability — SSO bypass is a
// property of the user's roles, not of what an OAuth client was delegated.
if (actor === ActorType.USER) {
- validateOrgSSO(
+ validateOrgSSO({
actorAuthMethod,
- permissionData?.[0].orgAuthEnforced,
- Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),
- Boolean(permissionData?.[0].bypassOrgAuthEnabled),
- canBypassSso
- );
+ isOrgSsoEnforced: permissionData?.[0].orgAuthEnforced,
+ isOrgGoogleSsoEnforced: Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),
+ isOrgSsoBypassEnabled: Boolean(permissionData?.[0].bypassOrgAuthEnabled),
+ isAdmin: canBypassSso,
+ issuingRootOrgId: getSessionIssuingRootOrgId(actorId),
+ rootOrgId: rootOrgId ?? orgId
+ });
}
// Delegated OAuth tokens get a scope-narrowed ability; first-party sessions get the full one.
@@ -787,13 +796,15 @@ export const permissionServiceFactory = ({
// SSO enforcement runs on every request (uses per-request actorAuthMethod, not cached)
if (actor === ActorType.USER) {
- validateOrgSSO(
+ validateOrgSSO({
actorAuthMethod,
- permissionData?.[0].orgAuthEnforced,
- Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),
- Boolean(permissionData?.[0].bypassOrgAuthEnabled),
- canBypassSso
- );
+ isOrgSsoEnforced: permissionData?.[0].orgAuthEnforced,
+ isOrgGoogleSsoEnforced: Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),
+ isOrgSsoBypassEnabled: Boolean(permissionData?.[0].bypassOrgAuthEnabled),
+ isAdmin: canBypassSso,
+ issuingRootOrgId: getSessionIssuingRootOrgId(actorId),
+ rootOrgId: permissionData?.[0].rootOrgId ?? projectDetails.orgId
+ });
}
const rules = buildProjectPermissionRules(permissionFromRoles, projectDetails.type, folderScopedPrivileges);
diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.ts
index 8045aec1fb..40b1324a66 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -50,7 +50,11 @@ 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, verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";
+import {
+ findOrgIdByVerifiedDomain,
+ isIdpAuthoritativeForDomain,
+ verifyEmailDomainOwnership
+} from "../email-domain/email-domain-fns";
import { TGroupDALFactory } from "../group/group-dal";
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "../group/group-fns";
import { TUserGroupMembershipDALFactory } from "../group/user-group-membership-dal";
@@ -565,17 +569,17 @@ export const samlConfigServiceFactory = ({
aliasType: UserAliasType.SAML
});
- await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL });
+ 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` });
- // When the org enforces SSO, the verified domain + IdP are authoritative, so we skip the
- // separate email-verification step (the email-domain ownership check above already proves the
- // org owns this domain, and password signup is blocked for enforced domains).
- const skipEmailVerification = Boolean(organization.authEnforced);
+ // 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");
@@ -678,8 +682,8 @@ export const samlConfigServiceFactory = ({
{
username: sanitizedEmail,
email: sanitizedEmail,
- isEmailVerified: skipEmailVerification,
- isAccepted: skipEmailVerification,
+ isEmailVerified: isIdpAuthoritative,
+ isAccepted: isIdpAuthoritative,
firstName,
lastName,
authMethods: [],
@@ -699,7 +703,7 @@ export const samlConfigServiceFactory = ({
externalId,
emails: sanitizedEmail ? [sanitizedEmail] : [],
orgId,
- isEmailVerified: skipEmailVerification
+ isEmailVerified: isIdpAuthoritative
},
tx
);
@@ -791,8 +795,8 @@ export const samlConfigServiceFactory = ({
await samlConfigDAL.update({ orgId }, { lastUsed: new Date() });
- // When SSO is enforced, mark the user + alias as verified/accepted before issuing a session.
- if (skipEmailVerification) {
+ // When the IdP is authoritative, mark the user + alias as verified/accepted before issuing a session.
+ if (isIdpAuthoritative) {
({ user, userAlias } = await ensureSsoAccountVerified({
user,
userAlias,
@@ -811,7 +815,7 @@ export const samlConfigServiceFactory = ({
assertedFirstName: firstName,
assertedLastName: lastName,
orgId,
- isAuthEnforced: Boolean(organization.authEnforced),
+ isIdpAuthoritative,
userDAL,
userAliasDAL,
emailDomainDAL,
diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.ts
index 8a4bfc6887..2a5f87350d 100644
--- a/backend/src/server/plugins/auth/inject-identity.ts
+++ b/backend/src/server/plugins/auth/inject-identity.ts
@@ -326,7 +326,11 @@ export const injectIdentity = fp(
await server.services.authToken.fnValidateJwtIdentity(token);
requestContext.set(RequestContextKey.OrgId, orgId);
requestContext.set(RequestContextKey.OrgName, orgName);
- requestContext.set(RequestContextKey.UserAuthInfo, { userId: user.id, email: user.email || "" });
+ requestContext.set(RequestContextKey.UserAuthInfo, {
+ userId: user.id,
+ email: user.email || "",
+ issuingRootOrgId: token.issuingRootOrgId
+ });
req.auth = {
authMode: AuthMode.JWT,
user,
@@ -352,7 +356,11 @@ export const injectIdentity = fp(
if (token.delegation !== OauthDelegationMode.Full) {
requestContext.set(RequestContextKey.OauthScopes, token.scopes ?? []);
}
- requestContext.set(RequestContextKey.UserAuthInfo, { userId: user.id, email: user.email || "" });
+ requestContext.set(RequestContextKey.UserAuthInfo, {
+ userId: user.id,
+ email: user.email || "",
+ issuingRootOrgId: token.issuingRootOrgId
+ });
req.auth = {
authMode: AuthMode.OAUTH,
user,
diff --git a/backend/src/server/routes/v1/auth-router.ts b/backend/src/server/routes/v1/auth-router.ts
index 6a29ea1c9e..c02e942fd3 100644
--- a/backend/src/server/routes/v1/auth-router.ts
+++ b/backend/src/server/routes/v1/auth-router.ts
@@ -153,6 +153,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
accessVersion: tokenVersion.accessVersion,
organizationId: decodedToken.organizationId,
...(decodedToken.subOrganizationId && { subOrganizationId: decodedToken.subOrganizationId }),
+ issuingRootOrgId: decodedToken.issuingRootOrgId,
isMfaVerified: decodedToken.isMfaVerified,
mfaMethod: decodedToken.mfaMethod
},
diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.ts
index 92d5c64782..1d3bf6bdab 100644
--- a/backend/src/server/routes/v1/oauth-router.ts
+++ b/backend/src/server/routes/v1/oauth-router.ts
@@ -424,6 +424,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {
scope: req.body.scope,
userId: req.auth.userId,
authMethod: req.auth.authMethod,
+ issuingRootOrgId: req.auth.token.issuingRootOrgId,
isMfaVerified: req.auth.isMfaVerified,
mfaMethod: req.auth.mfaMethod,
ip: req.realIp
diff --git a/backend/src/server/routes/v3/login-router.ts b/backend/src/server/routes/v3/login-router.ts
index 68bea9c404..02a2fe0d5d 100644
--- a/backend/src/server/routes/v3/login-router.ts
+++ b/backend/src/server/routes/v3/login-router.ts
@@ -77,6 +77,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
userId: req.auth.userId,
userAuthMethod: req.auth.authMethod,
actorRootOrgId: req.auth.rootOrgId,
+ issuingRootOrgId: req.auth.token.issuingRootOrgId,
isMfaVerified: req.auth.isMfaVerified,
mfaMethod: req.auth.mfaMethod
});
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index 6d44021890..2cb2e999e5 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -348,6 +348,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
refreshVersion: updatedSession.refreshVersion,
organizationId: decodedToken.organizationId,
...(decodedToken.subOrganizationId && { subOrganizationId: decodedToken.subOrganizationId }),
+ issuingRootOrgId: decodedToken.issuingRootOrgId,
isMfaVerified: decodedToken.isMfaVerified,
mfaMethod: decodedToken.mfaMethod
},
diff --git a/backend/src/services/auth/auth-fns.test.ts b/backend/src/services/auth/auth-fns.test.ts
index 5ffdd12429..f4b3abad3c 100644
--- a/backend/src/services/auth/auth-fns.test.ts
+++ b/backend/src/services/auth/auth-fns.test.ts
@@ -3,6 +3,8 @@ import {
assertOAuthLoginMethodEnabled,
isMfaProofAccepted,
isOAuthLoginMethodDisabled,
+ isSsoAuthMethod,
+ isSsoSessionIssuedByOrg,
RECOVERY_CODE_MFA_ASSURANCE
} from "./auth-fns";
import { AuthMethod, MfaMethod } from "./auth-type";
@@ -62,3 +64,37 @@ describe("isMfaProofAccepted", () => {
expect(isMfaProofAccepted("1", [MfaMethod.EMAIL])).toBe(false);
});
});
+
+describe("isSsoSessionIssuedByOrg", () => {
+ const rootOrgId = "org-a";
+
+ test.each([
+ AuthMethod.OKTA_SAML,
+ AuthMethod.AZURE_SAML,
+ AuthMethod.KEYCLOAK_SAML,
+ AuthMethod.OIDC,
+ AuthMethod.LDAP
+ ] as const)("accepts a %s session this org's IdP issued", (authMethod) => {
+ expect(isSsoAuthMethod(authMethod)).toBe(true);
+ expect(isSsoSessionIssuedByOrg({ authMethod, issuingRootOrgId: rootOrgId, rootOrgId })).toBe(true);
+ });
+
+ test.each([AuthMethod.OKTA_SAML, AuthMethod.OIDC, AuthMethod.LDAP] as const)(
+ "refuses a %s session another org's IdP issued",
+ (authMethod) => {
+ expect(isSsoSessionIssuedByOrg({ authMethod, issuingRootOrgId: "org-b", rootOrgId })).toBe(false);
+ }
+ );
+
+ test("takes a token issued before the claim existed at its method", () => {
+ expect(isSsoSessionIssuedByOrg({ authMethod: AuthMethod.OKTA_SAML, rootOrgId })).toBe(true);
+ });
+
+ test.each([AuthMethod.EMAIL, AuthMethod.GOOGLE, AuthMethod.GITHUB, AuthMethod.GITLAB] as const)(
+ "never counts an own-credential %s session as the org's SSO",
+ (authMethod) => {
+ expect(isSsoAuthMethod(authMethod)).toBe(false);
+ expect(isSsoSessionIssuedByOrg({ authMethod, issuingRootOrgId: rootOrgId, rootOrgId })).toBe(false);
+ }
+ );
+});
diff --git a/backend/src/services/auth/auth-fns.ts b/backend/src/services/auth/auth-fns.ts
index cf03ac1f7b..0543ae9fd2 100644
--- a/backend/src/services/auth/auth-fns.ts
+++ b/backend/src/services/auth/auth-fns.ts
@@ -1,3 +1,4 @@
+import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
@@ -71,6 +72,25 @@ export const getRequiredMfaMethod = (
return { isMfaRequired, requiredMfaMethod };
};
+export const isSsoAuthMethod = (authMethod: AuthMethod) =>
+ isAuthMethodSaml(authMethod) || authMethod === AuthMethod.OIDC || authMethod === AuthMethod.LDAP;
+
+/**
+ * Whether a session counts as this root org's own SSO. The method alone is not enough: a SAML
+ * session another org's IdP minted would otherwise satisfy this org's enforcement without its IdP,
+ * MFA or deprovisioning ever seeing the login. Tokens issued before the claim existed carry no
+ * issuer and are taken at their method, as before.
+ */
+export const isSsoSessionIssuedByOrg = ({
+ authMethod,
+ issuingRootOrgId,
+ rootOrgId
+}: {
+ authMethod: AuthMethod;
+ issuingRootOrgId?: string;
+ rootOrgId: string;
+}) => isSsoAuthMethod(authMethod) && (!issuingRootOrgId || issuingRootOrgId === rootOrgId);
+
export const RECOVERY_CODE_MFA_ASSURANCE = "recovery-code";
export type TMfaAssurance = MfaMethod | typeof RECOVERY_CODE_MFA_ASSURANCE;
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index e9beeb66bb..7472e9368c 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -10,7 +10,7 @@ import {
} from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { OrgPermissionSsoActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
-import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";
+import { FOREIGN_SSO_SESSION_ERROR_NAME } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { getConfig } from "@app/lib/config/env";
import { crypto, generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
@@ -58,6 +58,8 @@ import {
enforceUserLockStatus,
getRequiredMfaMethod,
isOAuthLoginMethodDisabled,
+ isSsoAuthMethod,
+ isSsoSessionIssuedByOrg,
OAuthAuthMethod,
RECOVERY_CODE_MFA_ASSURANCE
} from "./auth-fns";
@@ -188,12 +190,14 @@ export const authLoginServiceFactory = ({
email,
authMethod,
organizationId,
+ issuingRootOrgId,
requiredMfaMethod
}: {
userId: string;
email?: string | null;
authMethod: AuthMethod;
organizationId?: string;
+ issuingRootOrgId?: string;
requiredMfaMethod: MfaMethod;
}) => {
const appCfg = getConfig();
@@ -204,6 +208,7 @@ export const authLoginServiceFactory = ({
authTokenType: AuthTokenType.MFA_TOKEN,
userId,
organizationId,
+ issuingRootOrgId,
email,
requiredMfaMethod
},
@@ -232,6 +237,7 @@ export const authLoginServiceFactory = ({
organizationId,
subOrganizationId,
authMethod,
+ issuingRootOrgId,
isMfaVerified,
mfaMethod
}: {
@@ -241,6 +247,7 @@ export const authLoginServiceFactory = ({
organizationId?: string;
subOrganizationId?: string;
authMethod: AuthMethod;
+ issuingRootOrgId?: string;
isMfaVerified?: boolean;
mfaMethod?: MfaMethod;
},
@@ -289,6 +296,7 @@ export const authLoginServiceFactory = ({
accessVersion: tokenSession.accessVersion,
organizationId,
subOrganizationId,
+ issuingRootOrgId,
isMfaVerified,
mfaMethod
},
@@ -305,6 +313,7 @@ export const authLoginServiceFactory = ({
refreshVersion: tokenSession.refreshVersion,
organizationId,
subOrganizationId,
+ issuingRootOrgId,
isMfaVerified,
mfaMethod
},
@@ -327,6 +336,10 @@ export const authLoginServiceFactory = ({
}: TProcessProviderCallbackDTO): Promise<TProviderAuthCallback> => {
const appCfg = getConfig();
+ // SSO configs live on root orgs, so the org an IdP login names is the issuing root org. An
+ // OAuth login may name an org too (the default auth org) and must not be bound to it.
+ const issuingRootOrgId = isSsoAuthMethod(authMethod) ? organizationId : undefined;
+
if (!user.isAccepted || !isEmailVerified) {
const signupToken = crypto.jwt().sign(
{
@@ -336,6 +349,7 @@ export const authLoginServiceFactory = ({
isEmailVerified,
aliasId,
organizationId,
+ issuingRootOrgId,
callbackPort,
email: user.email,
firstName: user.firstName,
@@ -353,7 +367,8 @@ export const authLoginServiceFactory = ({
userId: user.id,
ip,
userAgent,
- authMethod
+ authMethod,
+ issuingRootOrgId
});
if (organizationId) {
@@ -738,6 +753,7 @@ export const authLoginServiceFactory = ({
userAgent,
organizationId: orgId,
authMethod: decodedToken.authMethod,
+ issuingRootOrgId: decodedToken.issuingRootOrgId,
isMfaVerified: true,
mfaMethod
});
@@ -1154,6 +1170,7 @@ export const authLoginServiceFactory = ({
userId,
userAuthMethod,
actorRootOrgId,
+ issuingRootOrgId,
isMfaVerified,
mfaMethod
}: {
@@ -1163,6 +1180,7 @@ export const authLoginServiceFactory = ({
userId: string;
userAuthMethod: AuthMethod;
actorRootOrgId?: string;
+ issuingRootOrgId?: string;
isMfaVerified?: boolean;
mfaMethod?: MfaMethod;
}) => {
@@ -1236,30 +1254,52 @@ export const authLoginServiceFactory = ({
}
}
- const { permission } = await permissionService.getOrgPermission({
- actor: ActorType.USER,
- actorId: user.id,
- orgId: rootOrg.id,
- actorAuthMethod: userAuthMethod,
- actorOrgId: rootOrg.id,
- scope: OrganizationActionScope.Any
- });
+ const { permission } = await permissionService
+ .getOrgPermission({
+ actor: ActorType.USER,
+ actorId: user.id,
+ orgId: rootOrg.id,
+ actorAuthMethod: userAuthMethod,
+ actorOrgId: rootOrg.id,
+ scope: OrganizationActionScope.Any
+ })
+ .catch(async (error: unknown) => {
+ // getOrgPermission enforces SSO, so it is what refuses a session another org's IdP issued.
+ if (
+ error instanceof ForbiddenRequestError &&
+ error.name === FOREIGN_SSO_SESSION_ERROR_NAME &&
+ issuingRootOrgId
+ ) {
+ await auditLogService.createAuditLog({
+ orgId: organizationId,
+ ipAddress,
+ userAgent,
+ userAgentType: getUserAgentType(userAgent),
+ actor: {
+ type: ActorType.USER,
+ metadata: {
+ email: user.email,
+ userId: user.id,
+ username: user.username,
+ authMethod: userAuthMethod as string
+ }
+ },
+ event: {
+ type: EventType.SELECT_ORGANIZATION_REFUSED,
+ metadata: {
+ organizationId,
+ organizationName: selectedOrg.name,
+ issuingOrganizationId: issuingRootOrgId
+ }
+ }
+ });
+ }
+ throw error;
+ });
const canBypassSso =
rootOrg.bypassOrgAuthEnabled &&
permission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);
- if (
- rootOrg.authEnforced &&
- !isAuthMethodSaml(userAuthMethod) &&
- userAuthMethod !== AuthMethod.OIDC &&
- userAuthMethod !== AuthMethod.LDAP &&
- !canBypassSso
- ) {
- throw new BadRequestError({
- message: "Login with the auth method required by your organization."
- });
- }
-
if (rootOrg.googleSsoAuthEnforced && userAuthMethod !== AuthMethod.GOOGLE) {
if (!canBypassSso) {
throw new ForbiddenRequestError({
@@ -1303,7 +1343,8 @@ export const authLoginServiceFactory = ({
email: user.email,
authMethod: userAuthMethod,
requiredMfaMethod,
- organizationId: rootOrg.id
+ organizationId: rootOrg.id,
+ issuingRootOrgId
});
return { isMfaEnabled: true, mfa: mfaToken, mfaMethod: requiredMfaMethod } as const;
@@ -1318,17 +1359,16 @@ export const authLoginServiceFactory = ({
ip: ipAddress,
organizationId: isSubOrganization ? rootOrg.id : organizationId,
subOrganizationId: isSubOrganization ? organizationId : undefined,
+ issuingRootOrgId,
isMfaVerified,
mfaMethod
});
- // In the event of this being a break-glass request (non-saml / non-oidc / non-google, when any is enforced)
+ // In the event of this being a break-glass request (not this org's own SAML / OIDC / LDAP session, nor Google, when any is enforced)
const isAuthEnforcedBypass =
rootOrg.authEnforced &&
rootOrg.bypassOrgAuthEnabled &&
- !isAuthMethodSaml(userAuthMethod) &&
- userAuthMethod !== AuthMethod.OIDC &&
- userAuthMethod !== AuthMethod.LDAP &&
+ !isSsoSessionIssuedByOrg({ authMethod: userAuthMethod, issuingRootOrgId, rootOrgId: rootOrg.id }) &&
userAuthMethod !== AuthMethod.GOOGLE;
const isGoogleSsoEnforcedBypass =
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index 49257450d4..8bdee202bc 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -404,7 +404,8 @@ export const authSignupServiceFactory = ({
ip: dto.ip,
userAgent: dto.userAgent,
authMethod,
- organizationId
+ organizationId,
+ issuingRootOrgId: decodedToken.issuingRootOrgId
});
return {
diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.ts
index 826a69c300..66278c2bed 100644
--- a/backend/src/services/auth/auth-type.ts
+++ b/backend/src/services/auth/auth-type.ts
@@ -111,6 +111,10 @@ export type AuthModeJwtTokenPayload = {
accessVersion: number;
organizationId?: string;
subOrganizationId?: string;
+ // Root org whose IdP issued this session. Set only by SAML, OIDC and LDAP logins; absent on
+ // own-credential sessions and on tokens issued before the claim existed, which are taken at
+ // their auth method as before.
+ issuingRootOrgId?: string;
isMfaVerified?: boolean;
mfaMethod?: MfaMethod;
// Present only on delegated OAuth 2.0 access tokens. Its presence marks the token as
@@ -129,6 +133,7 @@ export type AuthModeMfaJwtTokenPayload = {
authMethod: AuthMethod;
userId: string;
organizationId?: string;
+ issuingRootOrgId?: string;
requiredMfaMethod: MfaMethod;
};
@@ -141,6 +146,7 @@ export type AuthModeRefreshJwtTokenPayload = {
refreshVersion: number;
organizationId?: string;
subOrganizationId?: string;
+ issuingRootOrgId?: string;
isMfaVerified?: boolean;
mfaMethod?: MfaMethod;
oauthClientId?: string;
@@ -154,6 +160,7 @@ export type AuthModeSignUpTokenPayload = {
isEmailVerified: boolean;
aliasId?: string;
organizationId?: string;
+ issuingRootOrgId?: string;
callbackPort?: string;
// User profile fields for the frontend signup page
email?: string;
diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.ts
index 120b69df7f..7cbb0eedbc 100644
--- a/backend/src/services/oauth-client/oauth-client-service.ts
+++ b/backend/src/services/oauth-client/oauth-client-service.ts
@@ -100,6 +100,7 @@ type TOauthTokenClaims = {
userId: string;
tokenVersionId: string;
organizationId: string;
+ issuingRootOrgId?: string;
isMfaVerified?: boolean;
mfaMethod?: MfaMethod;
} & ({ scopes: string[]; delegation?: never } | { delegation: OauthDelegationMode.Full; scopes?: never });
@@ -132,6 +133,7 @@ const signOauthToken = (
// refreshVersion. Emit whichever claim matches this token's type under its expected name.
...(isAccessToken ? { accessVersion: claims.version } : { refreshVersion: claims.version }),
organizationId: claims.organizationId,
+ issuingRootOrgId: claims.issuingRootOrgId,
isMfaVerified: claims.isMfaVerified,
mfaMethod: claims.mfaMethod,
// Marks this as a delegated OAuth token. extractAuth maps tokens carrying this claim to
@@ -571,6 +573,7 @@ export const oauthClientServiceFactory = ({
orgId: client.orgId,
userId: dto.userId,
authMethod: dto.authMethod,
+ issuingRootOrgId: dto.issuingRootOrgId,
isMfaVerified: dto.isMfaVerified,
mfaMethod: dto.mfaMethod,
tokenVersionId: tokenSession.id,
@@ -761,6 +764,7 @@ export const oauthClientServiceFactory = ({
userId: user.id,
tokenVersionId: tokenSession.id,
organizationId: client.orgId,
+ issuingRootOrgId: client.orgId,
isMfaVerified: client.tokenExchangeIdpSatisfiesMfa || undefined,
delegation: OauthDelegationMode.Full,
tokenType: AuthTokenType.ACCESS_TOKEN,
@@ -864,6 +868,7 @@ export const oauthClientServiceFactory = ({
userId: codePayload.userId,
tokenVersionId: tokenSession.id,
organizationId: codePayload.orgId,
+ issuingRootOrgId: codePayload.issuingRootOrgId,
isMfaVerified: codePayload.isMfaVerified,
mfaMethod: codePayload.mfaMethod,
scopes: grantedScopes
@@ -931,6 +936,7 @@ export const oauthClientServiceFactory = ({
userId: decodedToken.userId,
tokenVersionId: tokenVersion.id,
organizationId: decodedToken.organizationId,
+ issuingRootOrgId: decodedToken.issuingRootOrgId,
isMfaVerified: decodedToken.isMfaVerified,
mfaMethod: decodedToken.mfaMethod,
scopes: grantedScopes
diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.ts
index 5dfb48b273..1b32612616 100644
--- a/backend/src/services/oauth-client/oauth-client-types.ts
+++ b/backend/src/services/oauth-client/oauth-client-types.ts
@@ -76,6 +76,7 @@ export type TOauthConsentDTO = {
scope?: string;
userId: string;
authMethod: AuthMethod;
+ issuingRootOrgId?: string;
isMfaVerified?: boolean;
mfaMethod?: MfaMethod;
ip: string;
@@ -108,6 +109,7 @@ export const OauthAuthorizationCodePayloadSchema = z.object({
orgId: z.string(),
userId: z.string(),
authMethod: z.nativeEnum(AuthMethod),
+ issuingRootOrgId: z.string().optional(),
isMfaVerified: z.boolean().optional(),
mfaMethod: z.nativeEnum(MfaMethod).optional(),
tokenVersionId: z.string(),
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index b02cdfae4c..1f3c125ef8 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -937,6 +937,7 @@ export const orgServiceFactory = ({
{
userId: user.id,
authMethod: decodedToken.authMethod,
+ issuingRootOrgId: decodedToken.issuingRootOrgId,
ip: ipAddress,
userAgent: userAgentHeader,
isMfaVerified: decodedToken.isMfaVerified,
diff --git a/backend/src/services/user-alias/user-alias-fns.test.ts b/backend/src/services/user-alias/user-alias-fns.test.ts
index 4fc24f556b..e031455eff 100644
--- a/backend/src/services/user-alias/user-alias-fns.test.ts
+++ b/backend/src/services/user-alias/user-alias-fns.test.ts
@@ -486,7 +486,7 @@ const sync = (args: Record<string, unknown>, deps: ReturnType<typeof makeDeps>)
userAlias: makeAlias(),
assertedEmail: "[email protected]",
orgId: "org-1",
- isAuthEnforced: true,
+ isIdpAuthoritative: true,
userDAL: deps.userDAL,
userAliasDAL: deps.userAliasDAL,
emailDomainDAL: deps.emailDomainDAL,
@@ -495,9 +495,9 @@ const sync = (args: Record<string, unknown>, deps: ReturnType<typeof makeDeps>)
} as Parameters<typeof syncSsoUserProfile>[0]);
describe("syncSsoUserProfile", () => {
- test("does nothing when the org does not enforce SSO", async () => {
+ test("does nothing when the IdP is not authoritative for the account", async () => {
const deps = makeDeps();
- const user = await sync({ assertedEmail: "[email protected]", isAuthEnforced: false }, deps);
+ const user = await sync({ assertedEmail: "[email protected]", isIdpAuthoritative: false }, deps);
expect(user.username).toBe("[email protected]");
expect(deps.userDAL.updateById).not.toHaveBeenCalled();
diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.ts
index bb336b8753..d1d82e4ccf 100644
--- a/backend/src/services/user-alias/user-alias-fns.ts
+++ b/backend/src/services/user-alias/user-alias-fns.ts
@@ -146,7 +146,8 @@ type TSyncSsoUserProfileDTO = {
assertedFirstName?: string | null;
assertedLastName?: string | null;
orgId: string;
- isAuthEnforced: boolean;
+ // The org enforces SSO and owns the asserted domain (isIdpAuthoritativeForDomain).
+ isIdpAuthoritative: boolean;
userDAL: Pick<TUserDALFactory, "findOne" | "updateById" | "transaction">;
userAliasDAL: Pick<TUserAliasDALFactory, "updateById">;
emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;
@@ -157,8 +158,8 @@ type TSyncSsoUserProfileDTO = {
* An IdP that keys people on a stable identifier (a UPN, say) lets them change mailbox and display
* name without changing who they are, so our copy of both goes stale: notification mail is sent to
* an address that no longer exists, and every audit entry written from then on records it. Where
- * the org enforces SSO it has already made the IdP authoritative for identity, so the assertion is
- * the better source and we take it.
+ * the org enforces SSO and owns the asserted domain it has made the IdP authoritative for identity,
+ * so the assertion is the better source and we take it.
*
* Requires a verified alias, which is our proof that the IdP controls this account. An unverified
* alias asserting an unrecognized email is what isStaleSsoAlias exists to catch, and reading that
@@ -178,13 +179,13 @@ export const syncSsoUserProfile = async ({
assertedFirstName,
assertedLastName,
orgId,
- isAuthEnforced,
+ isIdpAuthoritative,
userDAL,
userAliasDAL,
emailDomainDAL,
auditLogService
}: TSyncSsoUserProfileDTO): Promise<TUsers> => {
- if (!isAuthEnforced || !userAlias.isEmailVerified) return user;
+ if (!isIdpAuthoritative || !userAlias.isEmailVerified) return user;
const assertedUsername = sanitizeEmail(assertedEmail);
const isEmailChanged = Boolean(assertedUsername) && assertedUsername !== user.username;
diff --git a/docs/documentation/platform/sso/overview.mdx b/docs/documentation/platform/sso/overview.mdx
index 7db6d2fe3e..f12bf781ab 100644
--- a/docs/documentation/platform/sso/overview.mdx
+++ b/docs/documentation/platform/sso/overview.mdx
@@ -52,6 +52,8 @@ When you enforce SAML or OIDC SSO for your organization, members can only access
- **Email verification is skipped for SSO sign-ins.** Because the verified domain and IdP already prove ownership of the email, Infisical skips the additional email-verification step that normally applies to SSO logins (see the FAQ below).
- **Email addresses and names come from your identity provider.** Each SSO login updates the member's email address and name to match the assertion. Someone renamed in your identity provider keeps their Infisical account and their access, and later notifications and audit log entries carry the new address. Members on one of your verified domains can't change their own email address while enforcement is on.
+Enforcement also covers members who belong to another organization that uses SSO: a session issued by that organization's identity provider doesn't satisfy your enforcement. Infisical refuses the session, including one that was already open when you turned on enforcement, and the member signs in through your identity provider instead.
+
<Warning>
Before enforcing SSO, make sure a break-glass organization admin already has a password and SSO bypass access. After enforcement is enabled, the signup block prevents creating new password accounts for the domain.
</Warning>
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index ce6f7eab66..6658d0f1fd 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -129,6 +129,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.DELETE_PKI_COLLECTION_ITEM]: "Delete PKI collection item",
[EventType.ORG_ADMIN_ACCESS_PROJECT]: "Org admin accessed project",
[EventType.ORG_ADMIN_BYPASS_SSO]: "Org admin bypassed SSO enforcement",
+ [EventType.SELECT_ORGANIZATION_REFUSED]: "Organization sign-in refused",
[EventType.CREATE_CERTIFICATE_TEMPLATE]: "Create certificate template",
[EventType.UPDATE_CERTIFICATE_TEMPLATE]: "Update certificate template",
[EventType.DELETE_CERTIFICATE_TEMPLATE]: "Delete certificate template",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 0bd3c2a7cc..86e4961ba7 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -145,6 +145,7 @@ export enum EventType {
DELETE_PKI_COLLECTION_ITEM = "delete-pki-collection-item",
ORG_ADMIN_ACCESS_PROJECT = "org-admin-accessed-project",
ORG_ADMIN_BYPASS_SSO = "org-admin-bypassed-sso",
+ SELECT_ORGANIZATION_REFUSED = "select-organization-refused",
CREATE_CERTIFICATE_TEMPLATE = "create-certificate-template",
UPDATE_CERTIFICATE_TEMPLATE = "update-certificate-template",
DELETE_CERTIFICATE_TEMPLATE = "delete-certificate-template",
diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrg.utils.ts b/frontend/src/pages/auth/SelectOrgPage/SelectOrg.utils.ts
index 72dd0acc65..ea42c98dab 100644
--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrg.utils.ts
+++ b/frontend/src/pages/auth/SelectOrgPage/SelectOrg.utils.ts
@@ -4,6 +4,7 @@ import { getAuthToken } from "@app/hooks/api/reactQuery";
import { AuthMethod, SAML_AUTH_METHODS } from "@app/hooks/api/users/types";
type TOrgSsoEnforcement = {
+ id: string;
authEnforced: boolean;
googleSsoAuthEnforced: boolean;
orgAuthMethod: string;
@@ -12,7 +13,9 @@ type TOrgSsoEnforcement = {
const SSO_ENFORCEMENT_ERRORS = {
google: 'This organization requires Google login. Log out, then choose "Continue with Google".',
oidc: 'This organization requires OIDC login. Log out, then choose "Continue with OIDC" and enter your work email.',
- saml: 'This organization requires SAML login. Log out, then choose "Continue with SAML" and enter your work email.'
+ saml: 'This organization requires SAML login. Log out, then choose "Continue with SAML" and enter your work email.',
+ foreignIssuer:
+ "This organization requires its own SSO. Your session was issued by another organization's identity provider; log out, then sign in through this organization's SSO."
} as const;
// User-facing error when the org enforces an SSO method the session token wasn't issued by,
@@ -20,7 +23,10 @@ const SSO_ENFORCEMENT_ERRORS = {
export const getSsoEnforcementError = (org: TOrgSsoEnforcement): string | null => {
if (!org.authEnforced && !org.googleSsoAuthEnforced) return null;
- const authToken = jwtDecode(getAuthToken()) as { authMethod: AuthMethod };
+ const authToken = jwtDecode(getAuthToken()) as {
+ authMethod: AuthMethod;
+ issuingRootOrgId?: string;
+ };
if (org.googleSsoAuthEnforced && authToken.authMethod !== AuthMethod.GOOGLE) {
return SSO_ENFORCEMENT_ERRORS.google;
@@ -34,6 +40,11 @@ export const getSsoEnforcementError = (org: TOrgSsoEnforcement): string | null =
) {
return SSO_ENFORCEMENT_ERRORS.saml;
}
+ // An SSO session another org's IdP issued does not satisfy this org's enforcement. Tokens from
+ // before the claim existed carry no issuer and pass on their method, as the server does.
+ if (org.authEnforced && authToken.issuingRootOrgId && authToken.issuingRootOrgId !== org.id) {
+ return SSO_ENFORCEMENT_ERRORS.foreignIssuer;
+ }
return null;
};