Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(email): update email normalization and aliasing tests for new domain
Victor Hugo dos Santosf2d0497bf12a
diff --git a/backend/src/lib/validator/validate-email.test.ts b/backend/src/lib/validator/validate-email.test.tsindex 93bb5da50c..717ae03e82 100644--- a/backend/src/lib/validator/validate-email.test.ts+++ b/backend/src/lib/validator/validate-email.test.ts@@ -2,7 +2,7 @@ import { isAliasedEmail, normalizeEmail } from "./validate-email";describe("normalizeEmail", () => {test("strips sub-addressing on every provider", () => {- expect(normalizeEmail("[email protected]")).toBe("[email protected]");+ expect(normalizeEmail("[email protected]")).toBe("[email protected]");expect(normalizeEmail("[email protected]")).toBe("[email protected]");});@@ -42,13 +42,13 @@ describe("normalizeEmail", () => {],[- "[email protected]",+ "[email protected]",[- "[email protected]",- "[email protected]",- "[email protected]",- "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",]]])("collapses every observed variant onto %s", (mailbox, variants) => {@@ -69,9 +69,9 @@ describe("normalizeEmail", () => {describe("isAliasedEmail", () => {test("flags variants but not the canonical address", () => {- expect(isAliasedEmail("[email protected]")).toBe(true);+ expect(isAliasedEmail("[email protected]")).toBe(true);expect(isAliasedEmail("[email protected]")).toBe(true);- expect(isAliasedEmail("[email protected]")).toBe(false);+ expect(isAliasedEmail("[email protected]")).toBe(false);expect(isAliasedEmail("[email protected]")).toBe(false);});});diff --git a/backend/src/services/account-recovery/account-recovery-service.ts b/backend/src/services/account-recovery/account-recovery-service.tsindex 84dd8b0329..16ef3d2a3d 100644--- a/backend/src/services/account-recovery/account-recovery-service.ts+++ b/backend/src/services/account-recovery/account-recovery-service.ts@@ -45,21 +45,13 @@ export const accountRecoveryServiceFactory = ({captchaToken?: string;}) => {await verifyPublicEmailCaptcha(captchaToken);- await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.AccountRecovery, ip });const { mailboxHash } = await emailDispatchGuard.acquireMailboxCooldown({purpose: EmailDispatchPurpose.AccountRecovery,email: unsanitizedUsername});- if (- !(await emailDispatchGuard.consumeMailboxAllowance({- purpose: EmailDispatchPurpose.AccountRecovery,- mailboxHash- }))- ) {- return;- }+ await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.AccountRecovery, ip });const sendEmail = async () => {const username = sanitizeEmail(unsanitizedUsername);@@ -67,6 +59,15 @@ export const accountRecoveryServiceFactory = ({if (!user) throw new BadRequestError({ message: "Failed to find user data" });if (user && user.isAccepted) {+ if (+ !(await emailDispatchGuard.consumeMailboxAllowance({+ purpose: EmailDispatchPurpose.AccountRecovery,+ mailboxHash+ }))+ ) {+ return;+ }+const cfg = getConfig();const recipient = user.email ?? user.username;diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.tsindex 63a6d3929c..8c80b37824 100644--- a/backend/src/services/auth/auth-signup-service.ts+++ b/backend/src/services/auth/auth-signup-service.ts@@ -97,13 +97,13 @@ export const authSignupServiceFactory = ({throw new BadRequestError({ message: "Disposable email addresses cannot be used to sign up" });}- await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.Signup, ip });-const { emailHash, mailboxHash, cooldownSeconds } = await emailDispatchGuard.acquireMailboxCooldown({purpose: EmailDispatchPurpose.Signup,email: sanitizedEmail});+ await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.Signup, ip });+const { isNewSource, isNewMailbox } = await emailDispatchGuard.probeTraffic({purpose: EmailDispatchPurpose.Signup,mailboxHash,@@ -112,14 +112,6 @@ export const authSignupServiceFactory = ({if (isNewSource) signupOtpDistinctCounter.add(1, { "signup.dimension": SignupDistinctDimension.SOURCE });if (isNewMailbox) signupOtpDistinctCounter.add(1, { "signup.dimension": SignupDistinctDimension.MAILBOX });- if (!(await emailDispatchGuard.consumeMailboxAllowance({ purpose: EmailDispatchPurpose.Signup, mailboxHash }))) {- signupOtpRequestCounter.add(1, {- ...trafficAttributes,- "signup.outcome": SignupOtpOutcome.MAILBOX_CAPPED- });- return { cooldownSeconds };- }-// Block email/password signup for domains owned by an org that enforces SSO. The org's verified// domain + IdP are authoritative, so allowing a competing password account would reopen an// account-takeover vector. Domain ownership isn't secret, so surfacing this is acceptable.@@ -139,6 +131,15 @@ export const authSignupServiceFactory = ({// Case sensitive email resolutionconst existingUser = await userDAL.findOne({ username: sanitizedEmail });++ if (!(await emailDispatchGuard.consumeMailboxAllowance({ purpose: EmailDispatchPurpose.Signup, mailboxHash }))) {+ signupOtpRequestCounter.add(1, {+ ...trafficAttributes,+ "signup.outcome": SignupOtpOutcome.MAILBOX_CAPPED+ });+ return { cooldownSeconds };+ }+if (existingUser?.isAccepted) {// Send informational email for existing accounts instead of throwing error to prevent user enumeration vulnerabilityconst appCfg = getConfig();diff --git a/backend/src/services/auth/captcha-fns.test.ts b/backend/src/services/auth/captcha-fns.test.tsindex 79002fa48f..f0fdd3f4e2 100644--- a/backend/src/services/auth/captcha-fns.test.ts+++ b/backend/src/services/auth/captcha-fns.test.ts@@ -2,11 +2,13 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import { BadRequestError } from "@app/lib/errors";-const getConfig = vi.fn();-const postForm = vi.fn();+const getConfig = vi.fn<() => { CAPTCHA_SECRET?: string }>();+const postForm = vi.fn<(url: string, body: Record<string, unknown>) => Promise<{ data: { success: boolean } }>>();vi.mock("@app/lib/config/env", () => ({ getConfig: () => getConfig() }));-vi.mock("@app/lib/config/request", () => ({ request: { postForm: (...args: unknown[]) => postForm(...args) } }));+vi.mock("@app/lib/config/request", () => ({+ request: { postForm: (url: string, body: Record<string, unknown>) => postForm(url, body) }+}));// eslint-disable-next-line import/firstimport { verifyPublicEmailCaptcha } from "./auth-fns";diff --git a/backend/src/services/auth/email-dispatch-guard.test.ts b/backend/src/services/auth/email-dispatch-guard.test.tsindex b77db4c740..f849a38b9e 100644--- a/backend/src/services/auth/email-dispatch-guard.test.ts+++ b/backend/src/services/auth/email-dispatch-guard.test.ts@@ -23,7 +23,11 @@ const hmac = (value: string) => createHmac("sha256", AUTH_SECRET).update(value).type KeyStoreSlice = Pick<TKeyStoreFactory,- "setItemWithExpiryNX" | "ttl" | "incrementByWithExpiry" | "deleteItemsByKeyIn" | "probeDistinctMember"+ | "setItemWithExpiryNX"+ | "ttl"+ | "incrementByAndRefreshExpiryIfUnderLimit"+ | "deleteItemsByKeyIn"+ | "probeDistinctMember">;type MockedKeyStore = Mocked<KeyStoreSlice>;@@ -32,7 +36,7 @@ const setup = () => {const keyStore = {setItemWithExpiryNX: vi.fn().mockResolvedValue("OK"),ttl: vi.fn().mockResolvedValue(-1),- incrementByWithExpiry: vi.fn().mockResolvedValue(1),+ incrementByAndRefreshExpiryIfUnderLimit: vi.fn().mockResolvedValue(1),deleteItemsByKeyIn: vi.fn().mockResolvedValue(2),probeDistinctMember: vi.fn().mockResolvedValue(true)} as MockedKeyStore;@@ -77,10 +81,10 @@ describe("emailDispatchGuard", () => {test("keys the code on the literal address and the throttles on the mailbox", () => {const { guard } = setup();- const { emailHash, mailboxHash } = guard.hashAddress("[email protected]");+ const { emailHash, mailboxHash } = guard.hashAddress("[email protected]");- expect(emailHash).toBe(hmac("[email protected]"));- expect(mailboxHash).toBe(hmac("[email protected]"));+ expect(emailHash).toBe(hmac("[email protected]"));+ expect(mailboxHash).toBe(hmac("[email protected]"));});test("dots survive outside Google, where they distinguish real people", () => {@@ -99,8 +103,8 @@ describe("emailDispatchGuard", () => {["[email protected]", "[email protected]"],["[email protected]", "[email protected]"],["[email protected]", "[email protected]"],- ["[email protected]", "[email protected]"],- ["[email protected]", "[email protected]"]+ ["[email protected]", "[email protected]"],+ ["[email protected]", "[email protected]"]])("%s shares the bucket of %s", async (variant, mailbox) => {const { keyStore, guard } = setup();@@ -116,10 +120,10 @@ describe("emailDispatchGuard", () => {test("signup and recovery do not share a bucket", async () => {const { keyStore, guard } = setup();- await guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" });+ await guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" });await guard.acquireMailboxCooldown({purpose: EmailDispatchPurpose.AccountRecovery,- email: "[email protected]"+ email: "[email protected]"});const keys = keyStore.setItemWithExpiryNX.mock.calls.map(([key]) => key);@@ -132,7 +136,7 @@ describe("emailDispatchGuard", () => {keyStore.ttl.mockResolvedValue(30);const err = await expectRejected(- guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),+ guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),BadRequestError);@@ -145,7 +149,7 @@ describe("emailDispatchGuard", () => {keyStore.ttl.mockResolvedValue(-1);const err = await expectRejected(- guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),+ guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),BadRequestError);@@ -154,59 +158,78 @@ describe("emailDispatchGuard", () => {});describe("consumeMailboxAllowance", () => {- test("allows up to the cap and refuses past it", async () => {+ const mailboxHash = hmac("[email protected]");+ const args = { purpose: EmailDispatchPurpose.Signup, mailboxHash };++ test("allows a send while under the cap", async () => {const { keyStore, guard } = setup();- const args = { purpose: EmailDispatchPurpose.Signup, mailboxHash: hmac("[email protected]") };+ keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(5);- keyStore.incrementByWithExpiry.mockResolvedValueOnce(5);await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(true);+ });++ test("refuses once the cap is reached", async () => {+ const { keyStore, guard } = setup();+ keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(-1);- keyStore.incrementByWithExpiry.mockResolvedValueOnce(6);await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(false);});- test("counts refused attempts, so an active campaign keeps the window rolling forward", async () => {+ test("uses the primitive that does not extend the window on refusal", async () => {const { keyStore, guard } = setup();- const mailboxHash = hmac("[email protected]");- keyStore.incrementByWithExpiry.mockResolvedValue(99);- await guard.consumeMailboxAllowance({ purpose: EmailDispatchPurpose.Signup, mailboxHash });+ await guard.consumeMailboxAllowance(args);- expect(keyStore.incrementByWithExpiry).toHaveBeenCalledWith(+ expect(keyStore.incrementByAndRefreshExpiryIfUnderLimit).toHaveBeenCalledWith(KeyStorePrefixes.EmailDispatchMailboxSends(EmailDispatchPurpose.Signup, mailboxHash),- 1,+ 5,KeyStoreTtls.EmailDispatchMailboxWindowInSeconds);});});describe("consumeSourceAllowance", () => {+ const args = { purpose: EmailDispatchPurpose.Signup, ip: "203.0.113.7" };+test("hashes the source address before it reaches the store", async () => {const { keyStore, guard } = setup();- await guard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.Signup, ip: "203.0.113.7" });+ await guard.consumeSourceAllowance(args);- const [key] = keyStore.incrementByWithExpiry.mock.calls[0];+ const [key] = keyStore.incrementByAndRefreshExpiryIfUnderLimit.mock.calls[0];expect(key).toContain(hmac("203.0.113.7"));expect(key).not.toContain("203.0.113.7");});- test("allows a busy shared address up to the cap, then refuses loudly", async () => {+ test("admits a busy shared address while under the cap", async () => {const { keyStore, guard } = setup();- const args = { purpose: EmailDispatchPurpose.Signup, ip: "203.0.113.7" };+ keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(20);- keyStore.incrementByWithExpiry.mockResolvedValueOnce(20);await expect(guard.consumeSourceAllowance(args)).resolves.toBeUndefined();+ });++ test("refuses loudly once the cap is reached", async () => {+ const { keyStore, guard } = setup();+ keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(-1);- keyStore.incrementByWithExpiry.mockResolvedValueOnce(21);await expectRejected(guard.consumeSourceAllowance(args), RateLimitError);});++ test("uses the primitive that does not extend the window on refusal", async () => {+ const { keyStore, guard } = setup();++ await guard.consumeSourceAllowance(args);++ const [, limit, ttl] = keyStore.incrementByAndRefreshExpiryIfUnderLimit.mock.calls[0];+ expect(limit).toBe(20);+ expect(ttl).toBe(KeyStoreTtls.EmailDispatchSourceWindowInSeconds);+ });});describe("clearMailboxThrottle", () => {test("drops both the cooldown and the send counter for that purpose", async () => {const { keyStore, guard } = setup();- const mailboxHash = hmac("[email protected]");+ const mailboxHash = hmac("[email protected]");await guard.clearMailboxThrottle({ purpose: EmailDispatchPurpose.AccountRecovery, mailboxHash });@@ -223,14 +246,14 @@ describe("emailDispatchGuard", () => {await guard.probeTraffic({purpose: EmailDispatchPurpose.Signup,- mailboxHash: hmac("[email protected]"),+ mailboxHash: hmac("[email protected]"),ip: "203.0.113.7"});const members = keyStore.probeDistinctMember.mock.calls.map(([, member]) => member);expect(members).toContain(hmac("203.0.113.7"));expect(members).not.toContain("203.0.113.7");- expect(members).not.toContain("[email protected]");+ expect(members).not.toContain("[email protected]");});});});diff --git a/backend/src/services/auth/email-dispatch-guard.ts b/backend/src/services/auth/email-dispatch-guard.tsindex ad2c5bbd67..8b97fd4766 100644--- a/backend/src/services/auth/email-dispatch-guard.ts+++ b/backend/src/services/auth/email-dispatch-guard.ts@@ -12,6 +12,8 @@ export enum EmailDispatchPurpose {const MAX_UNCONFIRMED_SENDS_PER_MAILBOX = 5;const MAX_SENDS_PER_SOURCE = 20;+const OVER_LIMIT = -1;+const computeHash = (key: string, pepper: string): string =>crypto.nativeCrypto.createHmac("sha256", pepper).update(key).digest("hex");@@ -24,7 +26,11 @@ export const emailDispatchGuardFactory = ({}: {keyStore: Pick<TKeyStoreFactory,- "setItemWithExpiryNX" | "ttl" | "incrementByWithExpiry" | "deleteItemsByKeyIn" | "probeDistinctMember"+ | "setItemWithExpiryNX"+ | "ttl"+ | "incrementByAndRefreshExpiryIfUnderLimit"+ | "deleteItemsByKeyIn"+ | "probeDistinctMember">;}) => {// emailHash is the literal address (OTP verification); mailboxHash is normalized (all throttles below).@@ -55,13 +61,13 @@ export const emailDispatchGuardFactory = ({const consumeSourceAllowance = async ({ purpose, ip }: { purpose: EmailDispatchPurpose; ip: string }) => {const appCfg = getConfig();- const sends = await keyStore.incrementByWithExpiry(+ const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(KeyStorePrefixes.EmailDispatchSourceSends(purpose, computeHash(ip, appCfg.AUTH_SECRET)),- 1,+ MAX_SENDS_PER_SOURCE,KeyStoreTtls.EmailDispatchSourceWindowInSeconds);- if (sends > MAX_SENDS_PER_SOURCE) {+ if (count === OVER_LIMIT) {throw new RateLimitError({message: "Too many requests from this network. Please try again later."});@@ -75,13 +81,13 @@ export const emailDispatchGuardFactory = ({purpose: EmailDispatchPurpose;mailboxHash: string;}): Promise<boolean> => {- const sends = await keyStore.incrementByWithExpiry(+ const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(KeyStorePrefixes.EmailDispatchMailboxSends(purpose, mailboxHash),- 1,+ MAX_UNCONFIRMED_SENDS_PER_MAILBOX,KeyStoreTtls.EmailDispatchMailboxWindowInSeconds);- return sends <= MAX_UNCONFIRMED_SENDS_PER_MAILBOX;+ return count !== OVER_LIMIT;};const clearMailboxThrottle = async ({