Skip to content

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

feat: resolving bugs while testing

=90da30f0bfc9
diff --git a/backend/src/db/migrations/20260404140728_username-merge.ts b/backend/src/db/migrations/20260404140728_username-merge.ts
new file mode 100644
index 0000000000..feebb3421a
--- /dev/null
+++ b/backend/src/db/migrations/20260404140728_username-merge.ts
@@ -0,0 +1,143 @@
+/* eslint-disable no-await-in-loop */
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ // ============================================================
+ // Step 1: Copy hashedPassword from user_encryption_keys to users
+ // ============================================================
+ await knex.raw(`
+ UPDATE "${TableName.Users}" u
+ SET "hashedPassword" = uek."hashedPassword"
+ FROM "${TableName.UserEncryptionKey}" uek
+ WHERE u.id = uek."userId"
+ AND uek."hashedPassword" IS NOT NULL
+ AND u."hashedPassword" IS NULL
+ `);
+
+ // ============================================================
+ // Step 2: Mark provider-verified flags based on authMethods
+ // ============================================================
+ await knex.raw(`
+ UPDATE "${TableName.Users}"
+ SET "isGitHubVerified" = TRUE
+ WHERE "authMethods" @> ARRAY['github']::text[]
+ AND ("isGitHubVerified" IS NULL OR "isGitHubVerified" = FALSE)
+ `);
+
+ await knex.raw(`
+ UPDATE "${TableName.Users}"
+ SET "isGoogleVerified" = TRUE
+ WHERE "authMethods" @> ARRAY['google']::text[]
+ AND ("isGoogleVerified" IS NULL OR "isGoogleVerified" = FALSE)
+ `);
+
+ await knex.raw(`
+ UPDATE "${TableName.Users}"
+ SET "isGitLabVerified" = TRUE
+ WHERE "authMethods" @> ARRAY['gitlab']::text[]
+ AND ("isGitLabVerified" IS NULL OR "isGitLabVerified" = FALSE)
+ `);
+
+ // ============================================================
+ // Step 3: Clean up duplicate users sharing the same email
+ //
+ // All FK references to users are either CASCADE (deleted with the user)
+ // or SET NULL (nulled out). So deleting a user row is always safe.
+ // For verified+accepted duplicates, we reassign FK references to the winner before deleting.
+ // ============================================================
+
+ // Get all FK references to users.id once (used when merging verified+accepted duplicates)
+ const fkRefs = await knex.raw(`
+ SELECT tc.table_name, kcu.column_name
+ FROM information_schema.table_constraints tc
+ JOIN information_schema.key_column_usage kcu
+ ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
+ JOIN information_schema.constraint_column_usage ccu
+ ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema
+ WHERE tc.constraint_type = 'FOREIGN KEY'
+ AND ccu.table_name = 'users' AND ccu.column_name = 'id'
+ AND tc.table_schema = 'public'
+ `);
+ const userFkReferences = fkRefs.rows as { table_name: string; column_name: string }[];
+
+ // Find all emails with multiple user rows
+ const duplicateEmails = await knex.raw(`
+ SELECT LOWER(email) as email, array_agg(id) as user_ids
+ FROM "${TableName.Users}"
+ WHERE email IS NOT NULL AND "isGhost" = FALSE
+ GROUP BY LOWER(email)
+ HAVING COUNT(*) > 1
+ `);
+
+ for (const row of duplicateEmails.rows) {
+ const { email, user_ids: userIds } = row as { email: string; user_ids: string[] };
+ // eslint-disable-next-line no-continue
+ if (!userIds || userIds.length < 2) continue;
+
+ // Get details for all users in this group
+ const usersDetail = await knex.raw(
+ `SELECT id, username, "isEmailVerified", "isAccepted"
+ FROM "${TableName.Users}" WHERE id = ANY(?) ORDER BY "createdAt" ASC`,
+ [userIds]
+ );
+ const users = usersDetail.rows as {
+ id: string;
+ username: string;
+ isEmailVerified: boolean | null;
+ isAccepted: boolean | null;
+ }[];
+
+ // Delete incomplete users (not verified OR not accepted)
+ const incompleteIds = users.filter((u) => !u.isEmailVerified || !u.isAccepted).map((u) => u.id);
+
+ if (incompleteIds.length > 0) {
+ await knex.raw(`DELETE FROM "${TableName.Users}" WHERE id = ANY(?)`, [incompleteIds]);
+ }
+
+ // Check what's left
+ const remaining = users.filter((u) => !incompleteIds.includes(u.id));
+ // eslint-disable-next-line no-continue
+ if (remaining.length <= 1) continue;
+
+ // Still multiple verified+accepted users — pick winner and merge losers into them
+ const winner = remaining.find((u) => u.username === email) || remaining[0];
+ const loserIds = remaining.filter((u) => u.id !== winner.id).map((u) => u.id);
+
+ if (loserIds.length > 0) {
+ // Reassign loser FK references to winner before deleting
+ for (const ref of userFkReferences) {
+ // Try to reassign loser rows to winner. If the winner already has a row
+ // that would conflict (unique constraint), the update will fail for that row.
+ // So we do it in two steps: update what we can, leave the rest for CASCADE delete.
+ try {
+ await knex.raw(
+ `UPDATE "${ref.table_name}" SET "${ref.column_name}" = ?
+ WHERE "${ref.column_name}" = ANY(?)`,
+ [winner.id, loserIds]
+ );
+ } catch {
+ // Unique constraint violation — some rows couldn't be reassigned.
+ // That's fine — they'll be cleaned up by CASCADE when the loser user is deleted.
+ }
+ }
+
+ // Now delete losers — any remaining CASCADE refs will be cleaned up,
+ // SET NULL refs were already reassigned or will be nulled
+ await knex.raw(`DELETE FROM "${TableName.Users}" WHERE id = ANY(?)`, [loserIds]);
+ }
+ }
+
+ // Final step: update all remaining users where username != LOWER(email)
+ await knex.raw(`
+ UPDATE "${TableName.Users}"
+ SET username = LOWER(email)
+ WHERE email IS NOT NULL
+ AND username != LOWER(email)
+ `);
+}
+
+export async function down(): Promise<void> {
+ // Data transformation — not reversible
+}
diff --git a/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts b/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
new file mode 100644
index 0000000000..cc4d90d9fa
--- /dev/null
+++ b/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
@@ -0,0 +1,161 @@
+/* eslint-disable no-await-in-loop */
+import crypto from "node:crypto";
+
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+// Public/shared email providers that should never be claimed as org-owned domains
+const PUBLIC_EMAIL_DOMAINS = new Set([
+ // Google
+ "gmail.com",
+ "googlemail.com",
+ // Microsoft
+ "outlook.com",
+ "hotmail.com",
+ "live.com",
+ "msn.com",
+ "onmicrosoft.com",
+ // Yahoo
+ "yahoo.com",
+ "ymail.com",
+ "rocketmail.com",
+ // Apple
+ "icloud.com",
+ "me.com",
+ "mac.com",
+ // ProtonMail
+ "protonmail.com",
+ "proton.me",
+ "pm.me",
+ // Other major providers
+ "aol.com",
+ "zoho.com",
+ "mail.com",
+ "gmx.com",
+ "gmx.net",
+ "yandex.com",
+ "fastmail.com",
+ "tutanota.com",
+ "tuta.io",
+ // IdP provider domains (test/default accounts)
+ "okta.com",
+ "auth0.com",
+ "onelogin.com",
+ "jumpcloud.com",
+ "duo.com",
+ // Development/testing
+ "example.com",
+ "test.com",
+ "localhost",
+ "localhost.local"
+]);
+
+/**
+ * For non-cloud (self-hosted) environments only:
+ * Auto-seed verified email domains from existing SSO configurations.
+ *
+ * Looks at orgs with SAML, OIDC, or LDAP configs and finds the unique email domains
+ * from their verified user aliases. For each domain, inserts it as a verified email domain
+ * for the org with the most verified aliases in that domain.
+ */
+export async function up(knex: Knex): Promise<void> {
+ // Only run for non-cloud (self-hosted) environments
+ // Cloud environments have LICENSE_SERVER_KEY set
+ if (process.env.LICENSE_SERVER_KEY) {
+ return;
+ }
+
+ const emailDomainsPopulated = await knex(TableName.EmailDomains).select("id").limit(1);
+ if (emailDomainsPopulated.length) {
+ return;
+ }
+
+ // Find all orgs that have SSO configured (SAML, OIDC, or LDAP)
+ const ssoOrgs = await knex.raw(`
+ SELECT DISTINCT org_id FROM (
+ SELECT "orgId" as org_id FROM "${TableName.SamlConfig}" WHERE "isActive" = TRUE
+ UNION
+ SELECT "orgId" as org_id FROM "${TableName.OidcConfig}" WHERE "isActive" = TRUE
+ UNION
+ SELECT "orgId" as org_id FROM "${TableName.LdapConfig}" WHERE "isActive" = TRUE
+ ) sso_orgs
+ `);
+
+ const ssoOrgIds = (ssoOrgs.rows as { org_id: string }[]).map((r) => r.org_id);
+ if (ssoOrgIds.length === 0) return;
+
+ // For each SSO org, find unique email domains from verified user aliases
+ // Count how many verified aliases each org has per domain
+ const domainCounts = await knex.raw(
+ `
+ SELECT
+ ua."orgId" as org_id,
+ LOWER(SPLIT_PART(ua.emails[1], '@', 2)) as domain,
+ COUNT(*) as alias_count
+ FROM "${TableName.UserAliases}" ua
+ WHERE ua."orgId" = ANY(?)
+ AND ua."isEmailVerified" = TRUE
+ AND ua.emails IS NOT NULL
+ AND array_length(ua.emails, 1) > 0
+ AND SPLIT_PART(ua.emails[1], '@', 2) != ''
+ GROUP BY ua."orgId", LOWER(SPLIT_PART(ua.emails[1], '@', 2))
+ ORDER BY domain, alias_count DESC
+ `,
+ [ssoOrgIds]
+ );
+
+ // For each domain, pick the org with the most verified aliases
+ const domainToOrg = new Map<string, { orgId: string; count: number }>();
+ for (const row of domainCounts.rows as { org_id: string; domain: string; alias_count: string }[]) {
+ const { org_id: orgId, domain, alias_count: aliasCount } = row;
+ // eslint-disable-next-line no-continue
+ if (!domain || domain.length < 3) continue;
+
+ // Skip public/shared email providers — these are not org-owned domains
+ // eslint-disable-next-line no-continue
+ if (PUBLIC_EMAIL_DOMAINS.has(domain)) continue;
+
+ const count = parseInt(aliasCount, 10);
+ const existing = domainToOrg.get(domain);
+ if (!existing || count > existing.count) {
+ domainToOrg.set(domain, { orgId, count });
+ }
+ }
+
+ if (domainToOrg.size === 0) return;
+
+ // Check which domains already exist in email_domains table
+ const existingDomains = await knex(TableName.EmailDomains)
+ .whereIn("domain", Array.from(domainToOrg.keys()))
+ .select("domain");
+
+ const existingDomainSet = new Set(existingDomains.map((r) => r.domain));
+
+ // Insert new verified email domains
+ const toInsert = Array.from(domainToOrg.entries())
+ .filter(([domain]) => !existingDomainSet.has(domain))
+ .map(([domain, { orgId }]) => ({
+ orgId,
+ domain,
+ verificationMethod: "migration",
+ verificationCode: crypto.randomBytes(16).toString("hex"),
+ verificationRecordName: `_infisical-verification.${domain}`,
+ status: "verified",
+ verifiedAt: new Date(),
+ codeExpiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000) // 1 year
+ }));
+
+ if (toInsert.length > 0) {
+ // Insert in batches to avoid hitting parameter limits
+ const BATCH_SIZE = 100;
+ for (let i = 0; i < toInsert.length; i += BATCH_SIZE) {
+ const batch = toInsert.slice(i, i + BATCH_SIZE);
+ await knex(TableName.EmailDomains).insert(batch);
+ }
+ }
+}
+
+export async function down(): Promise<void> {
+ // Data seeding — not reversible
+}
diff --git a/backend/src/ee/routes/v1/ldap-router.ts b/backend/src/ee/routes/v1/ldap-router.ts
index d20f726f2c..d94dbf4808 100644
--- a/backend/src/ee/routes/v1/ldap-router.ts
+++ b/backend/src/ee/routes/v1/ldap-router.ts
@@ -120,6 +120,7 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
}) as any,
handler: (req, res) => {
const passportResult = req.passportUser;
+ const cbPort = passportResult.callbackPort;
let nextUrl;
if (passportResult.result === ProviderAuthResult.SESSION) {
@@ -129,9 +130,9 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
- nextUrl = `${appCfg.SITE_URL}/login/select-organization`;
+ nextUrl = `${appCfg.SITE_URL}/login/select-organization${cbPort ? `?callback_port=${cbPort}` : ""}`;
} else if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
- nextUrl = `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`;
+ nextUrl = `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}${cbPort ? `&callback_port=${cbPort}` : ""}`;
} else {
throw new BadRequestError({ message: "Unexpected auth result" });
}
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index 1e050d091a..b8e062777b 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -15,6 +15,7 @@ import { OidcConfigsSchema } from "@app/db/schemas";
import { OIDCConfigurationType, OIDCJWTSignatureAlgorithm } from "@app/ee/services/oidc/oidc-config-types";
import { ApiDocsTags, OidcSSo } from "@app/lib/api-docs";
import { getConfig } from "@app/lib/config/env";
+import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
@@ -75,24 +76,35 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
},
schema: {
querystring: z.object({
- domain: z.string().trim(),
+ domain: z.string().trim().optional(),
+ orgSlug: z.string().trim().optional(),
callbackPort: z.string().trim().optional()
})
},
preValidation: [
async (req, res) => {
- const { domain, callbackPort } = req.query;
+ const { domain, orgSlug, callbackPort } = req.query;
+
+ const identifier = domain || orgSlug;
+ if (!identifier) {
+ throw new BadRequestError({ message: "Missing domain or orgSlug query parameter" });
+ }
// ensure fresh session state per login attempt
await req.session.regenerate();
- req.session.set<any>("oidcDomain", domain);
+ req.session.set<any>("oidcIdentifier", identifier);
+ req.session.set<any>("oidcIdentifierType", domain ? "domain" : "orgSlug");
if (callbackPort) {
req.session.set<any>("callbackPort", callbackPort);
}
- const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(domain, callbackPort);
+ const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(
+ identifier,
+ domain ? "domain" : "orgSlug",
+ callbackPort
+ );
return (
passport.authenticate(oidcStrategy as Strategy, {
scope: "profile email openid"
@@ -109,9 +121,14 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
method: "GET",
preValidation: [
async (req, res) => {
- const oidcDomain = req.session.get<any>("oidcDomain");
+ const oidcIdentifier = req.session.get<any>("oidcIdentifier");
+ const oidcIdentifierType = req.session.get<any>("oidcIdentifierType") || "domain";
const callbackPort = req.session.get<any>("callbackPort");
- const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(oidcDomain, callbackPort);
+ const oidcStrategy = await server.services.oidc.getOrgAuthStrategy(
+ oidcIdentifier,
+ oidcIdentifierType,
+ callbackPort
+ );
return (
passport.authenticate(oidcStrategy as Strategy, {
@@ -125,6 +142,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
handler: async (req, res) => {
await req.session.destroy();
const passportResult = req.passportUser;
+ const cbPort = passportResult.callbackPort;
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
@@ -134,11 +152,13 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
secure: appCfg.HTTPS_ENABLED
});
addAuthOriginDomainCookie(res);
- return res.redirect(`${appCfg.SITE_URL}/login/select-organization`);
+ return res.redirect(`${appCfg.SITE_URL}/login/select-organization${cbPort ? `?callback_port=${cbPort}` : ""}`);
}
if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
- return res.redirect(`${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`);
+ return res.redirect(
+ `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}${cbPort ? `&callback_port=${cbPort}` : ""}`
+ );
}
throw new Error("Unexpected auth result");
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 9304aff4d0..384ad5a8d9 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -52,7 +52,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
// eslint-disable-next-line
getSamlOptions: async (req, done) => {
try {
- const { samlConfigId, domain } = req.params;
+ const { samlConfigId, domain, orgSlug } = req.params;
let ssoLookupDetails: TGetSamlCfgDTO;
@@ -61,6 +61,11 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
type: "domain",
domain
};
+ } else if (orgSlug) {
+ ssoLookupDetails = {
+ type: "orgSlug",
+ orgSlug
+ };
} else if (samlConfigId) {
ssoLookupDetails = {
type: "ssoId",
@@ -200,7 +205,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
);
server.route({
- url: "/redirect/saml2/organizations/:domain",
+ url: "/redirect/saml2/organizations/domain/:domain",
method: "GET",
config: {
rateLimit: readLimit
@@ -228,6 +233,35 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
handler: () => {}
});
+ server.route({
+ url: "/redirect/saml2/organizations/:orgSlug",
+ method: "GET",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ orgSlug: z.string().trim()
+ }),
+ querystring: z.object({
+ callback_port: z.string().optional()
+ })
+ },
+ preValidation: (req, res) =>
+ (
+ passport.authenticate("saml", {
+ failureRedirect: "/",
+ additionalParams: {
+ RelayState: JSON.stringify({
+ spInitiated: true,
+ callbackPort: req.query.callback_port ?? ""
+ })
+ }
+ } as any) as any
+ )(req, res),
+ handler: () => {}
+ });
+
server.route({
url: "/redirect/saml2/:samlConfigId",
method: "GET",
@@ -282,6 +316,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
) as any, // this is due to zod type difference
handler: (req, res) => {
const passportResult = req.passportUser;
+ const cbPort = passportResult.callbackPort;
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
@@ -291,11 +326,13 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
secure: appCfg.HTTPS_ENABLED
});
addAuthOriginDomainCookie(res);
- return res.redirect(`${appCfg.SITE_URL}/login/select-organization`);
+ return res.redirect(`${appCfg.SITE_URL}/login/select-organization${cbPort ? `?callback_port=${cbPort}` : ""}`);
}
if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
- return res.redirect(`${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}`);
+ return res.redirect(
+ `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}${cbPort ? `&callback_port=${cbPort}` : ""}`
+ );
}
throw new BadRequestError({ message: "Unexpected auth result" });
diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts
index 32133542a3..3b0a2d7539 100644
--- a/backend/src/ee/services/group/group-service.ts
+++ b/backend/src/ee/services/group/group-service.ts
@@ -46,7 +46,7 @@ import { TIdentityGroupMembershipDALFactory } from "./identity-group-membership-
import { TUserGroupMembershipDALFactory } from "./user-group-membership-dal";
type TGroupServiceFactoryDep = {
- userDAL: Pick<TUserDALFactory, "find" | "findUserEncKeyByUserIdsBatch" | "transaction" | "findUserByUsername">;
+ userDAL: Pick<TUserDALFactory, "find" | "findOne" | "findUserEncKeyByUserIdsBatch" | "transaction">;
identityDAL: Pick<TIdentityDALFactory, "findOne" | "find" | "transaction">;
identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find" | "delete" | "insertMany">;
groupDAL: Pick<
@@ -905,10 +905,10 @@ export const groupServiceFactory = ({
details: { missingPermissions: permissionBoundary.missingPermissions }
});
- const usersWithUsername = await userDAL.findUserByUsername(username);
+ const user = await userDAL.findOne({
+ username
+ });
// akhilmhdh: case sensitive email resolution
- const user =
- usersWithUsername?.length > 1 ? usersWithUsername.find((el) => el.username === username) : usersWithUsername?.[0];
if (!user) throw new NotFoundError({ message: `Failed to find user with username ${username}` });
const users = await addUsersToGroupByUserIds({
@@ -1074,10 +1074,7 @@ export const groupServiceFactory = ({
details: { missingPermissions: permissionBoundary.missingPermissions }
});
- const usersWithUsername = await userDAL.findUserByUsername(username);
- // akhilmhdh: case sensitive email resolution
- const user =
- usersWithUsername?.length > 1 ? usersWithUsername.find((el) => el.username === username) : usersWithUsername?.[0];
+ const user = await userDAL.findOne({ username });
if (!user) throw new NotFoundError({ message: `Failed to find user with username ${username}` });
const users = await removeUsersFromGroupByUserIds({
diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts
index bf3f60b141..71b1eb4832 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -80,7 +80,7 @@ export type TFeatureSet = {
pkiEst: boolean;
pkiAcme: false;
pkiScep: false;
- enforceMfa: boolean;
+ enforceMfa: false;
projectTemplates: false;
kmip: false;
gateway: false;
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 674df060c9..a5c4ac517f 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -638,23 +638,32 @@ export const oidcConfigServiceFactory = ({
return oidcCfg;
};
- const getOrgAuthStrategy = async (domain: string, callbackPort?: string) => {
+ const getOrgAuthStrategy = async (
+ identifier: string,
+ identifierType: "domain" | "orgSlug" = "domain",
+ callbackPort?: string
+ ) => {
const appCfg = getConfig();
- const verifiedDomain = await findOrgIdByVerifiedDomain({ domain, emailDomainDAL });
- if (!verifiedDomain) {
- throw new ForbiddenRequestError({
- message: "Failed to authenticate with OIDC SSO"
- });
- }
+ let resolvedOrgId: string;
- const org = await orgDAL.findOne({
- id: verifiedDomain.orgId
- });
+ if (identifierType === "domain") {
+ const verifiedDomain = await findOrgIdByVerifiedDomain({ domain: identifier, emailDomainDAL });
+ if (!verifiedDomain) {
+ throw new ForbiddenRequestError({ message: "Failed to authenticate with OIDC SSO" });
+ }
+ resolvedOrgId = verifiedDomain.orgId;
+ } else {
+ const org = await orgDAL.findOne({ slug: identifier, rootOrgId: null });
+ if (!org) {
+ throw new ForbiddenRequestError({ message: "Failed to authenticate with OIDC SSO" });
+ }
+ resolvedOrgId = org.id;
+ }
const oidcCfg = await getOidc({
type: "internal",
- organizationId: verifiedDomain.orgId
+ organizationId: resolvedOrgId
});
if (!oidcCfg || !oidcCfg.isActive) {
@@ -662,6 +671,7 @@ export const oidcConfigServiceFactory = ({
message: "Failed to authenticate with OIDC SSO"
});
}
+ const org = await orgDAL.findOne({ id: resolvedOrgId });
let issuer: Issuer;
if (oidcCfg.configurationType === OIDCConfigurationType.DISCOVERY_URL) {
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 fa19d7a140..4b4bc05619 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -421,31 +421,24 @@ export const samlConfigServiceFactory = ({
const getSaml: TSamlConfigServiceFactory["getSaml"] = async (dto) => {
let samlConfig: TSamlConfigs | undefined;
if (dto.type === "org") {
- samlConfig = await samlConfigDAL.findOne({ orgId: dto.orgId, isActive: true });
+ 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") {
- // If orgSlug starts with @, treat the rest as a domain name and resolve via verified email domains
const verifiedDomain = await findOrgIdByVerifiedDomain({ domain: dto.domain, emailDomainDAL });
- if (verifiedDomain) {
- const resolvedOrgId = verifiedDomain.orgId;
- samlConfig = await samlConfigDAL.findOne({ orgId: resolvedOrgId, isActive: true });
- } else {
- logger.error(`No verified domain found for domain '${dto.domain}'`);
+ if (!verifiedDomain) {
+ throw new NotFoundError({ message: `No verified domain found for '${dto.domain}'` });
}
-
- // if (!resolvedOrgId) {
- // const org = await orgDAL.findOne({ slug: dto.orgSlug, rootOrgId: null });
- // if (!org) {
- // throw new NotFoundError({
- // message: `Organization with slug '${dto.orgSlug}' not found`
- // });
- // }
- // resolvedOrgId = org.id;
- // }
+ 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
diff --git a/backend/src/ee/services/saml-config/saml-config-types.ts b/backend/src/ee/services/saml-config/saml-config-types.ts
index 36f6ba63dc..059fee350d 100644
--- a/backend/src/ee/services/saml-config/saml-config-types.ts
+++ b/backend/src/ee/services/saml-config/saml-config-types.ts
@@ -44,6 +44,10 @@ export type TGetSamlCfgDTO =
type: "domain";
domain: string;
}
+ | {
+ type: "orgSlug";
+ orgSlug: string;
+ }
| {
type: "ssoId";
id: string;
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index 25530bc3b6..9b64e72647 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -383,6 +383,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
const isAdminLogin = req.session.get("isAdminLogin");
await req.session.destroy();
const passportResult = req.passportUser;
+ const cbPort = passportResult.callbackPort;
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
@@ -392,18 +393,27 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
secure: appCfg.HTTPS_ENABLED
});
addAuthOriginDomainCookie(res);
+ const sessionParams = [
+ isAdminLogin ? `isAdminLogin=${isAdminLogin}` : "",
+ cbPort ? `callback_port=${cbPort}` : ""
+ ]
+ .filter(Boolean)
+ .join("&");
return res.redirect(
- `${appCfg.SITE_URL}/login/select-organization${isAdminLogin ? `?isAdminLogin=${isAdminLogin}` : ""}`
+ `${appCfg.SITE_URL}/login/select-organization${sessionParams ? `?${sessionParams}` : ""}`
);
}
if (passportResult.result === ProviderAuthResult.SIGNUP_REQUIRED) {
const serverCfg = await getServerCfg();
- return res.redirect(
- `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent(passportResult.signupToken)}${
- serverCfg.defaultAuthOrgId && !appCfg.isCloud ? `&defaultOrgAllowed=true` : ""
- }`
- );
+ const signupParams = [
+ `token=${encodeURIComponent(passportResult.signupToken)}`,
+ serverCfg.defaultAuthOrgId && !appCfg.isCloud ? "defaultOrgAllowed=true" : "",
+ cbPort ? `callback_port=${cbPort}` : ""
+ ]
+ .filter(Boolean)
+ .join("&");
+ return res.redirect(`${appCfg.SITE_URL}/signup/sso?${signupParams}`);
}
throw new BadRequestError({ message: "Unexpected auth result" });
diff --git a/backend/src/services/account-recovery/account-recovery-service.ts b/backend/src/services/account-recovery/account-recovery-service.ts
index 859593c82a..18f6610f6b 100644
--- a/backend/src/services/account-recovery/account-recovery-service.ts
+++ b/backend/src/services/account-recovery/account-recovery-service.ts
@@ -32,9 +32,7 @@ export const accountRecoveryServiceFactory = ({
*/
const sendRecoveryEmail = async (email: string) => {
const sendEmail = async () => {
- const users = await userDAL.findUserByUsername(email);
- // akhilmhdh: case sensitive email resolution
- const user = users?.length > 1 ? users.find((el) => el.username === email) : users?.[0];
+ const user = await userDAL.findOne({ username: email });
if (!user) throw new BadRequestError({ message: "Failed to find user data" });
if (user && user.isAccepted) {
@@ -86,11 +84,7 @@ export const accountRecoveryServiceFactory = ({
*/
const verifyRecoveryEmail = async (email: string, code: string) => {
const cfg = getConfig();
- const users = await userDAL.findUserByUsername(email);
- // akhilmhdh: case sensitive email resolution
- const user = users?.length > 1 ? users.find((el) => el.username === email) : users?.[0];
- if (!user) throw new BadRequestError({ message: "Failed to find user data" });
- // ignore as user is not found to avoid an outside entity to identify infisical registered accounts
+ const user = await userDAL.findOne({ username: email });
if (!user || (user && !user.isAccepted)) {
throw new Error("Failed email verification for pass reset");
}
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 6f67caed7a..1ea885b114 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -26,6 +26,7 @@ import {
import { getMinExpiresIn, removeTrailingSlash } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import { validateEmail } from "@app/lib/validator";
import { getUserAgentType } from "@app/server/plugins/audit-log";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
@@ -340,7 +341,7 @@ export const authLoginServiceFactory = ({
{ expiresIn: appCfg.JWT_SIGNUP_LIFETIME }
);
- return { result: ProviderAuthResult.SIGNUP_REQUIRED, signupToken } as const;
+ return { result: ProviderAuthResult.SIGNUP_REQUIRED, signupToken, callbackPort } as const;
}
// Step 2: For org-scoped IdP flows with MFA, issue tokens without org scope
@@ -359,7 +360,7 @@ export const authLoginServiceFactory = ({
authMethod
});
- return { result: ProviderAuthResult.SESSION, tokens } as const;
+ return { result: ProviderAuthResult.SESSION, tokens, callbackPort } as const;
}
}
}
@@ -386,7 +387,7 @@ export const authLoginServiceFactory = ({
);
}
- return { result: ProviderAuthResult.SESSION, tokens } as const;
+ return { result: ProviderAuthResult.SESSION, tokens, callbackPort } as const;
};
/*
@@ -839,6 +840,8 @@ export const authLoginServiceFactory = ({
userAgent
}: TOauthLoginDTO) => {
const aliasType = authMethodToAliasType(authMethod);
+ const normalizedEmail = email.trim().toLowerCase();
+ validateEmail(normalizedEmail);
// Step 1: Look up user by provider alias (stable, immutable ID)
let user: TUsers | undefined;
@@ -850,7 +853,7 @@ export const authLoginServiceFactory = ({
// Step 2: Fall back to email lookup for existing users without an alias yet
if (!user) {
- user = await userDAL.findOne({ username: email });
+ user = await userDAL.findOne({ username: normalizedEmail });
if (user) {
isNewAlias = true;
}
@@ -925,8 +928,8 @@ export const authLoginServiceFactory = ({
user = await userDAL.transaction(async (tx) => {
const newUser = await userDAL.create(
{
- username: email.trim().toLowerCase(),
- email: email.trim().toLowerCase(),
+ username: normalizedEmail,
+ email: normalizedEmail,
isEmailVerified: false,
isAccepted: false,
firstName,
@@ -957,7 +960,7 @@ export const authLoginServiceFactory = ({
const membership = await membershipUserDAL.create(
{
actorUserId: newUser.id,
- inviteEmail: email,
+ inviteEmail: normalizedEmail,
scopeOrgId: orgId,
scope: AccessScope.Organization,
status: OrgMembershipStatus.Accepted,
@@ -981,7 +984,7 @@ export const authLoginServiceFactory = ({
userId: newUser.id,
aliasType,
externalId: providerUserId,
- emails: [email],
+ emails: [normalizedEmail],
orgId: orgId || null,
isEmailVerified: false
},
@@ -1002,10 +1005,8 @@ export const authLoginServiceFactory = ({
});
}
- // Sync email/username if the provider email has changed (user found by alias)
- const normalizedProviderEmail = email.trim().toLowerCase();
- if (existingAlias && user.email !== normalizedProviderEmail) {
- const conflictingUser = await userDAL.findOne({ username: normalizedProviderEmail });
+ if (existingAlias && user.email !== normalizedEmail) {
+ const conflictingUser = await userDAL.findOne({ username: normalizedEmail });
if (conflictingUser && conflictingUser.id !== user.id) {
throw new BadRequestError({
message:
@@ -1018,8 +1019,8 @@ export const authLoginServiceFactory = ({
const updatedUser = await userDAL.updateById(
user!.id,
{
- username: normalizedProviderEmail,
- email: normalizedProviderEmail,
+ username: normalizedEmail,
+ email: normalizedEmail,
isGitHubVerified: authMethod !== AuthMethod.GITHUB && user?.isGitHubVerified,
isGoogleVerified: authMethod !== AuthMethod.GOOGLE && user?.isGoogleVerified,
isGitLabVerified: authMethod !== AuthMethod.GITLAB && user?.isGitLabVerified
@@ -1030,7 +1031,7 @@ export const authLoginServiceFactory = ({
await userAliasDAL.updateById(
existingAlias.id,
{
- emails: [normalizedProviderEmail]
+ emails: [normalizedEmail]
},
tx
);
diff --git a/backend/src/services/auth/auth-login-type.ts b/backend/src/services/auth/auth-login-type.ts
index d7737da29b..ece19c462f 100644
--- a/backend/src/services/auth/auth-login-type.ts
+++ b/backend/src/services/auth/auth-login-type.ts
@@ -63,6 +63,6 @@ export type TProcessProviderCallbackDTO = {
};
export type TProviderAuthResult =
- | { result: ProviderAuthResult.SESSION; tokens: { access: string; refresh: string } }
- | { result: ProviderAuthResult.MFA_REQUIRED; mfaToken: string; mfaMethod: MfaMethod }
- | { result: ProviderAuthResult.SIGNUP_REQUIRED; signupToken: string };
+ | { result: ProviderAuthResult.SESSION; tokens: { access: string; refresh: string }; callbackPort?: string }
+ | { result: ProviderAuthResult.MFA_REQUIRED; mfaToken: string; mfaMethod: MfaMethod; callbackPort?: string }
+ | { result: ProviderAuthResult.SIGNUP_REQUIRED; signupToken: string; callbackPort?: string };
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index ff9e86cf3a..8cf3b92250 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -1,8 +1,8 @@
-import { AccessScope } from "@app/db/schemas";
+import { AccessScope, OrgMembershipStatus } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
-import { isDisposableEmail } from "@app/lib/validator";
+import { isDisposableEmail, validateEmail } from "@app/lib/validator";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
@@ -43,6 +43,7 @@ export const authSignupServiceFactory = ({
// first step of signup. create user and send email
const beginEmailSignupProcess = async (email: string) => {
const sanitizedEmail = email.trim().toLowerCase();
+ validateEmail(email);
const isEmailInvalid = await isDisposableEmail(sanitizedEmail);
if (isEmailInvalid) {
throw new Error("Provided a disposable email");
@@ -94,6 +95,7 @@ export const authSignupServiceFactory = ({
const verifyEmailSignup = async (email: string, code: string) => {
const sanitizedEmail = email.trim().toLowerCase();
+ validateEmail(email);
const user = await userDAL.findOne({ username: sanitizedEmail });
// Always call validateTokenForUser so the response time includes
@@ -231,6 +233,19 @@ export const authSignupServiceFactory = ({
userUpdates.isAccepted = true;
}
+ if (userAlias?.orgId) {
+ await orgDAL.updateMembership(
+ {
+ actorUserId: user.id,
+ scope: AccessScope.Organization,
+ scopeOrgId: userAlias.orgId
+ },
+ {
+ status: OrgMembershipStatus.Accepted
+ }
+ );
+ }
+
user = await userDAL.updateById(user.id, userUpdates);
authMethod = decodedToken.authMethod;
}
diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.ts
index 60918adffc..bac3bea535 100644
--- a/backend/src/services/membership-user/membership-user-service.ts
+++ b/backend/src/services/membership-user/membership-user-service.ts
@@ -13,7 +13,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
import { ms } from "@app/lib/ms";
import { SearchResourceOperators } from "@app/lib/search-resource/search";
-import { isDisposableEmail } from "@app/lib/validator";
+import { isDisposableEmail, validateEmail } from "@app/lib/validator";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { AuthMethod } from "../auth/auth-type";
@@ -103,35 +103,37 @@ export const membershipUserServiceFactory = ({
const $getUsers = async (usernames: string[]) => {
const existingUsers = await userDAL.find({ $in: { username: usernames } });
if (existingUsers.length !== usernames.length) {
- const newUserEmails = usernames.filter(
- (inviteeEmail) => !existingUsers.find((el) => el.username === inviteeEmail)
- );
+ const newUserEmails = usernames
+ .filter((inviteeEmail) => !existingUsers.find((el) => el.username === inviteeEmail))
+ .map((el) => el.toLowerCase());
+
+ const invalidEmails = newUserEmails.filter((el) => {
+ try {
+ validateEmail(el);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+ if (invalidEmails.length > 0) {
+ throw new BadRequestError({ message: `Invalid emails: ${invalidEmails.join(", ")}` });
+ }
+
await userDAL.transaction(async (tx) => {
for await (const inviteeEmail of newUserEmails) {
- const usersByUsername = await userDAL.findUserByUsername(inviteeEmail, tx);
- let inviteeUser =
- usersByUsername?.length > 1
- ? usersByUsername.find((el) => el.username === inviteeEmail)
- : usersByUsername?.[0];
-
+ let inviteeUser = await userDAL.findOne({ username: inviteeEmail }, tx);
// if the user doesn't exist we create the user with the email
if (!inviteeUser) {
- // TODO(carlos): will be removed once the function receives usernames instead of emails
- const usersByEmail = await userDAL.findUserByEmail(inviteeEmail, tx);
- if (usersByEmail?.length === 1) {
- [inviteeUser] = usersByEmail;
- } else {
- inviteeUser = await userDAL.create(
- {
- isAccepted: false,
- email: inviteeEmail,
- username: inviteeEmail,
- authMethods: [AuthMethod.EMAIL],
- isGhost: false
- },
- tx
- );
- }
+ inviteeUser = await userDAL.create(
+ {
+ isAccepted: false,
+ email: inviteeEmail,
+ username: inviteeEmail,
+ authMethods: [AuthMethod.EMAIL],
+ isGhost: false
+ },
+ tx
+ );
}
existingUsers.push(inviteeUser);
@@ -211,7 +213,6 @@ export const membershipUserServiceFactory = ({
message: "Disposable emails are not allowed"
});
}
-
const scopeDatabaseFields = factory.getScopeDatabaseFields(dto.scopeData);
const users = await $getUsers(dto.data.usernames);
const existingMemberships = await membershipUserDAL.find({
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 47046526ae..c4cbde0a53 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -945,9 +945,7 @@ export const orgServiceFactory = ({
* magic link and issue a temporary signup token for user to complete setting up their account
*/
const verifyUserToOrg = async ({ orgId, email, code }: TVerifyUserToOrgDTO) => {
- const usersByUsername = await userDAL.findUserByUsername(email);
- const user =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0];
+ const user = await userDAL.findOne({ username: email });
if (!user) {
throw new NotFoundError({ message: "User not found" });
}
diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts
index 177352b4f2..7a076afd1b 100644
--- a/backend/src/services/super-admin/super-admin-service.ts
+++ b/backend/src/services/super-admin/super-admin-service.ts
@@ -23,7 +23,7 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
-import { isDisposableEmail } from "@app/lib/validator";
+import { isDisposableEmail, validateEmail } from "@app/lib/validator";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
@@ -780,6 +780,21 @@ export const superAdminServiceFactory = ({
});
}
+ const invalidEmailFormats = inviteAdminEmails.filter((email) => {
+ try {
+ validateEmail(email);
+ return false;
+ } catch {
+ return true;
+ }
+ });
+ if (invalidEmailFormats.length > 0) {
+ throw new BadRequestError({
+ message: `Invalid email formats: ${invalidEmailFormats.join(", ")}`,
+ name: "InviteUser"
+ });
+ }
+
const { organization, users: usersToEmail } = await orgDAL.transaction(async (tx) => {
const org = await orgService.createOrganization(
{
@@ -792,30 +807,19 @@ export const superAdminServiceFactory = ({
const users: Pick<TUsers, "id" | "firstName" | "lastName" | "email" | "username" | "isAccepted">[] = [];
for await (const inviteeEmail of inviteAdminEmails) {
- const usersByUsername = await userDAL.findUserByUsername(inviteeEmail, tx);
- let inviteeUser =
- usersByUsername?.length > 1
- ? usersByUsername.find((el) => el.username === inviteeEmail)
- : usersByUsername?.[0];
-
+ let inviteeUser = await userDAL.findOne({ username: inviteeEmail }, tx);
// if the user doesn't exist we create the user with the email
if (!inviteeUser) {
- // TODO(carlos): will be removed once the function receives usernames instead of emails
- const usersByEmail = await userDAL.findUserByEmail(inviteeEmail, tx);
- if (usersByEmail?.length === 1) {
- [inviteeUser] = usersByEmail;
- } else {
- inviteeUser = await userDAL.create(
- {
- isAccepted: false,
- email: inviteeEmail,
- username: inviteeEmail,
- authMethods: [AuthMethod.EMAIL],
- isGhost: false
- },
- tx
- );
- }
+ inviteeUser = await userDAL.create(
+ {
+ isAccepted: false,
+ email: inviteeEmail,
+ username: inviteeEmail,
+ authMethods: [AuthMethod.EMAIL],
+ isGhost: false
+ },
+ tx
+ );
}
const inviteeUserId = inviteeUser?.id;
diff --git a/backend/src/services/user/user-dal.ts b/backend/src/services/user/user-dal.ts
index f9be787027..6de06d6fa4 100644
--- a/backend/src/services/user/user-dal.ts
+++ b/backend/src/services/user/user-dal.ts
@@ -19,18 +19,6 @@ export type TUserDALFactory = ReturnType<typeof userDALFactory>;
export const userDALFactory = (db: TDbClient) => {
const userOrm = ormify(db, TableName.Users);
- const findUserByUsername = async (username: string, tx?: Knex) =>
- (tx || db.replicaNode())(TableName.Users).whereRaw('lower("username") = :username', {
- username: username.toLowerCase()
- });
-
- const findUserByEmail = async (email: string, tx?: Knex) =>
- (tx || db.replicaNode())(TableName.Users)
- .whereRaw('lower("email") = :email', { email: email.toLowerCase() })
- .where({
- isEmailVerified: true
- });
-
const getUsersByFilter = async ({
limit,
offset,
@@ -259,7 +247,6 @@ export const userDALFactory = (db: TDbClient) => {
return {
...userOrm,
- findUserByUsername,
findUserEncKeyByUsername,
findUserEncKeyByUserIdsBatch,
findUserEncKeyByUserId,
@@ -271,7 +258,6 @@ export const userDALFactory = (db: TDbClient) => {
findOneUserAction,
createUserAction,
getUsersByFilter,
- findAllMyAccounts,
- findUserByEmail
+ findAllMyAccounts
};
};
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index bb1906b1d4..8750412ddb 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -7,6 +7,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { validateEmail } from "@app/lib/validator";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -23,7 +24,7 @@ type TUserServiceFactoryDep = {
userDAL: Pick<
TUserDALFactory,
| "find"
- | "findUserByUsername"
+ | "findOne"
| "findById"
| "transaction"
| "updateById"
@@ -65,10 +66,9 @@ export const userServiceFactory = ({
};
if (authTokenType !== AuthTokenType.SIGNUP_TOKEN) throw new BadRequestError({ name: "Invalid auth token type" });
- // akhilmhdh: case sensitive email resolution
- const users = await userDAL.findUserByUsername(username);
- const user = users?.length > 1 ? users.find((el) => el.username === username) : users?.[0];
+ const user = await userDAL.findOne({ username });
if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
+
let { isEmailVerified } = user;
if (aliasId) {
const userAlias = await userAliasDAL.findOne({ userId: user.id, aliasType: authType, id: aliasId });
@@ -99,20 +99,7 @@ export const userServiceFactory = ({
const verifyEmailVerificationCode = async (username: string, code: string) => {
// akhilmhdh: case sensitive email resolution
- const usersByusername = await userDAL.findUserByUsername(username);
-
- logger.info(
- usersByusername.map((user) => ({
- id: user.id,
- email: user.email,
- username: user.username,
- isEmailVerified: user.isEmailVerified
- })),
- `Verify email users: [username=${username}]`
- );
-
- const user =
- usersByusername?.length > 1 ? usersByusername.find((el) => el.username === username) : usersByusername?.[0];
+ const user = await userDAL.findOne({ username });
if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
if (!user.email)
throw new BadRequestError({ name: "Failed to verify email verification code due to no email on user" });
@@ -201,6 +188,8 @@ export const userServiceFactory = ({
const requestEmailChangeOTP = async ({ userId, newEmail }: TUpdateUserEmailDTO) => {
const startTime = new Date();
+ const normalizedNewEmail = newEmail.toLowerCase();
+ validateEmail(normalizedNewEmail);
const changeEmailOTP = await userDAL.transaction(async (tx) => {
const user = await userDAL.findById(userId, tx);
if (!user)
@@ -219,8 +208,7 @@ export const userServiceFactory = ({
}
// Silently check if another user already has this email - don't send OTP if email is taken
- const existingUsers = await userDAL.findUserByUsername(newEmail.toLowerCase(), tx);
- const existingUser = existingUsers?.find((u) => u.id !== userId);
+ const existingUser = await userDAL.findOne({ username: newEmail }, tx);
if (!existingUser) {
// Generate 6-digit OTP
const otpCode = await tokenService.createTokenForUser({
@@ -253,7 +241,13 @@ export const userServiceFactory = ({
return changeEmailOTP;
};
- const updateUserEmail = async ({ userId, newEmail, otpCode }: TUpdateUserEmailDTO & { otpCode: string }) => {
+ const updateUserEmail = async ({
+ userId,
+ newEmail: unsanitizedEmail,
+ otpCode
+ }: TUpdateUserEmailDTO & { otpCode: string }) => {
+ const newEmail = unsanitizedEmail.toLowerCase();
+ validateEmail(newEmail);
const changedUser = await userDAL.transaction(async (tx) => {
const user = await userDAL.findById(userId, tx);
if (!user) throw new NotFoundError({ message: `User with ID '${userId}' not found`, name: "UpdateUserEmail" });
@@ -289,8 +283,7 @@ export const userServiceFactory = ({
}
// Final check if another user has this email
- const existingUsers = await userDAL.findUserByUsername(newEmail.toLowerCase(), tx);
- const existingUser = existingUsers?.find((u) => u.id !== userId);
+ const existingUser = await userDAL.findOne({ username: newEmail }, tx);
if (existingUser) {
throw new BadRequestError({ message: "Email is no longer available", name: "UpdateUserEmail" });
}
@@ -462,9 +455,7 @@ export const userServiceFactory = ({
const listUserGroups = async ({ username, actorOrgId, actor, actorId, actorAuthMethod }: TListUserGroupsDTO) => {
// akhilmhdh: case sensitive email resolution
- const usersByusername = await userDAL.findUserByUsername(username);
- const user =
- usersByusername?.length > 1 ? usersByusername.find((el) => el.username === username) : usersByusername?.[0];
+ const user = await userDAL.findOne({ username });
if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
// This makes it so the user can always read information about themselves, but no one else if they don't have the Members Read permission.
diff --git a/docs/docs.json b/docs/docs.json
index 9f06628f9f..8fd9883e1f 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -268,7 +268,8 @@
"documentation/platform/scim/pingone",
"documentation/platform/scim/group-mappings"
]
- }
+ },
+ "documentation/platform/email-domain"
]
},
{
diff --git a/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx b/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx
index 164775f019..b8619a72be 100644
--- a/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx
+++ b/frontend/src/pages/auth/LoginPage/components/SSOStep/SSOStep.tsx
@@ -44,7 +44,7 @@ export const SSOStep = ({ setSection, type }: Props) => {
saveLastLogin({ method: matchingMethod, orgSlug: ssoEmail });
if (type === "SAML") {
- window.location.href = `/api/v1/sso/redirect/saml2/organizations/${identifier}${
+ window.location.href = `/api/v1/sso/redirect/saml2/organizations/domain/${identifier}${
callbackPort ? `?callback_port=${callbackPort}` : ""
}`;
} else {