Skip to content

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

25.3 KB
Raw Blame
import { Knex } from "knex";
import { describe, expect, test, vi } from "vitest";

import { TUserAliases, TUsers } from "@app/db/schemas";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { DatabaseError, ForbiddenRequestError } from "@app/lib/errors";

import {
  adoptProvisionedShadowUser,
  resolveAliasUserIds,
  resolveAssertedProfileName,
  syncSsoUserProfile
} from "./user-alias-fns";
import { UserAliasType } from "./user-alias-types";

vi.mock("@app/lib/logger", () => ({
  logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() }
}));

const alias = (externalId: string, userId: string) => ({ externalId, userId });

describe("resolveAssertedProfileName", () => {
  test("uses the structured claims when the given name is asserted", () => {
    expect(resolveAssertedProfileName({ givenName: "Jane", familyName: "Doe", displayName: "Jane Doe" })).toEqual({
      firstName: "Jane",
      lastName: "Doe"
    });
  });

  test("keeps the given name even when no surname is asserted", () => {
    expect(resolveAssertedProfileName({ givenName: "Jane" })).toEqual({ firstName: "Jane", lastName: "" });
  });

  // The regression this function exists for: the composite name carries the surname already, so
  // taking the surname from family_name as well rendered it twice ("Jane Doe Doe").
  test("removes the surname from the composite name when the given name is missing", () => {
    expect(resolveAssertedProfileName({ familyName: "Doe", displayName: "Jane Doe" })).toEqual({
      firstName: "Jane",
      lastName: "Doe"
    });
  });

  test("removes a multi-part surname from the composite name", () => {
    expect(resolveAssertedProfileName({ familyName: "García López", displayName: "Juan García López" })).toEqual({
      firstName: "Juan",
      lastName: "García López"
    });
  });

  // A family-name-first locale puts the surname at the start, so the suffix match must not fire and
  // the whole name is kept as-is rather than being split on a guess.
  test("keeps the whole composite name when the surname is not a trailing part of it", () => {
    expect(resolveAssertedProfileName({ familyName: "Nagy", displayName: "Nagy János" })).toEqual({
      firstName: "Nagy János",
      lastName: ""
    });
  });

  test("keeps the whole composite name when a suffix follows the surname", () => {
    expect(resolveAssertedProfileName({ familyName: "Doe", displayName: "Jane Doe Jr." })).toEqual({
      firstName: "Jane Doe Jr.",
      lastName: ""
    });
  });

  test("keeps the whole composite name when only part of the surname trails it", () => {
    expect(resolveAssertedProfileName({ familyName: "García López", displayName: "Juan López" })).toEqual({
      firstName: "Juan López",
      lastName: ""
    });
  });

  test("keeps the composite name when no surname is asserted", () => {
    expect(resolveAssertedProfileName({ displayName: "Jane Doe" })).toEqual({
      firstName: "Jane Doe",
      lastName: ""
    });
  });

  // Stripping here would leave an empty first name, so the composite is kept whole instead.
  test("keeps the composite name when it consists only of the surname", () => {
    expect(resolveAssertedProfileName({ familyName: "Doe", displayName: "Doe" })).toEqual({
      firstName: "Doe",
      lastName: ""
    });
  });

  test("still resolves when the given name repeats the surname", () => {
    expect(resolveAssertedProfileName({ familyName: "Doe", displayName: "Doe Doe" })).toEqual({
      firstName: "Doe",
      lastName: "Doe"
    });
  });

  test("ignores whitespace-only assertions", () => {
    expect(resolveAssertedProfileName({ givenName: "   ", familyName: "  ", displayName: "  Jane Doe  " })).toEqual({
      firstName: "Jane Doe",
      lastName: ""
    });
  });

  // Every one of these attributes is multi-valued in the LDAP schema, so ldapjs returns a string[]
  // for any entry that carries a second value, and an IdP can assert a JSON array just as well.
  test("takes the first value when an assertion is multi-valued", () => {
    expect(
      resolveAssertedProfileName({
        givenName: ["Jane", "Janet"],
        familyName: ["Doe", "Smith"],
        displayName: "Jane Doe"
      })
    ).toEqual({ firstName: "Jane", lastName: "Doe" });
  });

  test("removes the surname from a multi-valued composite name", () => {
    expect(resolveAssertedProfileName({ familyName: "Doe", displayName: ["Jane Doe", "jdoe"] })).toEqual({
      firstName: "Jane",
      lastName: "Doe"
    });
  });

  // ldapjs renders an attribute with no values as an empty array rather than omitting it.
  test("ignores empty and whitespace-only values inside an assertion", () => {
    expect(resolveAssertedProfileName({ givenName: [], familyName: ["  ", "Doe"], displayName: ["Jane Doe"] })).toEqual(
      {
        firstName: "Jane",
        lastName: "Doe"
      }
    );
  });

  test("returns null when nothing usable is asserted", () => {
    expect(resolveAssertedProfileName({})).toBeNull();
    expect(resolveAssertedProfileName({ familyName: "Doe" })).toBeNull();
    expect(resolveAssertedProfileName({ givenName: null, familyName: null, displayName: null })).toBeNull();
    expect(resolveAssertedProfileName({ givenName: [], familyName: [], displayName: [] })).toBeNull();
  });
});

