Skip to content

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

fix small issues

Thiago Araujo da Silvafc5af208cd4d
diff --git a/backend/e2e-test/routes/v1/scim.spec.ts b/backend/e2e-test/routes/v1/scim.spec.ts
index dba6bc89b3..9df1e82895 100644
--- a/backend/e2e-test/routes/v1/scim.spec.ts
+++ b/backend/e2e-test/routes/v1/scim.spec.ts
@@ -670,10 +670,10 @@ describe("SCIM v1 Router", () => {
});
describe("Provisioned email changes", () => {
- const seedUser = async (db: Knex, label: string) => {
+ const seedUser = async (db: Knex, label: string, email?: string) => {
const [user] = await db(TableName.Users)
.insert({
- email: `scim-email-${label}@${TEST_DOMAIN}`,
+ email: email ?? `scim-email-${label}@${TEST_DOMAIN}`,
username: `scim-email-${label}@${TEST_DOMAIN}`,
isGhost: false,
isEmailVerified: true,
@@ -791,6 +791,49 @@ describe("SCIM v1 Router", () => {
expect(row.email).toBe(newEmail);
});
+ test("should apply an unrelated PATCH when the stored email and username have drifted", async () => {
+ const db = getDb();
+ const label = `drift-${crypto.randomUUID().slice(0, 8)}`;
+ const { user, membership } = await seedUser(db, label, `drifted-${label}@${TEST_DOMAIN}`);
+
+ const res = await testServer.inject({
+ method: "PATCH",
+ url: `/api/v1/scim/Users/${membership.id}`,
+ headers: { authorization: `Bearer ${scimToken}`, "content-type": "application/scim+json" },
+ payload: JSON.stringify({
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations: [{ op: "replace", path: "active", value: false }]
+ })
+ });
+
+ // Deprovisioning names no mailbox, so it must not trip the immutable-email refusal.
+ expect(res.statusCode).toBe(200);
+
+ const [row] = await db(TableName.Membership).where({ id: membership.id }).select("isActive");
+ expect(row.isActive).toBe(false);
+
+ const [userRow] = await db(TableName.Users).where({ id: user.id }).select("username");
+ expect(userRow.username).toBe(user.username);
+ });
+
+ test("should reject an address outside the organization's verified domains", async () => {
+ const db = getDb();
+ const label = `unverified-${crypto.randomUUID().slice(0, 8)}`;
+ const { user, membership } = await seedUser(db, label);
+
+ await db(TableName.Organization).where({ id: ORG_ID }).update({ authEnforced: true });
+
+ const res = await patchEmail(membership.id, `renamed-${label}@not-verified.local`);
+
+ expect(res.statusCode).toBe(400);
+ const body = JSON.parse(res.payload);
+ expect(body.scimType).toBe("invalidValue");
+ expect(body.schemas).toContain("urn:ietf:params:scim:api:messages:2.0:Error");
+
+ const [row] = await db(TableName.Users).where({ id: user.id }).select("username");
+ expect(row.username).toBe(user.username);
+ });
+
test("should report a conflict when the new address is already another account", async () => {
const db = getDb();
const label = `conflict-${crypto.randomUUID().slice(0, 8)}`;
@@ -808,5 +851,4 @@ describe("SCIM v1 Router", () => {
expect(row.username).toBe(user.username);
});
});
-
});
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index 5e9a5390a7..3b89a81cf6 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -645,7 +645,7 @@ export const scimServiceFactory = ({
if (!assertedEmail) return null;
const newEmail = sanitizeEmail(assertedEmail);
- if (newEmail === user.email && newEmail === user.username) return null;
+ if (newEmail === user.email || newEmail === user.username) return null;
if (!org.authEnforced) {
throw new ScimRequestError({
@@ -667,7 +667,16 @@ export const scimServiceFactory = ({
});
}
- await verifyEmailDomainOwnership({ email: newEmail, orgId: org.id, emailDomainDAL });
+ try {
+ await verifyEmailDomainOwnership({ email: newEmail, orgId: org.id, emailDomainDAL });
+ } catch (err) {
+ throw new ScimRequestError({
+ detail: `'${newEmail}' is not on a verified email domain for this organization. Add and verify the domain in Infisical, then retry.`,
+ status: 400,
+ scimType: "invalidValue",
+ error: err
+ });
+ }
const conflictingUser = await userDAL.findOne({ username: newEmail });
if (conflictingUser && conflictingUser.id !== user.id) {
@@ -684,9 +693,15 @@ export const scimServiceFactory = ({
/**
* The conflict check above is a read, not a lock, so a concurrent login or invite can take the
* address first. Report that as the conflict it is instead of a 500 carrying a constraint name.
+ * Only where a rename was actually attempted: the transaction writes other rows too, and calling
+ * an unrelated unique violation an email conflict would send the IdP chasing the wrong address.
*/
- const $toScimEmailConflictError = (err: unknown, newEmail: string) => {
- if (err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ const $toScimEmailConflictError = (err: unknown, newEmail: string | null) => {
+ if (
+ newEmail &&
+ err instanceof DatabaseError &&
+ (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation
+ ) {
return new ScimRequestError({
detail: `An Infisical account already exists for '${newEmail}'. Remove or merge that account before changing this user's email.`,
status: 409,
@@ -820,7 +835,7 @@ export const scimServiceFactory = ({
);
});
} catch (err) {
- throw $toScimEmailConflictError(err, newEmail ?? "");
+ throw $toScimEmailConflictError(err, newEmail);
}
return scimUser;
@@ -944,7 +959,7 @@ export const scimServiceFactory = ({
);
});
} catch (err) {
- throw $toScimEmailConflictError(err, newEmail ?? "");
+ throw $toScimEmailConflictError(err, newEmail);
}
return buildScimUser({
diff --git a/backend/src/services/user-alias/user-alias-fns.test.ts b/backend/src/services/user-alias/user-alias-fns.test.ts
index f95279a2dd..07bd250123 100644
--- a/backend/src/services/user-alias/user-alias-fns.test.ts
+++ b/backend/src/services/user-alias/user-alias-fns.test.ts
@@ -329,6 +329,7 @@ type TAuditLogArg = { orgId: string; event: { type: string; metadata: Record<str
const makeDeps = ({
conflictingUser = null as TUsers | null,
updateError = null as Error | null,
+ emailUpdateError = null as Error | null,
orgVerifiedDomains = ["example.com"] as string[]
} = {}) => {
const updatedRows: Record<string, unknown>[] = [];
@@ -336,6 +337,7 @@ const makeDeps = ({
findOne: vi.fn().mockResolvedValue(conflictingUser),
updateById: vi.fn().mockImplementation((id: string, update: Record<string, unknown>) => {
if (updateError) throw updateError;
+ if (emailUpdateError && update.username) throw emailUpdateError;
updatedRows.push(update);
return { ...makeUser(), ...update };
}),
@@ -439,6 +441,7 @@ describe("syncSsoUserProfile", () => {
expect(user.username).toBe("[email protected]");
expect(user.firstName).toBe("Bob");
expect(deps.updatedRows[0]).toEqual({ firstName: "Bob" });
+ expect(deps.userDAL.findOne).toHaveBeenCalledWith({ username: "[email protected]" });
const [audited] = deps.auditLogService.createAuditLog.mock.calls[0];
expect(audited.event.type).toBe("sso-user-profile-sync-conflict");
expect(audited.event.metadata.conflictingUserId).toBe("user-2");
@@ -463,6 +466,24 @@ describe("syncSsoUserProfile", () => {
expect(audited.event.type).toBe("sso-user-profile-sync-conflict");
});
+ test("keeps the name when the address is taken between the check and the write", async () => {
+ const deps = makeDeps({
+ emailUpdateError: new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
+ });
+ const user = await sync({ assertedEmail: "[email protected]", assertedFirstName: "Bob" }, deps);
+
+ expect(user.username).toBe("[email protected]");
+ expect(user.firstName).toBe("Bob");
+ expect(deps.updatedRows).toEqual([{ firstName: "Bob" }]);
+
+ const [conflict] = deps.auditLogService.createAuditLog.mock.calls[0];
+ expect(conflict.event.type).toBe("sso-user-profile-sync-conflict");
+ const [synced] = deps.auditLogService.createAuditLog.mock.calls[1];
+ expect(synced.event.type).toBe("sso-user-profile-synced");
+ expect(synced.event.metadata.newEmail).toBeUndefined();
+ expect(synced.event.metadata.newFirstName).toBe("Bob");
+ });
+
test("never fails the login on an unexpected database error", async () => {
const deps = makeDeps({ updateError: new Error("connection reset") });
const user = await sync({ assertedEmail: "[email protected]" }, deps);
diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.ts
index 8c406d6fd9..056118c191 100644
--- a/backend/src/services/user-alias/user-alias-fns.ts
+++ b/backend/src/services/user-alias/user-alias-fns.ts
@@ -212,18 +212,18 @@ export const syncSsoUserProfile = async ({
}
}
- try {
- const updatedUser = await userDAL.transaction(async (tx) => {
+ const writeProfile = (applyEmail: boolean) =>
+ userDAL.transaction(async (tx) => {
const nextUser = await userDAL.updateById(
user.id,
{
...nameChanges,
- ...(isEmailApplied ? { email: assertedUsername, username: assertedUsername } : {})
+ ...(applyEmail ? { email: assertedUsername, username: assertedUsername } : {})
},
tx
);
- if (isEmailApplied) {
+ if (applyEmail) {
await userAliasDAL.updateById(
userAlias.id,
{ emails: unique([...(userAlias.emails ?? []), assertedUsername]) },
@@ -234,43 +234,56 @@ export const syncSsoUserProfile = async ({
return nextUser;
});
- logger.info(
- { userId: user.id, orgId, externalId: userAlias.externalId, isEmailApplied },
- `Synced SSO profile from the identity provider [userId=${user.id}] [orgId=${orgId}]`
- );
-
- await auditLogService
- .createAuditLog({
- actor: { type: ActorType.PLATFORM, metadata: {} },
- orgId,
- event: {
- type: EventType.SSO_USER_PROFILE_SYNCED,
- metadata: {
- userId: user.id,
- aliasType: userAlias.aliasType,
- externalId: userAlias.externalId,
- ...(isEmailApplied ? { previousEmail: user.username, newEmail: assertedUsername } : {}),
- ...(nameChanges.firstName
- ? { previousFirstName: user.firstName, newFirstName: nameChanges.firstName }
- : {}),
- ...(nameChanges.lastName ? { previousLastName: user.lastName, newLastName: nameChanges.lastName } : {})
- }
- }
- })
- .catch((err) => {
- logger.error(err, `Failed to audit SSO profile sync for user ${user.id} in org ${orgId}`);
- });
-
- return updatedUser;
+ let updatedUser: TUsers;
+ try {
+ updatedUser = await writeProfile(isEmailApplied);
} catch (err) {
- if (err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation) {
- await logConflict();
+ if (
+ !(err instanceof DatabaseError) ||
+ (err.error as { code?: string })?.code !== DatabaseErrorCode.UniqueViolation
+ ) {
+ logger.error(err, `Failed to sync SSO profile for user ${user.id} in org ${orgId}`);
return user;
}
- logger.error(err, `Failed to sync SSO profile for user ${user.id} in org ${orgId}`);
- return user;
+ await logConflict();
+ isEmailApplied = false;
+ if (!isNameChanged) return user;
+
+ try {
+ updatedUser = await writeProfile(false);
+ } catch (nameErr) {
+ logger.error(nameErr, `Failed to sync SSO profile name for user ${user.id} in org ${orgId}`);
+ return user;
+ }
}
+
+ logger.info(
+ { userId: user.id, orgId, externalId: userAlias.externalId, isEmailApplied },
+ `Synced SSO profile from the identity provider [userId=${user.id}] [orgId=${orgId}]`
+ );
+
+ await auditLogService
+ .createAuditLog({
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ orgId,
+ event: {
+ type: EventType.SSO_USER_PROFILE_SYNCED,
+ metadata: {
+ userId: user.id,
+ aliasType: userAlias.aliasType,
+ externalId: userAlias.externalId,
+ ...(isEmailApplied ? { previousEmail: user.username, newEmail: assertedUsername } : {}),
+ ...(nameChanges.firstName ? { previousFirstName: user.firstName, newFirstName: nameChanges.firstName } : {}),
+ ...(nameChanges.lastName ? { previousLastName: user.lastName, newLastName: nameChanges.lastName } : {})
+ }
+ }
+ })
+ .catch((err) => {
+ logger.error(err, `Failed to audit SSO profile sync for user ${user.id} in org ${orgId}`);
+ });
+
+ return updatedUser;
};
type TResolveAliasUserIdsDTO = {