Skip to content

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

feat: updated migration file

=1a1b4a96fd73
diff --git a/backend/src/db/migrations/20260404140728_username-merge.ts b/backend/src/db/migrations/20260404140728_username-merge.ts
index ec46b52d7e..11353ca5fb 100644
--- a/backend/src/db/migrations/20260404140728_username-merge.ts
+++ b/backend/src/db/migrations/20260404140728_username-merge.ts
@@ -3,11 +3,25 @@ import { Knex } from "knex";
import { AccessScope, TableName } from "../schemas";
+const MIGRATION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
+
export async function up(knex: Knex): Promise<void> {
- // ============================================================
- // Step 1: Copy hashedPassword from user_encryption_keys to users
- // ============================================================
- await knex.raw(`
+ const result = await knex.raw("SHOW statement_timeout");
+ const originalTimeout = result.rows[0].statement_timeout;
+
+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+
+ const migrationStart = Date.now();
+ // eslint-disable-next-line no-console
+ const log = (msg: string) => console.log(`[username-merge] ${msg} (${Date.now() - migrationStart}ms elapsed)`);
+
+ try {
+ // ============================================================
+ // Step 1: Copy hashedPassword from user_encryption_keys to users
+ // ============================================================
+ log("Step 1: copying hashedPassword...");
+ let t = Date.now();
+ await knex.raw(`
UPDATE "${TableName.Users}" u
SET "hashedPassword" = uek."hashedPassword"
FROM "${TableName.UserEncryptionKey}" uek
@@ -15,135 +29,239 @@ export async function up(knex: Knex): Promise<void> {
AND uek."hashedPassword" IS NOT NULL
AND u."hashedPassword" IS NULL
`);
+ log(`Step 1 done in ${Date.now() - t}ms`);
- // ============================================================
- // Step 2: Mark provider-verified flags based on authMethods
- // ============================================================
- await knex.raw(`
+ // ============================================================
+ // Step 2: Mark provider-verified flags based on authMethods
+ // ============================================================
+ log("Step 2: setting provider-verified flags...");
+ t = Date.now();
+ await knex.raw(`
UPDATE "${TableName.Users}"
SET "isGitHubVerified" = TRUE
WHERE "authMethods" @> ARRAY['github']::text[]
AND ("isGitHubVerified" IS NULL OR "isGitHubVerified" = FALSE)
`);
- await knex.raw(`
+ await knex.raw(`
UPDATE "${TableName.Users}"
SET "isGoogleVerified" = TRUE
WHERE "authMethods" @> ARRAY['google']::text[]
AND ("isGoogleVerified" IS NULL OR "isGoogleVerified" = FALSE)
`);
- await knex.raw(`
+ await knex.raw(`
UPDATE "${TableName.Users}"
SET "isGitLabVerified" = TRUE
WHERE "authMethods" @> ARRAY['gitlab']::text[]
AND ("isGitLabVerified" IS NULL OR "isGitLabVerified" = FALSE)
`);
+ log(`Step 2 done in ${Date.now() - t}ms`);
- // ============================================================
- // 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
+ // ============================================================
+ // 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)
+ log("Step 3: fetching FK references...");
+ t = Date.now();
+ const fkRefs = await knex.raw(`
+ SELECT
+ c.conrelid::regclass::text AS table_name,
+ a.attname AS column_name
+ FROM pg_constraint c
+ JOIN pg_attribute a
+ ON a.attrelid = c.conrelid
+ AND a.attnum = ANY(c.conkey)
+ WHERE c.contype = 'f'
+ AND c.confrelid = 'public.users'::regclass
+ AND c.confkey = ARRAY(
+ SELECT attnum FROM pg_attribute
+ WHERE attrelid = 'public.users'::regclass AND attname = 'id'
+ )
`);
+ const userFkReferences = fkRefs.rows as { table_name: string; column_name: string }[];
+ log(`Step 3: found ${userFkReferences.length} FK refs in ${Date.now() - t}ms`);
- 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 users = await knex(TableName.Users)
- .select("id", "username", "isEmailVerified", "isAccepted")
- .whereIn("id", userIds)
- .orderBy("createdAt", "asc");
-
- // Find orphan users (no org membership) among duplicates
- const memberships = await knex(TableName.Membership)
- .select("actorUserId")
- .distinct("actorUserId")
- .whereIn("actorUserId", userIds)
- .where("scope", AccessScope.Organization);
-
- const usersWithMembership = new Set(memberships.map((r) => r.actorUserId));
-
- // Delete: incomplete users (not verified OR not accepted) + orphan users (no org membership)
- const deletableIds = users
- .filter((u) => !u.isEmailVerified || !u.isAccepted || !usersWithMembership.has(u.id))
- .map((u) => u.id);
-
- if (deletableIds.length > 0) {
- await knex(TableName.Users).whereIn("id", deletableIds).del();
+ // Phase 1: Ghost all simple-deletable duplicate users
+ // DELETE is too slow (~3.4s per user due to 48 FK constraint checks even on empty refs).
+ // Instead, randomize username/email and mark as ghost so they're invisible and don't conflict.
+ log("Phase 1: finding and ghosting simple duplicates...");
+ t = Date.now();
+ const ghostResult = await knex.raw(`
+ WITH duplicate_groups AS (
+ SELECT LOWER(email) AS email
+ FROM "${TableName.Users}"
+ WHERE email IS NOT NULL AND "isGhost" = FALSE
+ GROUP BY LOWER(email)
+ HAVING COUNT(*) > 1
+ ),
+ duplicate_users AS (
+ SELECT u.id, u."isEmailVerified", u."isAccepted"
+ FROM "${TableName.Users}" u
+ JOIN duplicate_groups dg ON LOWER(u.email) = dg.email
+ WHERE u."isGhost" = FALSE
+ ),
+ users_with_membership AS (
+ SELECT DISTINCT m."actorUserId"
+ FROM "${TableName.Membership}" m
+ JOIN duplicate_users du ON du.id = m."actorUserId"
+ WHERE m.scope = '${AccessScope.Organization}'
+ ),
+ to_ghost AS (
+ SELECT du.id
+ FROM duplicate_users du
+ WHERE NOT du."isEmailVerified"
+ OR NOT du."isAccepted"
+ OR du.id NOT IN (SELECT "actorUserId" FROM users_with_membership)
+ )
+ UPDATE "${TableName.Users}" u
+ SET username = 'ghost-' || gen_random_uuid(),
+ email = 'ghost-' || gen_random_uuid() || '@ghost.local',
+ "isGhost" = TRUE,
+ "isEmailVerified" = FALSE,
+ "isAccepted" = FALSE
+ WHERE u.id IN (SELECT id FROM to_ghost)
+ RETURNING u.id
+ `);
+ const ghostedUserIds = (ghostResult.rows as { id: string }[]).map((r) => r.id);
+ log(`Phase 1 done in ${Date.now() - t}ms — ghosted ${ghostedUserIds.length} users`);
+
+ // Phase 2: Find merge groups among remaining duplicates
+ // Now that simple duplicates are ghosted, any remaining duplicate-email groups need FK reassignment
+ // Winner: prefer user whose username matches the email, otherwise earliest by createdAt
+ log("Phase 2: finding merge groups...");
+ t = Date.now();
+ const mergeResult = await knex.raw(`
+ WITH ranked AS (
+ SELECT u.id, LOWER(u.email) AS email,
+ ROW_NUMBER() OVER (
+ PARTITION BY LOWER(u.email)
+ ORDER BY (u.username = LOWER(u.email)) DESC, u."createdAt" ASC
+ ) AS rn
+ FROM "${TableName.Users}" u
+ WHERE u.email IS NOT NULL AND u."isGhost" = FALSE
+ AND LOWER(u.email) IN (
+ SELECT LOWER(email) FROM "${TableName.Users}"
+ WHERE email IS NOT NULL AND "isGhost" = FALSE
+ GROUP BY LOWER(email) HAVING COUNT(*) > 1
+ )
+ )
+ SELECT w.id AS winner_id, l.id AS loser_id
+ FROM ranked w
+ JOIN ranked l ON l.email = w.email AND l.rn > 1
+ WHERE w.rn = 1
+ ORDER BY w.id
+ `);
+
+ const mergeMap = new Map<string, string[]>();
+ for (const row of mergeResult.rows as { winner_id: string; loser_id: string }[]) {
+ const existing = mergeMap.get(row.winner_id);
+ if (existing) {
+ existing.push(row.loser_id);
+ } else {
+ mergeMap.set(row.winner_id, [row.loser_id]);
+ }
}
+ const mergeGroups = Array.from(mergeMap.entries()).map(([winnerId, loserIds]) => ({ winnerId, loserIds }));
+ log(`Phase 2 done in ${Date.now() - t}ms — ${mergeGroups.length} merge groups`);
- // Check what's left
- const remaining = users.filter((u) => !deletableIds.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("SAVEPOINT fk_reassign");
- await knex(ref.table_name)
- .whereIn(ref.column_name, loserIds)
- .update({ [ref.column_name]: winner.id });
- await knex.raw("RELEASE SAVEPOINT fk_reassign");
- } catch (err: unknown) {
- await knex.raw("ROLLBACK TO SAVEPOINT fk_reassign");
- // 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;
- }
+ // Phase 3: FK reassignment + ghost merge losers
+ // One UPDATE per FK table using CASE to map all losers→winners at once.
+ // This is 48 queries instead of 45 groups × 24 tables = 1,080 queries.
+ const allMergeLoserIds: string[] = mergeGroups.flatMap((g) => g.loserIds);
+
+ // Build loser→winner mapping
+ const loserToWinner = new Map<string, string>();
+ for (const { winnerId, loserIds } of mergeGroups) {
+ for (const loserId of loserIds) {
+ loserToWinner.set(loserId, winnerId);
+ }
+ }
+
+ log(`Phase 3: reassigning FKs across ${userFkReferences.length} tables for ${allMergeLoserIds.length} losers...`);
+ t = Date.now();
+ let tablesProcessed = 0;
+ for (const ref of userFkReferences) {
+ const refStart = Date.now();
+ const caseClauses = allMergeLoserIds
+ .map((loserId) => `WHEN '${loserId}'::uuid THEN '${loserToWinner.get(loserId)!}'::uuid`)
+ .join(" ");
+
+ try {
+ await knex.raw("SAVEPOINT fk_reassign");
+ await knex.raw(
+ `
+ UPDATE "${ref.table_name}"
+ SET "${ref.column_name}" = CASE "${ref.column_name}" ${caseClauses} END
+ WHERE "${ref.column_name}" = ANY(?)
+ `,
+ [allMergeLoserIds]
+ );
+ await knex.raw("RELEASE SAVEPOINT fk_reassign");
+ } catch (err: unknown) {
+ await knex.raw("ROLLBACK TO SAVEPOINT fk_reassign");
+ if ((err as { code?: string })?.code !== "23505") {
+ throw err;
}
}
- // Now delete losers — any remaining CASCADE refs will be cleaned up,
- // SET NULL refs were already reassigned or will be nulled
- await knex(TableName.Users).whereIn("id", loserIds).del();
+ tablesProcessed += 1;
+ const refElapsed = Date.now() - refStart;
+ if (refElapsed > 200) {
+ log(
+ `Phase 3: table ${tablesProcessed}/${userFkReferences.length} ${ref.table_name}.${ref.column_name} took ${refElapsed}ms`
+ );
+ }
}
- }
+ log(`Phase 3: FK reassignment done in ${Date.now() - t}ms — processed ${tablesProcessed} tables`);
- // Final step: update all remaining users where username != LOWER(email)
- await knex.raw(`
+ // Ghost merge losers
+ t = Date.now();
+ if (allMergeLoserIds.length > 0) {
+ await knex.raw(
+ `
+ UPDATE "${TableName.Users}"
+ SET username = 'ghost-' || gen_random_uuid(),
+ email = 'ghost-' || gen_random_uuid() || '@ghost.local',
+ "isGhost" = TRUE,
+ "isEmailVerified" = FALSE,
+ "isAccepted" = FALSE
+ WHERE id = ANY(?)
+ `,
+ [allMergeLoserIds]
+ );
+ }
+ log(`Phase 3: ghosted ${allMergeLoserIds.length} merge losers in ${Date.now() - t}ms`);
+
+ // Phase 4: Clean up memberships and aliases for users ghosted by this migration
+ const allGhostedIds = [...ghostedUserIds, ...allMergeLoserIds];
+ log(`Phase 4: cleaning up memberships and aliases for ${allGhostedIds.length} ghosted users...`);
+ t = Date.now();
+ if (allGhostedIds.length > 0) {
+ await knex(TableName.Membership).whereIn("actorUserId", allGhostedIds).del();
+ await knex(TableName.UserAliases).whereIn("userId", allGhostedIds).del();
+ }
+ log(`Phase 4 done in ${Date.now() - t}ms`);
+
+ // Final step: update all remaining users where username != LOWER(email)
+ log("Final step: normalizing usernames...");
+ t = Date.now();
+ await knex.raw(`
UPDATE "${TableName.Users}"
SET username = LOWER(email)
WHERE email IS NOT NULL
AND username != LOWER(email)
`);
+ log(`Final step done in ${Date.now() - t}ms`);
+ log(`Migration complete — total ${Date.now() - migrationStart}ms`);
+ } finally {
+ await knex.raw(`SET statement_timeout = '${originalTimeout}'`);
+ }
}
export async function down(): Promise<void> {
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 3dc0569018..09d60a082c 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -176,7 +176,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
email: email.toLowerCase(),
firstName,
lastName: lastName as string,
- callbackPort,
+ callbackPort: callbackPort || undefined,
authProvider: (req as unknown as FastifyRequest).ssoConfig?.authProvider,
orgId: (req as unknown as FastifyRequest).ssoConfig?.orgId,
ip: requestContext.get("ip") || "",
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 8ba6e5d9da..09f0d06346 100644
--- a/backend/src/ee/services/email-domain/email-domain-service.ts
+++ b/backend/src/ee/services/email-domain/email-domain-service.ts
@@ -192,12 +192,34 @@ export const emailDomainServiceFactory = ({
});
}
- const updatedEmailDomain = await emailDomainDAL.updateById(emailDomainId, {
- status: EmailDomainStatus.Verified,
- verifiedAt: new Date()
+ const updatedEmailDomain = 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: emailDomainRecord.domain, status: EmailDomainStatus.Verified },
+ tx
+ );
+ if (platformExisting) {
+ return { error: "This domain is already verified by an organization.", data: null } as const;
+ }
+
+ const data = await emailDomainDAL.updateById(
+ emailDomainId,
+ {
+ status: EmailDomainStatus.Verified,
+ verifiedAt: new Date()
+ },
+ tx
+ );
+
+ return { error: null, data } as const;
});
- return { emailDomain: updatedEmailDomain };
+ if (updatedEmailDomain.error) {
+ throw new BadRequestError({ message: updatedEmailDomain.error });
+ }
+
+ return { emailDomain: updatedEmailDomain.data };
};
const listEmailDomains = async ({ actor, actorId, actorAuthMethod, actorOrgId, orgId }: TListEmailDomainsDTO) => {
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 ad30fdbd96..7a21480f44 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -136,7 +136,7 @@ export const ldapConfigServiceFactory = ({
scope: OrganizationActionScope.ParentOrganization,
actor,
actorId,
- orgId: actorOrgId,
+ orgId,
actorAuthMethod,
actorOrgId
});
diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts
index c2e80df919..9f8f787871 100644
--- a/backend/src/services/super-admin/super-admin-service.ts
+++ b/backend/src/services/super-admin/super-admin-service.ts
@@ -1217,16 +1217,19 @@ export const superAdminServiceFactory = ({
return { error: "This domain is already verified by an organization.", data: null } as const;
}
- const data = await emailDomainDAL.create({
- orgId,
- domain: domain.toLowerCase(),
- verificationMethod: "admin",
- verificationCode: crypto.randomBytes(16).toString("hex"),
- verificationRecordName: `_infisical-verification.${domain.toLowerCase()}`,
- status: "verified",
- verifiedAt: new Date(),
- codeExpiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)
- });
+ const data = await emailDomainDAL.create(
+ {
+ orgId,
+ domain: domain.toLowerCase(),
+ verificationMethod: "admin",
+ verificationCode: crypto.randomBytes(16).toString("hex"),
+ verificationRecordName: `_infisical-verification.${domain.toLowerCase()}`,
+ status: "verified",
+ verifiedAt: new Date(),
+ codeExpiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)
+ },
+ tx
+ );
return { error: undefined, data } as const;
});
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 2d5a5edc34..c998b27262 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -177,7 +177,7 @@ export const userServiceFactory = ({
}
// Silently check if another user already has this email - don't send OTP if email is taken
- const existingUser = await userDAL.findOne({ username: newEmail }, tx);
+ const existingUser = await userDAL.findOne({ username: normalizedNewEmail }, tx);
if (!existingUser) {
// Generate 6-digit OTP
const otpCode = await tokenService.createTokenForUser({
diff --git a/frontend/src/pages/middlewares/authenticate.tsx b/frontend/src/pages/middlewares/authenticate.tsx
index 92c8c98f38..c040a86546 100644
--- a/frontend/src/pages/middlewares/authenticate.tsx
+++ b/frontend/src/pages/middlewares/authenticate.tsx
@@ -36,6 +36,9 @@ export const Route = createFileRoute("/_authenticate")({
})
);
+ context.queryClient.removeQueries({
+ queryKey: authKeys.getAuthToken
+ });
throw redirect({
to: "/login"
});