describe("resolveAliasUserIds", () => {
  test("resolves an identifier to the user its alias points at", () => {
    const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
      identifiers: ["[email protected]"],
      aliases: [alias("[email protected]", "user-1")]
    });

    expect(userIdByIdentifier.get("[email protected]")).toBe("user-1");
    expect(ambiguousIdentifiers).toEqual([]);
  });

  // externalId is case-sensitive (OIDC Core says so for `sub`), so a differently-cased identifier
  // is a different subject and must not resolve.
  test("does not match an identifier whose case differs from the stored externalId", () => {
    const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
      identifiers: ["[email protected]"],
      aliases: [alias("[email protected]", "user-1")]
    });

    expect(userIdByIdentifier.size).toBe(0);
    expect(ambiguousIdentifiers).toEqual([]);
  });

  test("treats one user holding several aliases under the same externalId as one account", () => {
    const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
      identifiers: ["[email protected]"],
      aliases: [alias("[email protected]", "user-1"), alias("[email protected]", "user-1")]
    });

    expect(userIdByIdentifier.get("[email protected]")).toBe("user-1");
    expect(ambiguousIdentifiers).toEqual([]);
  });

  test("reports an identifier that reaches two distinct users as ambiguous and resolves it to nobody", () => {
    const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
      identifiers: ["[email protected]"],
      aliases: [alias("[email protected]", "user-1"), alias("[email protected]", "user-2")]
    });

    expect(userIdByIdentifier.has("[email protected]")).toBe(false);
    expect(ambiguousIdentifiers).toEqual(["[email protected]"]);
  });

  // Counterpart to the test above: matching is exact, so case-variant aliases on two different
  // people are two different subjects, not an ambiguity.
  test("keeps case-variant aliases on different accounts distinct rather than ambiguous", () => {
    const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
      identifiers: ["[email protected]"],
      aliases: [alias("[email protected]", "user-1"), alias("[email protected]", "user-2")]
    });

    expect(userIdByIdentifier.get("[email protected]")).toBe("user-2");
    expect(ambiguousIdentifiers).toEqual([]);
  });

  test("leaves an identifier with no alias unresolved", () => {
    const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
      identifiers: ["[email protected]"],
      aliases: [alias("[email protected]", "user-1")]
    });

    expect(userIdByIdentifier.size).toBe(0);
    expect(ambiguousIdentifiers).toEqual([]);
  });

  test("handles empty inputs", () => {
    expect(resolveAliasUserIds({ identifiers: [], aliases: [] })).toEqual({
      userIdByIdentifier: new Map(),
      ambiguousIdentifiers: []
    });
  });
});

