Skip to content

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

feat: made first review changes

=208b0f6e2565
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 848da63ce6..fb4ad587fa 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -72,7 +72,7 @@ import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/app
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { TAuthPasswordFactory } from "@app/services/auth/auth-password-service";
import { TAuthSignupFactory } from "@app/services/auth/auth-signup-service";
-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+import { ActorAuthMethod, ActorType, TProviderAuthCallback } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TCertificateServiceFactory } from "@app/services/certificate/certificate-service";
import { TCaAutoRenewalQueueFactory } from "@app/services/certificate-authority/ca-auto-renewal-queue";
@@ -227,9 +227,7 @@ declare module "fastify" {
rootOrgId: string;
};
rateLimits: RateLimitConfiguration;
- // passport data — result from processProviderCallback
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- passportUser: any;
+ passportUser: TProviderAuthCallback;
passportMachineIdentity: {
identityId: string;
user: {
diff --git a/backend/src/db/migrations/20260330072924_auth-revamp.ts b/backend/src/db/migrations/20260330072924_auth-revamp.ts
index c6cdc08fcc..728d52be8d 100644
--- a/backend/src/db/migrations/20260330072924_auth-revamp.ts
+++ b/backend/src/db/migrations/20260330072924_auth-revamp.ts
@@ -34,7 +34,6 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
t.string("domain", 255).notNullable();
- t.string("parentDomain", 255);
// Verification details
t.string("verificationMethod", 50).notNullable().defaultTo("dns-txt");
@@ -51,7 +50,6 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true);
// Indexes
- t.index("parentDomain");
t.index("orgId");
t.index("domain");
diff --git a/backend/src/db/migrations/20260404140728_username-merge.ts b/backend/src/db/migrations/20260404140728_username-merge.ts
index 95f41d4407..b0fd28ace1 100644
--- a/backend/src/db/migrations/20260404140728_username-merge.ts
+++ b/backend/src/db/migrations/20260404140728_username-merge.ts
@@ -119,9 +119,12 @@ export async function up(knex: Knex): Promise<void> {
await knex(ref.table_name)
.whereIn(ref.column_name, loserIds)
.update({ [ref.column_name]: winner.id });
- } catch {
- // Unique constraint violation — some rows couldn't be reassigned.
+ } catch (err: unknown) {
+ // Unique constraint violation (23505) — some rows couldn't be reassigned.
// That's fine — they'll be cleaned up by CASCADE when the loser user is deleted.
+ if ((err as { code?: string })?.code !== "23505") {
+ throw err;
+ }
}
}
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
index b462c82a3f..6352e58b82 100644
--- a/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
+++ b/backend/src/db/migrations/20260404140729_seed-email-domains-from-sso.ts
@@ -2,7 +2,8 @@
import crypto from "node:crypto";
import { Knex } from "knex";
-import { getDomain } from "tldts";
+
+import { isValidEmailDomain } from "@app/lib/validator/validate-email";
import { TableName } from "../schemas";
@@ -112,7 +113,7 @@ export async function up(knex: Knex): Promise<void> {
const { org_id: orgId, domain, alias_count: aliasCount } = row;
// eslint-disable-next-line no-continue
if (!domain || domain.length < 3) continue;
- const isDomain = getDomain(domain);
+ const isDomain = isValidEmailDomain(domain);
// eslint-disable-next-line no-continue
if (!isDomain) continue;
diff --git a/backend/src/db/schemas/email-domains.ts b/backend/src/db/schemas/email-domains.ts
index a747807cee..c921399fd3 100644
--- a/backend/src/db/schemas/email-domains.ts
+++ b/backend/src/db/schemas/email-domains.ts
@@ -11,7 +11,6 @@ export const EmailDomainsSchema = z.object({
id: z.string().uuid(),
orgId: z.string().uuid(),
domain: z.string(),
- parentDomain: z.string().nullable().optional(),
verificationMethod: z.string().default("dns-txt"),
verificationCode: z.string(),
verificationRecordName: z.string(),
diff --git a/backend/src/ee/routes/v1/assume-privilege-router.ts b/backend/src/ee/routes/v1/assume-privilege-router.ts
index 5ee5723fd8..5497137a30 100644
--- a/backend/src/ee/routes/v1/assume-privilege-router.ts
+++ b/backend/src/ee/routes/v1/assume-privilege-router.ts
@@ -43,7 +43,7 @@ export const registerAssumePrivilegeRouter = async (server: FastifyZodProvider)
const appCfg = getConfig();
void res.setCookie("infisical-project-assume-privileges", payload.assumePrivilegesToken, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 3600 // 1 hour in seconds
@@ -95,7 +95,7 @@ export const registerAssumePrivilegeRouter = async (server: FastifyZodProvider)
const appCfg = getConfig();
void res.setCookie("infisical-project-assume-privileges", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
expires: new Date(0)
diff --git a/backend/src/ee/routes/v1/email-domain-router.ts b/backend/src/ee/routes/v1/email-domain-router.ts
index 9cfaca5d75..59b354a50d 100644
--- a/backend/src/ee/routes/v1/email-domain-router.ts
+++ b/backend/src/ee/routes/v1/email-domain-router.ts
@@ -51,20 +51,6 @@ export const registerEmailDomainRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
emailDomain: EmailDomainsSchema
- // existingSubdomains: z.array(
- // EmailDomainsSchema.pick({
- // id: true,
- // domain: true,
- // orgId: true
- // })
- // ),
- // existingParentDomains: z.array(
- // EmailDomainsSchema.pick({
- // id: true,
- // domain: true,
- // orgId: true
- // })
- // )
})
}
},
diff --git a/backend/src/ee/routes/v1/ldap-router.ts b/backend/src/ee/routes/v1/ldap-router.ts
index d94dbf4808..8771e2b89b 100644
--- a/backend/src/ee/routes/v1/ldap-router.ts
+++ b/backend/src/ee/routes/v1/ldap-router.ts
@@ -6,8 +6,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-argument */
// All the any rules are disabled because passport typesense with fastify is really poor
-import { IncomingMessage } from "node:http";
-
import { Authenticator } from "@fastify/passport";
import { requestContext } from "@fastify/request-context";
import fastifySession from "@fastify/session";
@@ -56,9 +54,10 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
new LdapStrategy(
getLdapPassportOpts as any,
// eslint-disable-next-line
- async (req: IncomingMessage, user, cb) => {
+ async (req, user, cb) => {
try {
if (!user.mail) throw new BadRequestError({ message: "Invalid request. Missing mail attribute on user." });
+ const fastifyReq = req as unknown as FastifyRequest;
const ldapConfig = (req as unknown as FastifyRequest).ldapConfig as TLDAPConfig;
let groups: { dn: string; cn: string }[] | undefined;
@@ -78,6 +77,20 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
const externalId = ldapConfig.uniqueUserAttribute ? user[ldapConfig.uniqueUserAttribute] : user.uidNumber;
const username = ldapConfig.uniqueUserAttribute ? externalId : user.uid;
+ // had to put any due to passport ts issue with signature
+ let callbackPort: number | undefined;
+ try {
+ const relayStatePayload =
+ typeof fastifyReq?.body === "object"
+ ? (fastifyReq.body as { RelayState?: string })?.RelayState
+ : undefined;
+ if (relayStatePayload && Buffer.byteLength(relayStatePayload) <= 1024) {
+ callbackPort = Number(JSON.parse(relayStatePayload)?.callbackPort);
+ }
+ } catch (err) {
+ logger.error(err, "Relay state parsing failed");
+ }
+
const loginResult = await server.services.ldap.ldapLogin({
externalId,
username,
@@ -88,7 +101,7 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
groups,
ip: requestContext.get("ip") || "",
userAgent: requestContext.get("userAgent") || "",
- relayState: ((req as unknown as FastifyRequest).body as { RelayState?: string }).RelayState,
+ callbackPort: callbackPort || undefined,
orgId: (req as unknown as FastifyRequest).ldapConfig.organization
});
@@ -126,7 +139,7 @@ export const registerLdapRouter = async (server: FastifyZodProvider) => {
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index b8e062777b..d7b730a300 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -147,7 +147,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 384ad5a8d9..6cb46de95d 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -10,6 +10,7 @@ import { Authenticator } from "@fastify/passport";
import { requestContext } from "@fastify/request-context";
import fastifySession from "@fastify/session";
import { MultiSamlStrategy } from "@node-saml/passport-saml";
+import { AuthenticateOptions } from "@node-saml/passport-saml/lib/types";
import { FastifyRequest } from "fastify";
import { z } from "zod";
@@ -24,7 +25,7 @@ import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { SanitizedSamlConfigSchema } from "@app/server/routes/sanitizedSchema/directory-config";
-import { AuthMode, ProviderAuthResult } from "@app/services/auth/auth-type";
+import { AuthMode, ProviderAuthResult, TProviderAuthCallback } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
type TSAMLConfig = {
@@ -158,12 +159,23 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
})
.filter((el) => el.key && !["email", "firstName", "lastName"].includes(el.key));
+ let callbackPort: number | undefined;
+ try {
+ const relayStatePayload =
+ typeof req?.body === "object" ? (req.body as { RelayState?: string })?.RelayState : undefined;
+ if (relayStatePayload && Buffer.byteLength(relayStatePayload) <= 1024) {
+ callbackPort = Number(JSON.parse(relayStatePayload)?.callbackPort);
+ }
+ } catch (err) {
+ logger.error(err, "Relay state parsing failed");
+ }
+
const loginResult = await server.services.saml.samlLogin({
externalId: profile.nameID,
email: email.toLowerCase(),
firstName,
lastName: lastName as string,
- relayState: (req.body as { RelayState?: string }).RelayState,
+ callbackPort,
authProvider: (req as unknown as FastifyRequest).ssoConfig?.authProvider,
orgId: (req as unknown as FastifyRequest).ssoConfig?.orgId,
ip: requestContext.get("ip") || "",
@@ -174,9 +186,9 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": email.toLowerCase(),
- "infisical.user.id": loginResult.user.id,
- "infisical.organization.id": loginResult.organization.id,
- "infisical.organization.name": loginResult.organization.name,
+ "infisical.user.id": loginResult.userId,
+ "infisical.organization.id": loginResult.orgId,
+ "infisical.organization.name": loginResult.orgName,
"infisical.auth.method": AuthAttemptAuthMethod.SAML,
"infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
"client.address": requestContext.get("ip"),
@@ -228,7 +240,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
callbackPort: req.query.callback_port ?? ""
})
}
- } as any) as any
+ } as AuthenticateOptions) as any
)(req, res),
handler: () => {}
});
@@ -257,7 +269,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
callbackPort: req.query.callback_port ?? ""
})
}
- } as any) as any
+ } as AuthenticateOptions) as any
)(req, res),
handler: () => {}
});
@@ -286,7 +298,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
callbackPort: req.query.callback_port ?? ""
})
}
- } as any) as any
+ } as AuthenticateOptions) as any
)(req, res),
handler: () => {}
});
@@ -311,7 +323,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
if (err) {
throw new BadRequestError({ message: `Saml authentication failed. ${err?.message}`, error: err });
}
- req.passportUser = user;
+ req.passportUser = user as TProviderAuthCallback;
}
) as any, // this is due to zod type difference
handler: (req, res) => {
@@ -321,7 +333,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/ee/services/email-domain/email-domain-dal.ts b/backend/src/ee/services/email-domain/email-domain-dal.ts
index 6812edc827..45997e217b 100644
--- a/backend/src/ee/services/email-domain/email-domain-dal.ts
+++ b/backend/src/ee/services/email-domain/email-domain-dal.ts
@@ -1,5 +1,5 @@
import { TDbClient } from "@app/db";
-import { TableName, TEmailDomains } from "@app/db/schemas";
+import { TableName } from "@app/db/schemas";
import { ormify } from "@app/lib/knex";
export type TEmailDomainDALFactory = ReturnType<typeof emailDomainDALFactory>;
@@ -7,36 +7,5 @@ export type TEmailDomainDALFactory = ReturnType<typeof emailDomainDALFactory>;
export const emailDomainDALFactory = (db: TDbClient) => {
const emailDomainOrm = ormify(db, TableName.EmailDomains);
- // Find all verified subdomains under a parent domain at all nesting levels, excluding the given org
- const findVerifiedSubdomains = async (parentDomain: string, excludeOrgId: string): Promise<TEmailDomains[]> => {
- const results = await db
- .replicaNode()(TableName.EmailDomains)
- .where("status", "verified")
- .where("orgId", "!=", excludeOrgId)
- .andWhere("domain", "like", `%.${parentDomain}`);
-
- return results;
- };
-
- // Find all verified parent domains for a given subdomain, excluding the given org
- // E.g., for "a.b.company.com", finds verified records for "b.company.com", "company.com"
- const findVerifiedParentDomains = async (domain: string, excludeOrgId: string): Promise<TEmailDomains[]> => {
- const parts = domain.split(".");
- const parentCandidates: string[] = [];
- for (let i = 1; i < parts.length - 1; i += 1) {
- parentCandidates.push(parts.slice(i).join("."));
- }
-
- if (parentCandidates.length === 0) return [];
-
- const results = await db
- .replicaNode()(TableName.EmailDomains)
- .where("status", "verified")
- .where("orgId", "!=", excludeOrgId)
- .whereIn("domain", parentCandidates);
-
- return results;
- };
-
- return { ...emailDomainOrm, findVerifiedSubdomains, findVerifiedParentDomains };
+ return emailDomainOrm;
};
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 0e8d710163..2dd348d771 100644
--- a/backend/src/ee/services/email-domain/email-domain-fns.ts
+++ b/backend/src/ee/services/email-domain/email-domain-fns.ts
@@ -1,5 +1,3 @@
-import { getHostname } from "tldts";
-
// import { AccessScope, TableName } from "@app/db/schemas";
import { BadRequestError } from "@app/lib/errors";
import { TOrgDALFactory } from "@app/services/org/org-dal";
@@ -10,10 +8,6 @@ import { EmailDomainStatus } from "./email-domain-types";
/**
* Given an email and orgId, verifies the org is allowed to manage a user with this email.
*
- * Two-tier check:
- * 1. If the email domain has a verified record → it must belong to this org, else throw.
- * 2. If no verified domain → if a userId is provided, check if that user exists in another org.
- * If so, throw — the org must verify the domain first to manage cross-org users.
*/
export const verifyEmailDomainOwnership = async ({
email,
@@ -28,13 +22,13 @@ export const verifyEmailDomainOwnership = async ({
orgDAL: Pick<TOrgDALFactory, "findMembership">;
userId?: string;
}) => {
- const emailDomain = getHostname(email);
+ const emailDomain = email.split("@")?.[1];
if (!emailDomain) throw new BadRequestError({ message: "Invalid email address" });
- // Tier 1: Check verified domain ownership
const verifiedDomain = await emailDomainDAL.findOne({
- domain: emailDomain,
- status: EmailDomainStatus.Verified
+ domain: emailDomain.toLowerCase().trim(),
+ status: EmailDomainStatus.Verified,
+ orgId
});
if (!verifiedDomain) {
@@ -42,12 +36,6 @@ export const verifyEmailDomainOwnership = async ({
message: "Your organization does not have a verified domain for this email address"
});
}
-
- if (verifiedDomain.orgId !== orgId) {
- throw new BadRequestError({
- message: "Your organization does not have a verified domain for this email address"
- });
- }
};
/**
diff --git a/backend/src/ee/services/email-domain/email-domain-service.ts b/backend/src/ee/services/email-domain/email-domain-service.ts
index 6ed4508c46..dbf7957fa3 100644
--- a/backend/src/ee/services/email-domain/email-domain-service.ts
+++ b/backend/src/ee/services/email-domain/email-domain-service.ts
@@ -1,16 +1,15 @@
-import crypto from "node:crypto";
-import { Resolver } from "node:dns/promises";
+import dns from "node:dns/promises";
import { ForbiddenError } from "@casl/ability";
-import RE2 from "re2";
-import { getDomain, getHostname, getSubdomain } from "tldts";
import { OrganizationActionScope } from "@app/db/schemas";
import { OrgPermissionEmailDomainActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { PgSqlLock } from "@app/keystore/keystore";
+import { crypto } from "@app/lib/crypto";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
+import { logger } from "@app/lib/logger";
+import { isValidEmailDomain } from "@app/lib/validator";
import { TLicenseServiceFactory } from "../license/license-service";
import { TEmailDomainDALFactory } from "./email-domain-dal";
@@ -25,15 +24,7 @@ import {
type TEmailDomainServiceFactoryDep = {
emailDomainDAL: Pick<
TEmailDomainDALFactory,
- | "create"
- | "find"
- | "findOne"
- | "findById"
- | "deleteById"
- | "updateById"
- | "findVerifiedSubdomains"
- | "findVerifiedParentDomains"
- | "transaction"
+ "create" | "find" | "findOne" | "findById" | "deleteById" | "updateById" | "transaction"
>;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
@@ -45,26 +36,6 @@ const VERIFICATION_CODE_EXPIRY_DAYS = 7;
const DNS_RECORD_PREFIX = "_infisical-verification";
const DNS_TXT_VALUE_PREFIX = "infisical-domain-verification";
-const domainLabelValidator = characterValidator([CharacterType.AlphaNumeric, CharacterType.Hyphen]);
-const tldRegex = new RE2(/^[a-zA-Z]+$/);
-
-const isValidDomain = (domain: string): boolean => {
- const parts = domain.split(".");
- if (parts.length < 2) return false;
-
- for (const label of parts) {
- if (label.length === 0 || label.length > 63) return false;
- if (label.startsWith("-") || label.endsWith("-")) return false;
- if (!domainLabelValidator(label)) return false;
- }
-
- // TLD must be at least 2 chars and alphabetic only
- const tld = parts[parts.length - 1];
- if (tld.length < 2 || !tldRegex.test(tld)) return false;
-
- return true;
-};
-
export const emailDomainServiceFactory = ({
emailDomainDAL,
permissionService,
@@ -92,22 +63,15 @@ export const emailDomainServiceFactory = ({
);
const plan = await licenseService.getPlan(orgId);
- if (!plan.emailDomainVerification) {
+ const canEmailDomainVerification = plan.samlSSO || plan.ldap || plan.oidcSSO;
+ if (!canEmailDomainVerification) {
throw new BadRequestError({
message: "Failed to add email domain due to plan restriction. Upgrade plan to use email domain verification."
});
}
const normalizedDomain = domain.toLowerCase().trim();
- if (getHostname(normalizedDomain) !== normalizedDomain || !isValidDomain(normalizedDomain)) {
- throw new BadRequestError({
- message: "Invalid domain format. Please provide a valid domain name (e.g., company.com)."
- });
- }
-
- const subDomain = getSubdomain(normalizedDomain);
- const parentDomain = getDomain(normalizedDomain);
- if (subDomain && !parentDomain) {
+ if (!isValidEmailDomain(normalizedDomain)) {
throw new BadRequestError({
message: "Invalid domain format. Please provide a valid domain name (e.g., company.com)."
});
@@ -120,26 +84,25 @@ export const emailDomainServiceFactory = ({
// Domains are platform-level unique. Use a transaction with a lock to prevent races.
const emailDomain = await emailDomainDAL.transaction(async (tx) => {
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.EmailDomainCreationLock()]);
- // Check if any org (including this one) already has this domain verified
- const platformExisting = await emailDomainDAL.findOne(
- { domain: normalizedDomain, status: EmailDomainStatus.Verified },
- tx
- );
- if (platformExisting) {
- return { error: "This domain is already verified by another organization.", data: null };
- }
- // Check if this org already has a pending/expired record for this domain
- const orgExisting = await emailDomainDAL.findOne({ orgId, domain: normalizedDomain }, tx);
- if (orgExisting) {
- return { error: "This domain is already pending verification or has expired.", data: null };
+ // Check if any org (including this one) already has this domain verified
+ const platformExisting = await emailDomainDAL.find({ domain: normalizedDomain }, { tx });
+ if (platformExisting.length) {
+ const hasVerifiedDomain = platformExisting.some((el) => el.status === EmailDomainStatus.Verified);
+ if (hasVerifiedDomain) {
+ return { error: "This domain is already verified by an organization.", data: null } as const;
+ }
+
+ const isExistingInSameOrg = platformExisting.some((el) => el.orgId === orgId);
+ if (isExistingInSameOrg) {
+ return { error: "This domain is already pending verification or has expired.", data: null } as const;
+ }
}
const created = await emailDomainDAL.create(
{
orgId,
domain: normalizedDomain,
- parentDomain: subDomain ? parentDomain : null,
verificationMethod: "dns-txt",
verificationCode,
verificationRecordName,
@@ -149,14 +112,14 @@ export const emailDomainServiceFactory = ({
tx
);
- return { error: null, data: created };
+ return { error: undefined, data: created } as const;
});
if (emailDomain.error) {
throw new BadRequestError({ message: emailDomain.error });
}
- return emailDomain.data!;
+ return emailDomain.data;
};
const verifyEmailDomain = async ({
@@ -181,13 +144,18 @@ export const emailDomainServiceFactory = ({
);
const plan = await licenseService.getPlan(orgId);
- if (!plan.emailDomainVerification) {
+ const canEmailDomainVerification = plan.samlSSO || plan.ldap || plan.oidcSSO;
+ if (!canEmailDomainVerification) {
throw new BadRequestError({
- message: "Failed to verify email domain due to plan restriction. Upgrade plan to use email domain verification."
+ message: "Failed to add email domain due to plan restriction. Upgrade plan to use email domain verification."
});
}
- const emailDomainRecord = await emailDomainDAL.findOne({ id: emailDomainId, orgId, status: "pending" });
+ const emailDomainRecord = await emailDomainDAL.findOne({
+ id: emailDomainId,
+ orgId,
+ status: EmailDomainStatus.Pending
+ });
if (!emailDomainRecord) {
throw new NotFoundError({
message: "Email domain not found."
@@ -203,11 +171,11 @@ export const emailDomainServiceFactory = ({
}
// Perform DNS TXT record lookup
- const resolver = new Resolver();
let dnsRecords: string[][];
try {
- dnsRecords = await resolver.resolveTxt(emailDomainRecord.verificationRecordName);
- } catch {
+ dnsRecords = await dns.resolveTxt(emailDomainRecord.verificationRecordName);
+ } catch (err) {
+ logger.error(err, "Failed to resolve DNS records for the domain");
throw new BadRequestError({
message:
"Failed to resolve DNS records for the domain. Please verify the DNS TXT record exists and try again. DNS changes may take time to propagate."
@@ -247,9 +215,10 @@ export const emailDomainServiceFactory = ({
);
const plan = await licenseService.getPlan(orgId);
- if (!plan.emailDomainVerification) {
+ const canEmailDomainVerification = plan.samlSSO || plan.ldap || plan.oidcSSO;
+ if (!canEmailDomainVerification) {
throw new BadRequestError({
- message: "Failed to list email domains due to plan restriction. Upgrade plan to use email domain verification."
+ message: "Failed to add email domain due to plan restriction. Upgrade plan to use email domain verification."
});
}
@@ -278,13 +247,6 @@ export const emailDomainServiceFactory = ({
OrgPermissionSubjects.EmailDomains
);
- const plan = await licenseService.getPlan(orgId);
- if (!plan.emailDomainVerification) {
- throw new BadRequestError({
- message: "Failed to delete email domain due to plan restriction. Upgrade plan to use email domain verification."
- });
- }
-
const emailDomainRecord = await emailDomainDAL.findOne({ id: emailDomainId, orgId });
if (!emailDomainRecord) {
throw new NotFoundError({
diff --git a/backend/src/ee/services/group/group-fns.ts b/backend/src/ee/services/group/group-fns.ts
index fc4d4ac67c..c9d527b59c 100644
--- a/backend/src/ee/services/group/group-fns.ts
+++ b/backend/src/ee/services/group/group-fns.ts
@@ -30,6 +30,7 @@ const addAcceptedUsersToGroup = async ({
},
tx
);
+ if (!users.length) return;
await userGroupMembershipDAL.insertMany(
users.map((user) => ({
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 30ac24f474..303ddd2e63 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -14,7 +14,7 @@ import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { validateEmail } from "@app/lib/validator/validate-email";
+import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { AuthMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
@@ -398,7 +398,7 @@ export const ldapConfigServiceFactory = ({
orgId,
ip,
userAgent,
- relayState
+ callbackPort
}: TLdapLoginDTO) => {
const serverCfg = await getServerCfg();
@@ -410,7 +410,7 @@ export const ldapConfigServiceFactory = ({
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });
- const sanitizedEmail = email.toLowerCase();
+ const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
let userAlias = await userAliasDAL.findOne({
@@ -634,8 +634,6 @@ export const ldapConfigServiceFactory = ({
});
}
- const callbackPort = relayState ? (JSON.parse(relayState) as { callbackPort: string }).callbackPort : undefined;
-
const callbackResult = await loginService.processProviderCallback({
user,
authMethod: AuthMethod.LDAP,
diff --git a/backend/src/ee/services/ldap-config/ldap-config-types.ts b/backend/src/ee/services/ldap-config/ldap-config-types.ts
index 78052bba05..580f7958bb 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-types.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-types.ts
@@ -67,7 +67,7 @@ export type TLdapLoginDTO = {
dn: string;
cn: string;
}[];
- relayState?: string;
+ callbackPort?: number;
};
export type TGetLdapGroupMapsDTO = {
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index 01b5f4c673..b75ef22b5e 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -114,8 +114,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
eventSubscriptions: false,
machineIdentityAuthTemplates: false,
pkiLegacyTemplates: false,
- secretShareExternalBranding: false,
- emailDomainVerification: false
+ secretShareExternalBranding: false
});
export const setupLicenseRequestWithStore = (
diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts
index 71b1eb4832..bd556a5065 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -94,7 +94,6 @@ export type TFeatureSet = {
fips: false;
eventSubscriptions: false;
secretShareExternalBranding: false;
- emailDomainVerification: false;
};
export type TOrgPlansTableDTO = {
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index fb65314457..c92d2636cc 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -17,7 +17,12 @@ import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError, NotFoundError, OidcAuthError } from "@app/lib/errors";
import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
import { OrgServiceActor } from "@app/lib/types";
-import { blockLocalAndPrivateIpAddresses, matchesAllowedEmailDomain, validateEmail } from "@app/lib/validator";
+import {
+ blockLocalAndPrivateIpAddresses,
+ matchesAllowedEmailDomain,
+ sanitizeEmail,
+ validateEmail
+} from "@app/lib/validator";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
@@ -193,7 +198,7 @@ export const oidcConfigServiceFactory = ({
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });
- const sanitizedEmail = email.toLowerCase();
+ const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
let userAlias = await userAliasDAL.findOne({
@@ -434,10 +439,10 @@ export const oidcConfigServiceFactory = ({
ip,
userAgent,
organizationId: organization.id,
- callbackPort
+ callbackPort: Number(callbackPort)
});
- return { ...callbackResult, user };
+ return { ...callbackResult, userId: user.id };
};
const updateOidcCfg = async ({
@@ -763,7 +768,7 @@ export const oidcConfigServiceFactory = ({
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": claims?.email?.toLowerCase(),
- "infisical.user.id": loginResult.user?.id,
+ "infisical.user.id": loginResult.userId,
"infisical.organization.id": org.id,
"infisical.organization.name": org.name,
"infisical.auth.method": AuthAttemptAuthMethod.OIDC,
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 2efc625aac..d16598ead7 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -16,7 +16,7 @@ import {
} from "@app/db/schemas";
import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { validateEmail } from "@app/lib/validator/validate-email";
+import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { AuthMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
@@ -515,7 +515,7 @@ export const samlConfigServiceFactory = ({
orgId,
ip,
userAgent,
- relayState,
+ callbackPort,
metadata
}) => {
const serverCfg = await getServerCfg();
@@ -534,7 +534,7 @@ export const samlConfigServiceFactory = ({
// Verify that the email domain (if verified on the platform) belongs to this org
await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });
- const sanitizedEmail = email.toLowerCase();
+ const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
const organization = await orgDAL.findOrgById(orgId);
@@ -737,13 +737,6 @@ export const samlConfigServiceFactory = ({
});
}
- let callbackPort;
- try {
- callbackPort = relayState ? (JSON.parse(relayState) as { callbackPort: string }).callbackPort : undefined;
- } catch {
- // relayState is invalid JSON, ignore and proceed without a callback port
- }
-
const callbackResult = await loginService.processProviderCallback({
user,
authMethod: authProvider as AuthMethod,
@@ -755,7 +748,7 @@ export const samlConfigServiceFactory = ({
callbackPort
});
- return { ...callbackResult, user, organization };
+ return { ...callbackResult, userId: user.id, orgId: organization.id, orgName: organization.name };
};
return {
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 059fee350d..e20e613d6e 100644
--- a/backend/src/ee/services/saml-config/saml-config-types.ts
+++ b/backend/src/ee/services/saml-config/saml-config-types.ts
@@ -1,4 +1,4 @@
-import { TOrganizations, TSamlConfigs, TUsers } from "@app/db/schemas";
+import { TSamlConfigs } from "@app/db/schemas";
import { TOrgPermission } from "@app/lib/types";
import { TProviderAuthResult } from "@app/services/auth/auth-login-type";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
@@ -63,7 +63,7 @@ export type TSamlLoginDTO = {
ip: string;
userAgent: string;
// saml thingy
- relayState?: string;
+ callbackPort?: number;
metadata?: { key: string; value: string }[];
};
@@ -82,10 +82,5 @@ export type TSamlConfigServiceFactory = {
lastUsed: Date | null | undefined;
enableGroupSync?: boolean;
}>;
- samlLogin: (arg: TSamlLoginDTO) => Promise<
- TProviderAuthResult & {
- user: TUsers;
- organization: TOrganizations;
- }
- >;
+ samlLogin: (arg: TSamlLoginDTO) => Promise<TProviderAuthResult & { userId: string; orgId: string; orgName: string }>;
};
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index a23ccd044c..3dc73f4e9a 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -22,7 +22,7 @@ import { BadRequestError, NotFoundError, ScimRequestError, UnauthorizedError } f
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { validateEmail } from "@app/lib/validator/validate-email";
+import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { AuthTokenType } from "@app/services/auth/auth-type";
import { TExternalGroupOrgRoleMappingDALFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-dal";
@@ -374,7 +374,7 @@ export const scimServiceFactory = ({
}) => {
if (!email) throw new ScimRequestError({ detail: "Invalid request. Missing email.", status: 400 });
- const sanitizedEmail = email.toLowerCase();
+ const sanitizedEmail = sanitizeEmail(email);
validateEmail(sanitizedEmail);
const org = await orgDAL.findOrgById(orgId);
diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.ts
index 3edd025e05..7ac495d51b 100644
--- a/backend/src/lib/validator/index.ts
+++ b/backend/src/lib/validator/index.ts
@@ -1,5 +1,5 @@
export { matchesAllowedEmailDomain } from "./email-domain-matcher";
-export { isDisposableEmail, validateEmail } from "./validate-email";
+export { isDisposableEmail, isValidEmailDomain, sanitizeEmail, validateEmail } from "./validate-email";
export { isValidFolderName, isValidSecretPath } from "./validate-folder-name";
export {
containsDangerousSmbChars,
diff --git a/backend/src/lib/validator/validate-email.ts b/backend/src/lib/validator/validate-email.ts
index edd645a8ee..394a0667f6 100644
--- a/backend/src/lib/validator/validate-email.ts
+++ b/backend/src/lib/validator/validate-email.ts
@@ -1,8 +1,8 @@
import fs from "fs/promises";
import path from "path";
-import { getDomain } from "tldts";
import { BadRequestError } from "../errors";
+import { CharacterType, characterValidator } from "./validate-string";
export const isDisposableEmail = async (emails: string | string[]) => {
const disposableEmails = await fs.readFile(path.join(__dirname, "disposable_emails.txt"), "utf8");
@@ -18,15 +18,39 @@ export const isDisposableEmail = async (emails: string | string[]) => {
return false;
};
+const domainLabelValidator = characterValidator([CharacterType.AlphaNumeric, CharacterType.Hyphen]);
+const tldValidator = characterValidator([CharacterType.AlphaNumeric]);
+
+export const isValidEmailDomain = (domain: string): boolean => {
+ const parts = domain.split(".");
+ if (parts.length < 2) return false;
+
+ for (const label of parts) {
+ if (label.length === 0 || label.length > 63) return false;
+ if (label.startsWith("-") || label.endsWith("-")) return false;
+ if (!domainLabelValidator(label)) return false;
+ }
+
+ // TLD must be at least 2 chars and alphabetic only
+ const tld = parts[parts.length - 1];
+ if (tld.length < 2 || !tldValidator(tld)) return false;
+
+ return true;
+};
+
+export const sanitizeEmail = (email: string) => {
+ return email.toLowerCase().trim();
+};
+
export const validateEmail = (email: string) => {
- const domain = getDomain(email);
+ const userIdentifier = email.slice(0, email.indexOf("@"));
+ const domain = email.slice(email.indexOf("@") + 1);
+
if (!domain) throw new BadRequestError({ message: "Missing email domain" });
+ if (!isValidEmailDomain) throw new BadRequestError({ message: "Invalid email domain" });
- const userIdentifier = email.split("@")[0];
if (!userIdentifier) throw new BadRequestError({ message: "Missing user identifier in email" });
- if (userIdentifier.includes("+"))
- throw new BadRequestError({ message: "Email user identifier contains a plus sign" });
-
- if (email.toLowerCase() !== email) throw new BadRequestError({ message: "Email contains uppercase characters" });
+ if (email.toLowerCase().trim() !== email)
+ throw new BadRequestError({ message: "Email contains uppercase characters or leading/trailing whitespace" });
};
diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.ts
index b155a12dfb..84aaf0842c 100644
--- a/backend/src/server/plugins/auth/inject-identity.ts
+++ b/backend/src/server/plugins/auth/inject-identity.ts
@@ -8,7 +8,14 @@ import { TScimTokenJwtPayload } from "@app/ee/services/scim/scim-types";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError } from "@app/lib/errors";
-import { ActorType, AuthMethod, AuthMode, AuthModeJwtTokenPayload, AuthTokenType } from "@app/services/auth/auth-type";
+import {
+ ActorType,
+ AuthMethod,
+ AuthMode,
+ AuthModeJwtTokenPayload,
+ AuthTokenType,
+ MfaMethod
+} from "@app/services/auth/auth-type";
import { TIdentityAccessTokenJwtPayload } from "@app/services/identity-access-token/identity-access-token-types";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
@@ -24,6 +31,7 @@ export type TAuthMode =
parentOrgId: string;
authMethod: AuthMethod;
isMfaVerified?: boolean;
+ mfaMethod?: MfaMethod;
token: AuthModeJwtTokenPayload;
}
| {
@@ -150,7 +158,11 @@ export const injectIdentity = fp(
return;
}
- if (req.url.includes(".well-known/est") || req.url.includes("/scep/") || req.url.includes("/api/v3/auth/")) {
+ if (
+ req.url.includes(".well-known/est") ||
+ req.url.includes("/scep/") ||
+ (req.url.includes("/api/v3/auth/") && !req.url.includes("/api/v3/auth/select-organization"))
+ ) {
return;
}
@@ -195,7 +207,8 @@ export const injectIdentity = fp(
parentOrgId,
authMethod: token.authMethod,
isMfaVerified: token.isMfaVerified,
- token
+ token,
+ mfaMethod: token.mfaMethod
};
fireIdentifyForUser(user);
break;
diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts
index abf9237d80..c90efe01fd 100644
--- a/backend/src/server/routes/v1/admin-router.ts
+++ b/backend/src/server/routes/v1/admin-router.ts
@@ -696,7 +696,7 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => {
void res.setCookie("jid", token.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/server/routes/v1/auth-router.ts b/backend/src/server/routes/v1/auth-router.ts
index 29650870da..a9092a90f8 100644
--- a/backend/src/server/routes/v1/auth-router.ts
+++ b/backend/src/server/routes/v1/auth-router.ts
@@ -36,7 +36,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
void res.cookie("jid", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
@@ -44,7 +44,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
void res.cookie("infisical-project-assume-privileges", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
@@ -52,7 +52,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
void res.cookie("aod", "", {
httpOnly: false,
- path: "/",
+ path: "/api",
sameSite: "lax",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
@@ -112,7 +112,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
// when the browser keeps sending the stale cookie on subsequent requests.
void res.cookie("jid", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
@@ -165,7 +165,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
if (newRefreshToken) {
void res.setCookie("jid", newRefreshToken, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/server/routes/v1/password-router.ts b/backend/src/server/routes/v1/password-router.ts
index 1e5cd681bc..b421c3b9e8 100644
--- a/backend/src/server/routes/v1/password-router.ts
+++ b/backend/src/server/routes/v1/password-router.ts
@@ -119,7 +119,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
const appCfg = getConfig();
void res.cookie("jid", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index d5e7259e13..0e128c0286 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -388,7 +388,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
if (passportResult.result === ProviderAuthResult.SESSION) {
void res.setCookie("jid", passportResult.tokens.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
@@ -519,7 +519,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
if (req.passportUser.externalProviderAccessToken) {
void res.cookie(INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN, req.passportUser.externalProviderAccessToken, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
expires: new Date(Date.now() + ms("15m"))
diff --git a/backend/src/server/routes/v2/mfa-router.ts b/backend/src/server/routes/v2/mfa-router.ts
index 5ce3d998f3..e85d09ffdf 100644
--- a/backend/src/server/routes/v2/mfa-router.ts
+++ b/backend/src/server/routes/v2/mfa-router.ts
@@ -36,7 +36,7 @@ const handleMfaVerification = async (
void res.setCookie("jid", token.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/server/routes/v2/organization-router.ts b/backend/src/server/routes/v2/organization-router.ts
index 78a2fe4e98..ece8f3cb8e 100644
--- a/backend/src/server/routes/v2/organization-router.ts
+++ b/backend/src/server/routes/v2/organization-router.ts
@@ -442,7 +442,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
void res.setCookie("jid", tokens.refreshToken, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: cfg.HTTPS_ENABLED
});
diff --git a/backend/src/server/routes/v2/password-router.ts b/backend/src/server/routes/v2/password-router.ts
index cb2c88893c..2ff658aa8a 100644
--- a/backend/src/server/routes/v2/password-router.ts
+++ b/backend/src/server/routes/v2/password-router.ts
@@ -56,14 +56,14 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
void res.cookie("jid", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
void res.cookie("infisical-project-assume-privileges", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
@@ -71,7 +71,7 @@ export const registerPasswordRouter = async (server: FastifyZodProvider) => {
void res.cookie("aod", "", {
httpOnly: false,
- path: "/",
+ path: "/api",
sameSite: "lax",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
diff --git a/backend/src/server/routes/v3/login-router.ts b/backend/src/server/routes/v3/login-router.ts
index 0141625ce8..f8663f9c2a 100644
--- a/backend/src/server/routes/v3/login-router.ts
+++ b/backend/src/server/routes/v3/login-router.ts
@@ -2,8 +2,11 @@ import { z } from "zod";
import { INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN } from "@app/lib/config/const";
import { getConfig } from "@app/lib/config/env";
+import { UnauthorizedError } from "@app/lib/errors";
import { authRateLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
export const registerLoginRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -57,14 +60,23 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
})
}
},
+ onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req, res) => {
const cfg = getConfig();
+ if (req.auth.authMode !== AuthMode.JWT) {
+ throw new UnauthorizedError({ message: "Invalid auth mode" });
+ }
+
const tokens = await server.services.login.selectOrganization({
userAgent: req.body.userAgent ?? req.headers["user-agent"],
- authJwtToken: req.headers.authorization,
organizationId: req.body.organizationId,
- ipAddress: req.realIp
+ ipAddress: req.realIp,
+ userId: req.auth.userId,
+ userAuthMethod: req.auth.authMethod,
+ actorOrgId: req.auth.orgId,
+ isMfaVerified: req.auth.isMfaVerified,
+ mfaMethod: req.auth.mfaMethod
});
if (tokens.isMfaEnabled) {
@@ -82,7 +94,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
.finally(() => {
void res.setCookie(INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN, "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: cfg.HTTPS_ENABLED,
maxAge: 0
@@ -101,7 +113,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
void res.cookie("infisical-project-assume-privileges", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: cfg.HTTPS_ENABLED,
maxAge: 0
@@ -169,7 +181,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
addAuthOriginDomainCookie(res);
void res.cookie("infisical-project-assume-privileges", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
@@ -236,7 +248,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
void res.cookie("infisical-project-assume-privileges", "", {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED,
maxAge: 0
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index b68f34ff79..2ea8bbd301 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -26,7 +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 { sanitizeEmail, validateEmail } from "@app/lib/validator";
import { getUserAgentType } from "@app/server/plugins/audit-log";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
@@ -55,11 +55,11 @@ import {
import {
ActorType,
AuthMethod,
- AuthModeJwtTokenPayload,
AuthModeMfaJwtTokenPayload,
AuthTokenType,
MfaMethod,
- ProviderAuthResult
+ ProviderAuthResult,
+ TProviderAuthCallback
} from "./auth-type";
type TAuthLoginServiceFactoryDep = {
@@ -307,7 +307,7 @@ export const authLoginServiceFactory = ({
userAgent,
organizationId,
callbackPort
- }: TProcessProviderCallbackDTO) => {
+ }: TProcessProviderCallbackDTO): Promise<TProviderAuthCallback> => {
const appCfg = getConfig();
if (!user.isAccepted || !isEmailVerified) {
@@ -548,6 +548,9 @@ export const authLoginServiceFactory = ({
throw new BadRequestError({ message: "Invalid credentials" });
}
+ await userDAL.updateById(user.id, {
+ consecutiveFailedPasswordAttempts: 0
+ });
const token = await generateUserTokens({
userId: user.id,
ip,
@@ -804,8 +807,8 @@ export const authLoginServiceFactory = ({
userAgent
}: TOauthLoginDTO) => {
const aliasType = authMethodToAliasType(authMethod);
- const normalizedEmail = email.trim().toLowerCase();
- validateEmail(normalizedEmail);
+ const sanitizedEmail = sanitizeEmail(email);
+ validateEmail(sanitizedEmail);
// Step 1: Look up user by provider alias (stable, immutable ID)
let user: TUsers | undefined;
@@ -817,7 +820,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: normalizedEmail });
+ user = await userDAL.findOne({ username: sanitizedEmail });
if (user) {
isNewAlias = true;
}
@@ -892,8 +895,8 @@ export const authLoginServiceFactory = ({
user = await userDAL.transaction(async (tx) => {
const newUser = await userDAL.create(
{
- username: normalizedEmail,
- email: normalizedEmail,
+ username: sanitizedEmail,
+ email: sanitizedEmail,
isEmailVerified: false,
isAccepted: false,
firstName,
@@ -924,7 +927,7 @@ export const authLoginServiceFactory = ({
const membership = await membershipUserDAL.create(
{
actorUserId: newUser.id,
- inviteEmail: normalizedEmail,
+ inviteEmail: sanitizedEmail,
scopeOrgId: orgId,
scope: AccessScope.Organization,
status: OrgMembershipStatus.Accepted,
@@ -948,7 +951,7 @@ export const authLoginServiceFactory = ({
userId: newUser.id,
aliasType,
externalId: providerUserId,
- emails: [normalizedEmail],
+ emails: [sanitizedEmail],
orgId: orgId || null,
isEmailVerified: false
},
@@ -969,8 +972,8 @@ export const authLoginServiceFactory = ({
});
}
- if (existingAlias && user.email !== normalizedEmail) {
- const conflictingUser = await userDAL.findOne({ username: normalizedEmail });
+ if (existingAlias && user.email !== sanitizedEmail) {
+ const conflictingUser = await userDAL.findOne({ username: sanitizedEmail });
if (conflictingUser && conflictingUser.id !== user.id) {
throw new BadRequestError({
message:
@@ -983,8 +986,8 @@ export const authLoginServiceFactory = ({
const updatedUser = await userDAL.updateById(
user!.id,
{
- username: normalizedEmail,
- email: normalizedEmail,
+ username: sanitizedEmail,
+ email: sanitizedEmail,
isGitHubVerified: authMethod !== AuthMethod.GITHUB && user?.isGitHubVerified,
isGoogleVerified: authMethod !== AuthMethod.GOOGLE && user?.isGoogleVerified,
isGitLabVerified: authMethod !== AuthMethod.GITLAB && user?.isGitLabVerified
@@ -995,7 +998,7 @@ export const authLoginServiceFactory = ({
await userAliasDAL.updateById(
existingAlias.id,
{
- emails: [normalizedEmail]
+ emails: [sanitizedEmail]
},
tx
);
@@ -1097,28 +1100,27 @@ export const authLoginServiceFactory = ({
const selectOrganization = async ({
userAgent,
- authJwtToken,
ipAddress,
- organizationId
+ organizationId,
+ userId,
+ userAuthMethod,
+ actorOrgId,
+ isMfaVerified,
+ mfaMethod
}: {
userAgent: string | undefined;
- authJwtToken: string | undefined;
ipAddress: string;
organizationId: string;
+ userId: string;
+ userAuthMethod: AuthMethod;
+ actorOrgId?: string;
+ isMfaVerified?: boolean;
+ mfaMethod?: MfaMethod;
}) => {
const cfg = getConfig();
-
- if (!authJwtToken) throw new UnauthorizedError({ name: "Authorization header is required" });
if (!userAgent) throw new UnauthorizedError({ name: "User-Agent header is required" });
- // eslint-disable-next-line no-param-reassign
- authJwtToken = authJwtToken.replace("Bearer ", ""); // remove bearer from token
-
- // The decoded JWT token, which contains the auth method.
- const decodedToken = crypto.jwt().verify(authJwtToken, cfg.AUTH_SECRET) as AuthModeJwtTokenPayload;
- if (!decodedToken.authMethod) throw new UnauthorizedError({ name: "Auth method not found on existing token" });
-
- const user = await userDAL.findById(decodedToken.userId);
+ const user = await userDAL.findById(userId);
if (!user || !user.isAccepted)
throw new BadRequestError({ message: "User not found", name: "Find user from token" });
@@ -1177,7 +1179,7 @@ export const authLoginServiceFactory = ({
actor: ActorType.USER,
actorId: user.id,
orgId: rootOrg.id,
- actorAuthMethod: decodedToken.authMethod,
+ actorAuthMethod: userAuthMethod,
actorOrgId: rootOrg.id,
scope: OrganizationActionScope.Any
});
@@ -1187,8 +1189,8 @@ export const authLoginServiceFactory = ({
if (
rootOrg.authEnforced &&
- !isAuthMethodSaml(decodedToken.authMethod) &&
- decodedToken.authMethod !== AuthMethod.OIDC &&
+ !isAuthMethodSaml(userAuthMethod) &&
+ userAuthMethod !== AuthMethod.OIDC &&
!canBypassSso
) {
throw new BadRequestError({
@@ -1196,7 +1198,7 @@ export const authLoginServiceFactory = ({
});
}
- if (rootOrg.googleSsoAuthEnforced && decodedToken.authMethod !== AuthMethod.GOOGLE) {
+ if (rootOrg.googleSsoAuthEnforced && userAuthMethod !== AuthMethod.GOOGLE) {
if (!canBypassSso) {
throw new ForbiddenRequestError({
message: "Google SSO is enforced for this organization. Please use Google SSO to login.",
@@ -1205,7 +1207,7 @@ export const authLoginServiceFactory = ({
}
}
- if (decodedToken.authMethod === AuthMethod.GOOGLE) {
+ if (userAuthMethod === AuthMethod.GOOGLE) {
await orgDAL.updateById(rootOrg.id, {
googleSsoAuthLastUsed: new Date()
});
@@ -1213,12 +1215,11 @@ export const authLoginServiceFactory = ({
const { isMfaRequired, requiredMfaMethod } = getRequiredMfaMethod(rootOrg, user);
// Check if organization has changed
- const hasOrganizationChanged = decodedToken?.organizationId ? decodedToken.organizationId !== rootOrg.id : false;
+ const hasOrganizationChanged = actorOrgId ? actorOrgId !== rootOrg.id : false;
// Check if MFA method has changed
- const hasMfaMethodChanged = decodedToken.mfaMethod !== requiredMfaMethod;
+ const hasMfaMethodChanged = mfaMethod !== requiredMfaMethod;
// Trigger MFA if required and either not verified or something changed
- const shouldTriggerMfa =
- isMfaRequired && (!decodedToken.isMfaVerified || hasMfaMethodChanged || hasOrganizationChanged);
+ const shouldTriggerMfa = isMfaRequired && (!isMfaVerified || hasMfaMethodChanged || hasOrganizationChanged);
if (shouldTriggerMfa) {
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
@@ -1226,7 +1227,7 @@ export const authLoginServiceFactory = ({
const mfaToken = await issueMfaChallenge({
userId: user.id,
email: user.email,
- authMethod: decodedToken.authMethod,
+ authMethod: userAuthMethod,
requiredMfaMethod,
organizationId: rootOrg.id
});
@@ -1237,14 +1238,14 @@ export const authLoginServiceFactory = ({
await updateUserDeviceSession(user, ipAddress, userAgent);
const tokens = await generateUserTokens({
- authMethod: decodedToken.authMethod,
+ authMethod: userAuthMethod,
userId: user.id,
userAgent,
ip: ipAddress,
organizationId: isSubOrganization ? rootOrg.id : organizationId,
subOrganizationId: isSubOrganization ? organizationId : undefined,
- isMfaVerified: decodedToken.isMfaVerified,
- mfaMethod: decodedToken.mfaMethod
+ isMfaVerified,
+ mfaMethod
});
// Promote any Invited memberships to Accepted now that the user has authenticated into this org
@@ -1262,11 +1263,11 @@ export const authLoginServiceFactory = ({
const isAuthEnforcedBypass =
rootOrg.authEnforced &&
rootOrg.bypassOrgAuthEnabled &&
- !isAuthMethodSaml(decodedToken.authMethod) &&
- decodedToken.authMethod !== AuthMethod.OIDC &&
- decodedToken.authMethod !== AuthMethod.GOOGLE;
+ !isAuthMethodSaml(userAuthMethod) &&
+ userAuthMethod !== AuthMethod.OIDC &&
+ userAuthMethod !== AuthMethod.GOOGLE;
const isGoogleSsoEnforcedBypass =
- rootOrg.googleSsoAuthEnforced && rootOrg.bypassOrgAuthEnabled && decodedToken.authMethod !== AuthMethod.GOOGLE;
+ rootOrg.googleSsoAuthEnforced && rootOrg.bypassOrgAuthEnabled && userAuthMethod !== AuthMethod.GOOGLE;
if (isAuthEnforcedBypass || isGoogleSsoEnforcedBypass) {
await auditLogService.createAuditLog({
orgId: organizationId,
@@ -1335,7 +1336,7 @@ export const authLoginServiceFactory = ({
email: user.email,
userId: user.id,
username: user.username,
- authMethod: decodedToken.authMethod
+ authMethod: userAuthMethod as string
}
},
event: isSubOrganization
diff --git a/backend/src/services/auth/auth-login-type.ts b/backend/src/services/auth/auth-login-type.ts
index 2128ca9828..0c8c1c97c2 100644
--- a/backend/src/services/auth/auth-login-type.ts
+++ b/backend/src/services/auth/auth-login-type.ts
@@ -32,7 +32,7 @@ export type TOauthLoginDTO = {
firstName: string;
lastName?: string;
authMethod: AuthMethod;
- callbackPort?: string;
+ callbackPort?: number;
orgSlug?: string;
providerUserId: string;
ip: string;
@@ -46,11 +46,7 @@ export type TProcessProviderCallbackDTO = {
email?: string | null;
firstName?: string | null;
lastName?: string | null;
- isEmailVerified?: boolean | null;
- isMfaEnabled?: boolean | null;
- selectedMfaMethod?: string | null;
isLocked?: boolean | null;
- temporaryLockDateEnd?: Date | null;
};
authMethod: AuthMethod;
isEmailVerified: boolean;
@@ -58,10 +54,10 @@ export type TProcessProviderCallbackDTO = {
ip: string;
userAgent: string;
organizationId?: string;
- callbackPort?: string;
+ callbackPort?: number;
};
export type TProviderAuthResult =
- | { 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 };
+ | { result: ProviderAuthResult.SESSION; tokens: { access: string; refresh: string }; callbackPort?: number }
+ | { result: ProviderAuthResult.MFA_REQUIRED; mfaToken: string; mfaMethod: MfaMethod; callbackPort?: number }
+ | { result: ProviderAuthResult.SIGNUP_REQUIRED; signupToken: string; callbackPort?: number };
diff --git a/backend/src/services/auth/auth-password-service.ts b/backend/src/services/auth/auth-password-service.ts
index 3545a98b26..dadd7ad9cd 100644
--- a/backend/src/services/auth/auth-password-service.ts
+++ b/backend/src/services/auth/auth-password-service.ts
@@ -12,6 +12,7 @@ import { TUserDALFactory } from "../user/user-dal";
import { UserEncryption } from "../user/user-types";
import { TAuthDALFactory } from "./auth-dal";
import {
+ ResetPasswordV2Type,
TResetPasswordV2DTO,
TResetPasswordViaBackupKeyDTO,
TSetupPasswordViaBackupKeyDTO
@@ -34,10 +35,10 @@ export const authPaswordServiceFactory = ({
smtpService,
totpConfigDAL
}: TAuthPasswordServiceFactoryDep) => {
- const resetPasswordV2 = async ({ userId, newPassword, oldPassword }: TResetPasswordV2DTO) => {
+ const resetPasswordV2 = async ({ userId, newPassword, oldPassword, type }: TResetPasswordV2DTO) => {
const cfg = getConfig();
- const user = await userDAL.findUserEncKeyByUserId(userId);
+ const user = await userDAL.findById(userId);
if (!user) {
throw new BadRequestError({ message: `User encryption key not found for user with ID '${userId}'` });
}
@@ -50,22 +51,24 @@ export const authPaswordServiceFactory = ({
throw new BadRequestError({ message: "Unable to reset password, no email authentication method is configured" });
}
- if (!user.hashedPassword) {
- throw new BadRequestError({ message: "Unable to change password, no password is set" });
- }
+ if (type === ResetPasswordV2Type.LoggedInReset) {
+ if (!user.hashedPassword) {
+ throw new BadRequestError({ message: "Unable to change password, no password is set" });
+ }
- if (!oldPassword) {
- throw new BadRequestError({ message: "Current password is required." });
- }
+ if (!oldPassword) {
+ throw new BadRequestError({ message: "Current password is required." });
+ }
- const isValid = await crypto.hashing().compareHash(oldPassword, user.hashedPassword);
- if (!isValid) {
- throw new BadRequestError({ message: "Incorrect current password." });
+ const isValid = await crypto.hashing().compareHash(oldPassword, user.hashedPassword);
+ if (!isValid) {
+ throw new BadRequestError({ message: "Incorrect current password." });
+ }
}
const newHashedPassword = await crypto.hashing().createHash(newPassword, cfg.SALT_ROUNDS);
- await userDAL.updateUserEncryptionByUserId(userId, {
+ await userDAL.updateById(userId, {
hashedPassword: newHashedPassword
});
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index 4aaa62d134..ff40f4e13f 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -2,7 +2,7 @@ import { AccessScope, OrgMembershipStatus } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
-import { isDisposableEmail, validateEmail } from "@app/lib/validator";
+import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
@@ -41,7 +41,7 @@ export const authSignupServiceFactory = ({
}: TAuthSignupDep) => {
// first step of signup. create user and send email
const beginEmailSignupProcess = async (email: string) => {
- const sanitizedEmail = email.trim().toLowerCase();
+ const sanitizedEmail = sanitizeEmail(email);
validateEmail(email);
const isEmailInvalid = await isDisposableEmail(sanitizedEmail);
if (isEmailInvalid) {
@@ -93,7 +93,7 @@ export const authSignupServiceFactory = ({
};
const verifyEmailSignup = async (email: string, code: string) => {
- const sanitizedEmail = email.trim().toLowerCase();
+ const sanitizedEmail = sanitizeEmail(email);
validateEmail(email);
const user = await userDAL.findOne({ username: sanitizedEmail });
diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.ts
index 63736f8a89..efea56c4dd 100644
--- a/backend/src/services/auth/auth-type.ts
+++ b/backend/src/services/auth/auth-type.ts
@@ -114,3 +114,18 @@ export enum MfaMethod {
TOTP = "totp",
WEBAUTHN = "webauthn"
}
+
+export type TProviderAuthCallback =
+ | {
+ result: ProviderAuthResult.SIGNUP_REQUIRED;
+ signupToken: string;
+ callbackPort?: number;
+ }
+ | {
+ result: ProviderAuthResult.SESSION;
+ tokens: {
+ access: string;
+ refresh: string;
+ };
+ callbackPort?: number;
+ };
diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.ts
index 0870626a83..e0a3503f6f 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, validateEmail } from "@app/lib/validator";
+import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { AuthMethod } from "../auth/auth-type";
@@ -214,7 +214,8 @@ export const membershipUserServiceFactory = ({
});
}
const scopeDatabaseFields = factory.getScopeDatabaseFields(dto.scopeData);
- const users = await $getUsers(dto.data.usernames);
+ const sanitizedEmails = dto.data.usernames.map((el) => sanitizeEmail(el));
+ const users = await $getUsers(sanitizedEmails);
const existingMemberships = await membershipUserDAL.find({
scope: scopeData.scope,
...scopeDatabaseFields,
diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts
index 7a076afd1b..fd122030a2 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, validateEmail } from "@app/lib/validator";
+import { isDisposableEmail, sanitizeEmail, 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";
@@ -764,7 +764,7 @@ export const superAdminServiceFactory = ({
) => {
const appCfg = getConfig();
- const inviteAdminEmails = [...new Set(emails)];
+ const inviteAdminEmails = [...new Set(emails)].map((el) => sanitizeEmail(el));
if (!appCfg.isDevelopmentMode && appCfg.isCloud)
throw new BadRequestError({ message: "This endpoint is not supported for cloud instances" });
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 438451b756..29dad6dfc4 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -7,7 +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 { sanitizeEmail, 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";
@@ -159,7 +159,7 @@ export const userServiceFactory = ({
const requestEmailChangeOTP = async ({ userId, newEmail }: TUpdateUserEmailDTO) => {
const startTime = new Date();
- const normalizedNewEmail = newEmail.toLowerCase();
+ const normalizedNewEmail = sanitizeEmail(newEmail);
validateEmail(normalizedNewEmail);
const changeEmailOTP = await userDAL.transaction(async (tx) => {
const user = await userDAL.findById(userId, tx);
@@ -217,7 +217,7 @@ export const userServiceFactory = ({
newEmail: unsanitizedEmail,
otpCode
}: TUpdateUserEmailDTO & { otpCode: string }) => {
- const newEmail = unsanitizedEmail.toLowerCase();
+ const newEmail = sanitizeEmail(unsanitizedEmail);
validateEmail(newEmail);
const changedUser = await userDAL.transaction(async (tx) => {
const user = await userDAL.findById(userId, tx);
diff --git a/frontend/src/hooks/api/emailDomains/types.ts b/frontend/src/hooks/api/emailDomains/types.ts
index 9694291810..f5ec0102a7 100644
--- a/frontend/src/hooks/api/emailDomains/types.ts
+++ b/frontend/src/hooks/api/emailDomains/types.ts
@@ -2,7 +2,6 @@ export type TEmailDomain = {
id: string;
orgId: string;
domain: string;
- parentDomain: string | null;
verificationMethod: string;
verificationCode: string;
verificationRecordName: string;
diff --git a/frontend/src/hooks/api/subscriptions/queries.tsx b/frontend/src/hooks/api/subscriptions/queries.tsx
index 325e62e5f8..f57a108e98 100644
--- a/frontend/src/hooks/api/subscriptions/queries.tsx
+++ b/frontend/src/hooks/api/subscriptions/queries.tsx
@@ -16,7 +16,8 @@ export const fetchOrgSubscription = async (orgID: string, refreshCache: boolean
`/api/v1/organizations/${orgID}/plan${refreshCache ? "?refreshCache=true" : ""}`
);
- return data.plan;
+ const canEmailDomainVerification = data.plan.samlSSO || data.plan.ldap || data.plan.oidcSSO;
+ return { ...data.plan, canEmailDomainVerification };
};
type UseGetOrgSubscriptionProps = {
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgEmailDomainsSection/OrgEmailDomainsTable.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgEmailDomainsSection/OrgEmailDomainsTable.tsx
index f78220e4a7..1ad646b6aa 100644
--- a/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgEmailDomainsSection/OrgEmailDomainsTable.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgSsoTab/OrgEmailDomainsSection/OrgEmailDomainsTable.tsx
@@ -117,11 +117,6 @@ export const OrgEmailDomainsTable = () => {
<Tr key={emailDomain.id}>
<Td className="max-w-xs">
<span className="font-medium">{emailDomain.domain}</span>
- {emailDomain.parentDomain && (
- <span className="ml-2 text-xs text-gray-500">
- (subdomain of {emailDomain.parentDomain})
- </span>
- )}
</Td>
<Td>
<span className={twMerge("flex items-center gap-1.5", statusConfig.className)}>