const ORG_ID = "org-1";
const EXTERNAL_ID = "[email protected]";
const ASSERTED_EMAIL = "[email protected]";

const shadowUser = (overrides: Partial<TUsers> = {}) =>
  ({
    id: "shadow-1",
    username: EXTERNAL_ID,
    email: EXTERNAL_ID,
    isGhost: false,
    isAccepted: false,
    isEmailVerified: false,
    hashedPassword: null,
    ...overrides
  }) as TUsers;

const OTHER_ORG_ID = "org-2";

const buildDeps = ({
  candidate = shadowUser(),
  existingAlias = null,
  membership = [{ id: "membership-1", scopeOrgId: ORG_ID, isActive: true }],
  orgs = []
}: {
  candidate?: TUsers | null;
  existingAlias?: object | null;
  membership?: object[];
  orgs?: object[];
} = {}) => {
  const userDAL = {
    findOne: vi.fn().mockResolvedValue(candidate),
    updateById: vi
      .fn()
      .mockImplementation((id: string, update: Partial<TUsers>) => ({ ...shadowUser(), ...update, id }))
  };
  const userAliasDAL = { findOne: vi.fn().mockResolvedValue(existingAlias) };
  const orgDAL = {
    findMembership: vi.fn().mockResolvedValue(membership),
    find: vi.fn().mockResolvedValue(orgs)
  };
  // A real tx aborts on the unique violation, so the update has to run inside a savepoint for the
  // recovery lookup (and the caller's remaining writes) to stay runnable. `transaction` off a tx is
  // knex's savepoint; the handle is distinct here so the tests can tell the two scopes apart.
  const savepoint = { savepoint: true };
  const tx = { transaction: vi.fn((cb: (sp: unknown) => unknown) => Promise.resolve(cb(savepoint))), savepoint };

  return { userDAL, userAliasDAL, orgDAL, tx, savepoint };
};

const adopt = (
  { tx, savepoint: _savepoint, ...deps }: ReturnType<typeof buildDeps>,
  externalId = EXTERNAL_ID,
  rootOrgId: string | null = null
) =>
  adoptProvisionedShadowUser({
    externalId,
    assertedEmail: ASSERTED_EMAIL,
    orgId: ORG_ID,
    rootOrgId,
    tx: tx as unknown as Knex,
    ...deps
  });

describe("adoptProvisionedShadowUser", () => {
  test("rewrites the placeholder's identity to the asserted mailbox", async () => {
    const deps = buildDeps();

    const adopted = await adopt(deps);

    expect(adopted?.user.id).toBe("shadow-1");
    expect(adopted?.adoptedFromUsername).toBe(EXTERNAL_ID);
    expect(deps.userDAL.updateById).toHaveBeenCalledWith(
      "shadow-1",
      { username: ASSERTED_EMAIL, email: ASSERTED_EMAIL },
      deps.savepoint
    );
  });

  // `sub` is case-sensitive, so this is a different subject from EXTERNAL_ID, not the same person
  // typed differently. Adopting on a folded match would hand it the other subject's access.
  test("declines an identifier that is not already canonical, rather than folding it onto a placeholder", async () => {
    const deps = buildDeps();

    expect(await adopt(deps, "[email protected]")).toBeNull();
    expect(deps.userDAL.findOne).not.toHaveBeenCalled();
  });

  test("declines an identifier padded with whitespace, which sanitizing would otherwise trim into a match", async () => {
    const deps = buildDeps();

    expect(await adopt(deps, ` ${EXTERNAL_ID} `)).toBeNull();
    expect(deps.userDAL.findOne).not.toHaveBeenCalled();
  });

  test("declines when the identifier is already the asserted email", async () => {
    const deps = buildDeps();

    expect(await adopt(deps, ASSERTED_EMAIL)).toBeNull();
    expect(deps.userDAL.findOne).not.toHaveBeenCalled();
  });

  test("declines when no placeholder exists", async () => {
    const deps = buildDeps({ candidate: null });

    expect(await adopt(deps)).toBeNull();
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test.each([
    ["a ghost user", { isGhost: true }],
    ["an accepted account", { isAccepted: true }],
    ["an email-verified account", { isEmailVerified: true }],
    ["an account holding a password", { hashedPassword: "hash" }]
  ])("declines to adopt %s", async (_label, overrides) => {
    const deps = buildDeps({ candidate: shadowUser(overrides) });

    expect(await adopt(deps)).toBeNull();
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("declines when any IdP has already bound the account", async () => {
    const deps = buildDeps({ existingAlias: { id: "alias-1" } });

    expect(await adopt(deps)).toBeNull();
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("declines when the placeholder holds no membership in this org", async () => {
    const deps = buildDeps({ membership: [{ id: "membership-1", scopeOrgId: OTHER_ORG_ID }] });

    expect(await adopt(deps)).toBeNull();
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  // Username lookup is global, so another tenant that invited the same identifier shares this row.
  // Adopting it would hand this org's IdP subject that tenant's memberships and project access.
  test("declines when the placeholder also holds a membership in an unrelated org", async () => {
    const deps = buildDeps({
      membership: [
        { id: "membership-1", scopeOrgId: ORG_ID, isActive: true },
        { id: "membership-2", scopeOrgId: OTHER_ORG_ID }
      ],
      orgs: [{ id: OTHER_ORG_ID, rootOrgId: null }]
    });

    expect(await adopt(deps)).toBeNull();
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("adopts when the extra membership is a sub-org of this one, which is the same tenant", async () => {
    const deps = buildDeps({
      membership: [
        { id: "membership-1", scopeOrgId: ORG_ID, isActive: true },
        { id: "membership-2", scopeOrgId: OTHER_ORG_ID }
      ],
      orgs: [{ id: OTHER_ORG_ID, rootOrgId: ORG_ID }]
    });

    expect((await adopt(deps))?.user.username).toBe(ASSERTED_EMAIL);
  });

  // Declining is not neutral for a deactivated member: the caller reads null as "no placeholder"
  // and creates a second account with a fresh active membership, handing them the org back.
  test("fails the login when this org's placeholder has been deactivated", async () => {
    const deps = buildDeps({ membership: [{ id: "membership-1", scopeOrgId: ORG_ID, isActive: false }] });

    await expect(adopt(deps)).rejects.toThrow(ForbiddenRequestError);
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("fails the login for a deactivated placeholder even when adoption would be declined anyway", async () => {
    const deps = buildDeps({
      existingAlias: { id: "alias-1" },
      membership: [
        { id: "membership-1", scopeOrgId: ORG_ID, isActive: false },
        { id: "membership-2", scopeOrgId: OTHER_ORG_ID, isActive: true }
      ],
      orgs: [{ id: OTHER_ORG_ID, rootOrgId: null }]
    });

    await expect(adopt(deps)).rejects.toThrow(ForbiddenRequestError);
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("yields to the winner when a concurrent write takes the asserted email first", async () => {
    const deps = buildDeps();
    const winner = { ...shadowUser(), id: "winner-1", username: ASSERTED_EMAIL } as TUsers;
    deps.userDAL.updateById.mockRejectedValueOnce(
      new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
    );
    deps.userDAL.findOne.mockResolvedValueOnce(shadowUser()).mockResolvedValueOnce(winner);

    const yielded = await adopt(deps);

    expect(yielded?.user).toBe(winner);
    // Nothing was rewritten, so the caller must not record this as an adoption.
    expect(yielded?.adoptedFromUsername).toBeNull();
    // The write was scoped to the savepoint, and the recovery lookup runs outside it on the
    // caller's transaction. Reversed, the aborted transaction would fail the lookup with 25P02.
    expect(deps.tx.transaction).toHaveBeenCalledTimes(1);
    expect(deps.userDAL.updateById).toHaveBeenCalledWith(expect.anything(), expect.anything(), deps.savepoint);
    expect(deps.userDAL.findOne).toHaveBeenLastCalledWith({ username: ASSERTED_EMAIL }, deps.tx);
  });

  test("rethrows a unique violation that no concurrent write explains", async () => {
    const deps = buildDeps();
    deps.userDAL.updateById.mockRejectedValueOnce(
      new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
    );
    deps.userDAL.findOne.mockResolvedValueOnce(shadowUser()).mockResolvedValueOnce(null);

    await expect(adopt(deps)).rejects.toThrow(DatabaseError);
  });
});

const makeUser = (overrides: Partial<TUsers> = {}) =>
  ({
    id: "user-1",
    username: "[email protected]",
    email: "[email protected]",
    firstName: "Robert",
    lastName: "Smith",
    ...overrides
  }) as TUsers;

const makeAlias = (overrides: Partial<TUserAliases> = {}) =>
  ({
    id: "alias-1",
    userId: "user-1",
    orgId: "org-1",
    aliasType: UserAliasType.OIDC,
    externalId: "[email protected]",
    emails: ["[email protected]"],
    isEmailVerified: true,
    ...overrides
  }) as TUserAliases;

type TAuditLogArg = { orgId: string; event: { type: string; metadata: Record<string, unknown> } };

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>[] = [];
  const userDAL = {
    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 };
    }),
    transaction: vi.fn().mockImplementation((cb: (tx: unknown) => unknown) => cb({}))
  };
  const userAliasDAL = { updateById: vi.fn().mockResolvedValue(undefined) };
  const emailDomainDAL = {
    findOne: vi
      .fn()
      .mockImplementation(({ domain }: { domain: string }) =>
        orgVerifiedDomains.includes(domain) ? { id: "domain-1", domain } : undefined
      )
  };
  const auditLogService = {
    createAuditLog: vi.fn<(arg: TAuditLogArg) => Promise<void>>().mockResolvedValue(undefined)
  };

  return { userDAL, userAliasDAL, emailDomainDAL, auditLogService, updatedRows };
};

const sync = (args: Record<string, unknown>, deps: ReturnType<typeof makeDeps>) =>
  syncSsoUserProfile({
    user: makeUser(),
    userAlias: makeAlias(),
    assertedEmail: "[email protected]",
    orgId: "org-1",
    isIdpAuthoritative: true,
    userDAL: deps.userDAL,
    userAliasDAL: deps.userAliasDAL,
    emailDomainDAL: deps.emailDomainDAL,
    auditLogService: deps.auditLogService,
    ...args
  } as Parameters<typeof syncSsoUserProfile>[0]);

describe("syncSsoUserProfile", () => {
  test("does nothing when the IdP is not authoritative for the account", async () => {
    const deps = makeDeps();
    const user = await sync({ assertedEmail: "[email protected]", isIdpAuthoritative: false }, deps);

    expect(user.username).toBe("[email protected]");
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
    expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();
  });

  test("does nothing when the alias is not yet verified", async () => {
    const deps = makeDeps();
    const user = await sync(
      { assertedEmail: "[email protected]", userAlias: makeAlias({ isEmailVerified: false }) },
      deps
    );

    expect(user.username).toBe("[email protected]");
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("does not write when nothing differs", async () => {
    const deps = makeDeps();
    await sync({ assertedFirstName: "Robert", assertedLastName: "Smith" }, deps);

    expect(deps.userDAL.findOne).not.toHaveBeenCalled();
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("carries a renamed mailbox onto the account and the alias", async () => {
    const deps = makeDeps();
    const user = await sync({ assertedEmail: "[email protected]" }, deps);

    expect(user.username).toBe("[email protected]");
    expect(user.email).toBe("[email protected]");
    expect(deps.userAliasDAL.updateById).toHaveBeenCalledWith(
      "alias-1",
      { emails: ["[email protected]", "[email protected]"] },
      expect.anything()
    );
    const [audited] = deps.auditLogService.createAuditLog.mock.calls[0];
    expect(audited.event.type).toBe("sso-user-profile-synced");
    expect(audited.event.metadata.previousEmail).toBe("[email protected]");
    expect(audited.event.metadata.newEmail).toBe("[email protected]");
  });

  test("syncs a changed name without touching the email", async () => {
    const deps = makeDeps();
    const user = await sync({ assertedFirstName: "Bob", assertedLastName: "Smith" }, deps);

    expect(user.firstName).toBe("Bob");
    expect(deps.updatedRows[0]).toEqual({ firstName: "Bob" });
    expect(deps.userAliasDAL.updateById).not.toHaveBeenCalled();
  });

  test("does not blank out a name the assertion omits", async () => {
    const deps = makeDeps();
    await sync({ assertedFirstName: "", assertedLastName: undefined }, deps);

    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("skips the email but keeps the name when the address belongs to another account", async () => {
    const deps = makeDeps({ conflictingUser: { ...makeUser(), id: "user-2" } as TUsers });
    const user = await sync({ assertedEmail: "[email protected]", assertedFirstName: "Bob" }, deps);

    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-email-sync-skipped");
    expect(audited.event.metadata.reason).toBe("address-taken");
    expect(audited.event.metadata.conflictingUserId).toBe("user-2");
  });

  test("leaves the account untouched when the conflicting account is the only change", async () => {
    const deps = makeDeps({ conflictingUser: { ...makeUser(), id: "user-2" } as TUsers });
    const user = await sync({ assertedEmail: "[email protected]" }, deps);

    expect(user.username).toBe("[email protected]");
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
  });

  test("never fails the login when the address is taken between the check and the write", async () => {
    const deps = makeDeps({
      updateError: new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
    });
    const user = await sync({ assertedEmail: "[email protected]" }, deps);

    expect(user.username).toBe("[email protected]");
    const [audited] = deps.auditLogService.createAuditLog.mock.calls[0];
    expect(audited.event.type).toBe("sso-user-email-sync-skipped");
    expect(audited.event.metadata.reason).toBe("address-taken");
  });

  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-email-sync-skipped");
    expect(conflict.event.metadata.reason).toBe("address-taken");
    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);

    expect(user.username).toBe("[email protected]");
    expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();
  });

  test("skips the email but keeps the name when the org does not own the address being replaced", async () => {
    const deps = makeDeps({ orgVerifiedDomains: ["new-corp.com"] });
    const user = await sync({ assertedEmail: "[email protected]", assertedFirstName: "Bob" }, deps);

    expect(user.username).toBe("[email protected]");
    expect(user.firstName).toBe("Bob");
    expect(deps.updatedRows[0]).toEqual({ firstName: "Bob" });

    const [skipped] = deps.auditLogService.createAuditLog.mock.calls[0];
    expect(skipped.event.type).toBe("sso-user-email-sync-skipped");
    expect(skipped.event.metadata.reason).toBe("domain-not-owned");
    expect(skipped.event.metadata.conflictingUserId).toBeUndefined();
  });

  test("skips the email when the org does not own the address being written", async () => {
    const deps = makeDeps({ orgVerifiedDomains: ["example.com"] });
    const user = await sync({ assertedEmail: "[email protected]" }, deps);

    expect(user.username).toBe("[email protected]");
    expect(deps.userDAL.updateById).not.toHaveBeenCalled();
    expect(deps.userDAL.findOne).not.toHaveBeenCalled();

    const [skipped] = deps.auditLogService.createAuditLog.mock.calls[0];
    expect(skipped.event.type).toBe("sso-user-email-sync-skipped");
    expect(skipped.event.metadata.reason).toBe("domain-not-owned");
  });
});