Skip to content

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

refactor(email): update email dispatch guard methods for improved cooldown management

Victor Hugo dos Santosf9f955cfb352
diff --git a/backend/e2e-test/routes/v3/auth-email-signup.spec.ts b/backend/e2e-test/routes/v3/auth-email-signup.spec.ts
index 313e87cfb4..77883eca0b 100644
--- a/backend/e2e-test/routes/v3/auth-email-signup.spec.ts
+++ b/backend/e2e-test/routes/v3/auth-email-signup.spec.ts
@@ -1,16 +1,21 @@
import { createHmac } from "node:crypto";
import { decode } from "jsonwebtoken";
+import { Knex } from "knex";
+import { TableName } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { normalizeEmail } from "@app/lib/validator";
import { AuthTokenType } from "@app/services/auth/auth-type";
import { EmailDispatchPurpose } from "@app/services/auth/email-dispatch-guard";
import { TTestSmtpService } from "../../mocks/smtp";
+import { cleanupEmailDomains, seedVerifiedEmailDomain } from "../../testUtils/email-domains";
const smtp = () => (globalThis as unknown as { testSmtp: TTestSmtpService }).testSmtp;
const keyStore = () => (globalThis as unknown as { testKeyStore: TKeyStoreFactory }).testKeyStore;
+const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
const mailboxHashOf = (email: string) =>
createHmac("sha256", process.env.AUTH_SECRET as string)
@@ -332,10 +337,6 @@ describe("Auth Email Signup V3 - dispatch caps", () => {
await keyStore().deleteItemsByKeyIn([cooldownKeyOf(email), sendsKeyOf(email)]);
}
touched.length = 0;
- for (const key of await keyStore().getKeysByPattern("email-dispatch:*:src:*")) {
- // eslint-disable-next-line no-await-in-loop
- await keyStore().deleteItem(key);
- }
});
test("A mailbox stops receiving codes once its allowance is spent", async () => {
@@ -354,7 +355,6 @@ describe("Auth Email Signup V3 - dispatch caps", () => {
test("Alias variants of one mailbox share a single allowance", async () => {
const canonical = track("[email protected]");
- // Each of these reaches the same inbox: dots are insignificant at Gmail, +tags everywhere, and
const variants = [
@@ -397,6 +397,30 @@ describe("Auth Email Signup V3 - dispatch caps", () => {
expect(ttl).toBeLessThanOrEqual(100);
});
+ test("A request refused for an SSO-enforced domain leaves no cooldown", async () => {
+ const db = getDb();
+ const orgId = seedData1.organization.id;
+ const domain = "cap-ordering-sso.local";
+ const email = track(`blocked@${domain}`);
+
+ await seedVerifiedEmailDomain(orgId, domain, db);
+ await db(TableName.Organization).where({ id: orgId }).update({ authEnforced: true });
+
+ try {
+ const refused = await beginSignup(email);
+ expect(refused.statusCode).toBe(400);
+ expect(await keyStore().getItem(cooldownKeyOf(email))).toBeNull();
+ } finally {
+ await db(TableName.Organization).where({ id: orgId }).update({ authEnforced: false });
+ await cleanupEmailDomains(orgId, db);
+ }
+
+ smtp().clear();
+ const owner = await beginSignup(email);
+ expect(owner.statusCode).toBe(200);
+ expect(codesSentTo(email)).toBe(1);
+ });
+
test("Verifying a code clears the mailbox throttle", async () => {
const email = track("[email protected]");
@@ -413,23 +437,4 @@ describe("Auth Email Signup V3 - dispatch caps", () => {
expect(await keyStore().getItem(sendsKeyOf(email))).toBeNull();
expect(await keyStore().getItem(cooldownKeyOf(email))).toBeNull();
});
-
- test("One source cannot cycle through unlimited mailboxes", async () => {
- const SOURCE_ALLOWANCE = 20;
- let refusedAt = 0;
-
- for (let i = 1; i <= SOURCE_ALLOWANCE + 1; i += 1) {
- const email = track(`cap-source-${i}@localhost.local`);
- // eslint-disable-next-line no-await-in-loop
- const res = await beginSignup(email);
- if (res.statusCode !== 200) {
- refusedAt = i;
- expect(res.statusCode).toBe(429);
- break;
- }
- }
-
- expect(refusedAt).toBe(SOURCE_ALLOWANCE + 1);
- });
});
-
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index b033ba3821..ebeaac6dc5 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -148,8 +148,6 @@ export const KeyStorePrefixes = {
`email-dispatch:${purpose}:${mailboxHash}:cd` as const,
EmailDispatchMailboxSends: (purpose: string, mailboxHash: string) =>
`email-dispatch:${purpose}:${mailboxHash}:sends` as const,
- EmailDispatchSourceSends: (purpose: string, ipHash: string) =>
- `email-dispatch:${purpose}:src:${ipHash}:sends` as const,
EmailDispatchSourceProbe: (purpose: string, window: number) =>
`email-dispatch-abuse:${purpose}:src:${window}` as const,
EmailDispatchMailboxProbe: (purpose: string, window: number) =>
@@ -213,7 +211,6 @@ export const KeyStoreTtls = {
EmailSignupOtpInSeconds: 300, // 5 minutes
EmailDispatchCooldownInSeconds: 60, // 1 minute
EmailDispatchMailboxWindowInSeconds: 86400, // 24 hours
- EmailDispatchSourceWindowInSeconds: 3600, // 1 hour
EmailDispatchAbuseProbeInSeconds: 7200, // 2 hours
InsightsCacheInSeconds: 300, // 5 minutes
InsightsDuplicationCacheInSeconds: 3600, // 1 hour
diff --git a/backend/src/services/account-recovery/account-recovery-service.ts b/backend/src/services/account-recovery/account-recovery-service.ts
index 25ee680819..14ead61316 100644
--- a/backend/src/services/account-recovery/account-recovery-service.ts
+++ b/backend/src/services/account-recovery/account-recovery-service.ts
@@ -76,12 +76,12 @@ export const accountRecoveryServiceFactory = ({
throw err;
}
- const { mailboxHash } = await emailDispatchGuard.acquireMailboxCooldown({
+ const { mailboxHash } = await emailDispatchGuard.checkMailboxCooldown({
purpose: EmailDispatchPurpose.AccountRecovery,
email: unsanitizedUsername
});
- await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.AccountRecovery, ip });
+ await emailDispatchGuard.startMailboxCooldown({ purpose: EmailDispatchPurpose.AccountRecovery, mailboxHash });
const { isNewSource, isNewMailbox } = await emailDispatchGuard.probeTraffic({
purpose: EmailDispatchPurpose.AccountRecovery,
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index 3222d60dbf..c888601dd3 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -102,13 +102,11 @@ export const authSignupServiceFactory = ({
throw new BadRequestError({ message: "Disposable email addresses cannot be used to sign up" });
}
- const { emailHash, mailboxHash, cooldownSeconds } = await emailDispatchGuard.acquireMailboxCooldown({
+ const { emailHash, mailboxHash, cooldownSeconds } = await emailDispatchGuard.checkMailboxCooldown({
purpose: EmailDispatchPurpose.Signup,
email: sanitizedEmail
});
- await emailDispatchGuard.consumeSourceAllowance({ purpose: EmailDispatchPurpose.Signup, ip });
-
const { isNewSource, isNewMailbox } = await emailDispatchGuard.probeTraffic({
purpose: EmailDispatchPurpose.Signup,
mailboxHash,
@@ -142,6 +140,8 @@ export const authSignupServiceFactory = ({
}
}
+ await emailDispatchGuard.startMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, mailboxHash });
+
// Case sensitive email resolution
const existingUser = await userDAL.findOne({ username: sanitizedEmail });
diff --git a/backend/src/services/auth/email-dispatch-guard.test.ts b/backend/src/services/auth/email-dispatch-guard.test.ts
index f849a38b9e..904c844d13 100644
--- a/backend/src/services/auth/email-dispatch-guard.test.ts
+++ b/backend/src/services/auth/email-dispatch-guard.test.ts
@@ -4,7 +4,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, type Mock
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, RateLimitError } from "@app/lib/errors";
+import { BadRequestError } from "@app/lib/errors";
import { emailDispatchGuardFactory, EmailDispatchPurpose } from "./email-dispatch-guard";
@@ -35,7 +35,7 @@ type MockedKeyStore = Mocked<KeyStoreSlice>;
const setup = () => {
const keyStore = {
setItemWithExpiryNX: vi.fn().mockResolvedValue("OK"),
- ttl: vi.fn().mockResolvedValue(-1),
+ ttl: vi.fn().mockResolvedValue(-2),
incrementByAndRefreshExpiryIfUnderLimit: vi.fn().mockResolvedValue(1),
deleteItemsByKeyIn: vi.fn().mockResolvedValue(2),
probeDistinctMember: vi.fn().mockResolvedValue(true)
@@ -95,7 +95,7 @@ describe("emailDispatchGuard", () => {
});
});
- describe("acquireMailboxCooldown", () => {
+ describe("checkMailboxCooldown", () => {
// The signup bombing campaign varied dots and +tags; account recovery was reachable by varying
// case alone, since its lookup lowercased the address while its rate-limit key did not. Both
// collapse onto one bucket here or the cooldown is bypassable by changing a single character.
@@ -108,35 +108,32 @@ describe("emailDispatchGuard", () => {
])("%s shares the bucket of %s", async (variant, mailbox) => {
const { keyStore, guard } = setup();
- await guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: variant });
+ await guard.checkMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: variant });
- expect(keyStore.setItemWithExpiryNX).toHaveBeenCalledWith(
- KeyStorePrefixes.EmailDispatchCooldown(EmailDispatchPurpose.Signup, hmac(mailbox)),
- KeyStoreTtls.EmailDispatchCooldownInSeconds,
- "1"
+ expect(keyStore.ttl).toHaveBeenCalledWith(
+ KeyStorePrefixes.EmailDispatchCooldown(EmailDispatchPurpose.Signup, hmac(mailbox))
);
});
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({
+ await guard.checkMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" });
+ await guard.checkMailboxCooldown({
purpose: EmailDispatchPurpose.AccountRecovery,
});
- const keys = keyStore.setItemWithExpiryNX.mock.calls.map(([key]) => key);
+ const keys = keyStore.ttl.mock.calls.map(([key]) => key);
expect(new Set(keys).size).toBe(2);
});
test("reports remaining TTL when the cooldown is active", async () => {
const { keyStore, guard } = setup();
- keyStore.setItemWithExpiryNX.mockResolvedValue(null);
keyStore.ttl.mockResolvedValue(30);
const err = await expectRejected(
- guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),
+ guard.checkMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),
BadRequestError
);
@@ -145,11 +142,11 @@ describe("emailDispatchGuard", () => {
test("clamps remaining TTL to a minimum of 1", async () => {
const { keyStore, guard } = setup();
- keyStore.setItemWithExpiryNX.mockResolvedValue(null);
+ // -1 is "exists, no expiry", which still counts as an active cooldown.
keyStore.ttl.mockResolvedValue(-1);
const err = await expectRejected(
- guard.acquireMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),
+ guard.checkMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" }),
BadRequestError
);
@@ -157,72 +154,70 @@ describe("emailDispatchGuard", () => {
});
});
- describe("consumeMailboxAllowance", () => {
- const mailboxHash = hmac("[email protected]");
- const args = { purpose: EmailDispatchPurpose.Signup, mailboxHash };
-
- test("allows a send while under the cap", async () => {
+ describe("startMailboxCooldown", () => {
+ test("writes the cooldown for the normalized mailbox", async () => {
const { keyStore, guard } = setup();
- keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(5);
-
- await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(true);
- });
+ const mailboxHash = hmac("[email protected]");
- test("refuses once the cap is reached", async () => {
- const { keyStore, guard } = setup();
- keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(-1);
+ await guard.startMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, mailboxHash });
- await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(false);
+ expect(keyStore.setItemWithExpiryNX).toHaveBeenCalledWith(
+ KeyStorePrefixes.EmailDispatchCooldown(EmailDispatchPurpose.Signup, mailboxHash),
+ KeyStoreTtls.EmailDispatchCooldownInSeconds,
+ "1"
+ );
});
- test("uses the primitive that does not extend the window on refusal", async () => {
+ test("checking leaves no state behind", async () => {
const { keyStore, guard } = setup();
- await guard.consumeMailboxAllowance(args);
+ await guard.checkMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, email: "[email protected]" });
- expect(keyStore.incrementByAndRefreshExpiryIfUnderLimit).toHaveBeenCalledWith(
- KeyStorePrefixes.EmailDispatchMailboxSends(EmailDispatchPurpose.Signup, mailboxHash),
- 5,
- KeyStoreTtls.EmailDispatchMailboxWindowInSeconds
- );
+ expect(keyStore.setItemWithExpiryNX).not.toHaveBeenCalled();
});
- });
-
- describe("consumeSourceAllowance", () => {
- const args = { purpose: EmailDispatchPurpose.Signup, ip: "203.0.113.7" };
- test("hashes the source address before it reaches the store", async () => {
+ test("loses the race gracefully when another request armed it first", async () => {
const { keyStore, guard } = setup();
+ keyStore.setItemWithExpiryNX.mockResolvedValue(null);
+ keyStore.ttl.mockResolvedValue(42);
- await guard.consumeSourceAllowance(args);
+ const err = await expectRejected(
+ guard.startMailboxCooldown({ purpose: EmailDispatchPurpose.Signup, mailboxHash: hmac("[email protected]") }),
+ BadRequestError
+ );
- const [key] = keyStore.incrementByAndRefreshExpiryIfUnderLimit.mock.calls[0];
- expect(key).toContain(hmac("203.0.113.7"));
- expect(key).not.toContain("203.0.113.7");
+ expect(err.details).toMatchObject({ cooldownSeconds: 42 });
});
+ });
+
+ describe("consumeMailboxAllowance", () => {
+ const mailboxHash = hmac("[email protected]");
+ const args = { purpose: EmailDispatchPurpose.Signup, mailboxHash };
- test("admits a busy shared address while under the cap", async () => {
+ test("allows a send while under the cap", async () => {
const { keyStore, guard } = setup();
- keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(20);
+ keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(5);
- await expect(guard.consumeSourceAllowance(args)).resolves.toBeUndefined();
+ await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(true);
});
- test("refuses loudly once the cap is reached", async () => {
+ test("refuses once the cap is reached", async () => {
const { keyStore, guard } = setup();
keyStore.incrementByAndRefreshExpiryIfUnderLimit.mockResolvedValueOnce(-1);
- await expectRejected(guard.consumeSourceAllowance(args), RateLimitError);
+ await expect(guard.consumeMailboxAllowance(args)).resolves.toBe(false);
});
test("uses the primitive that does not extend the window on refusal", async () => {
const { keyStore, guard } = setup();
- await guard.consumeSourceAllowance(args);
+ await guard.consumeMailboxAllowance(args);
- const [, limit, ttl] = keyStore.incrementByAndRefreshExpiryIfUnderLimit.mock.calls[0];
- expect(limit).toBe(20);
- expect(ttl).toBe(KeyStoreTtls.EmailDispatchSourceWindowInSeconds);
+ expect(keyStore.incrementByAndRefreshExpiryIfUnderLimit).toHaveBeenCalledWith(
+ KeyStorePrefixes.EmailDispatchMailboxSends(EmailDispatchPurpose.Signup, mailboxHash),
+ 5,
+ KeyStoreTtls.EmailDispatchMailboxWindowInSeconds
+ );
});
});
diff --git a/backend/src/services/auth/email-dispatch-guard.ts b/backend/src/services/auth/email-dispatch-guard.ts
index 8b97fd4766..4160373163 100644
--- a/backend/src/services/auth/email-dispatch-guard.ts
+++ b/backend/src/services/auth/email-dispatch-guard.ts
@@ -1,7 +1,7 @@
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, RateLimitError } from "@app/lib/errors";
+import { BadRequestError } from "@app/lib/errors";
import { normalizeEmail } from "@app/lib/validator";
export enum EmailDispatchPurpose {
@@ -10,9 +10,10 @@ export enum EmailDispatchPurpose {
}
const MAX_UNCONFIRMED_SENDS_PER_MAILBOX = 5;
-const MAX_SENDS_PER_SOURCE = 20;
+// Error codes for Redis operations
const OVER_LIMIT = -1;
+const KEY_ABSENT = -2;
const computeHash = (key: string, pepper: string): string =>
crypto.nativeCrypto.createHmac("sha256", pepper).update(key).digest("hex");
@@ -42,34 +43,38 @@ export const emailDispatchGuardFactory = ({
};
};
- const acquireMailboxCooldown = async ({ purpose, email }: { purpose: EmailDispatchPurpose; email: string }) => {
+ const checkMailboxCooldown = async ({ purpose, email }: { purpose: EmailDispatchPurpose; email: string }) => {
const { emailHash, mailboxHash } = hashAddress(email);
const cooldownKey = KeyStorePrefixes.EmailDispatchCooldown(purpose, mailboxHash);
- const cooldownSeconds = KeyStoreTtls.EmailDispatchCooldownInSeconds;
+ const remaining = await keyStore.ttl(cooldownKey);
- const acquired = await keyStore.setItemWithExpiryNX(cooldownKey, cooldownSeconds, "1");
- if (!acquired) {
- const remaining = await keyStore.ttl(cooldownKey);
+ // ttl returns -2 when the key is absent and -1 when it exists without an expiry.
+ if (remaining !== KEY_ABSENT) {
throw new BadRequestError({
message: "Please wait before requesting another email",
details: { cooldownSeconds: Math.max(1, remaining) }
});
}
- return { emailHash, mailboxHash, cooldownSeconds };
+ return { emailHash, mailboxHash, cooldownSeconds: KeyStoreTtls.EmailDispatchCooldownInSeconds };
};
- const consumeSourceAllowance = async ({ purpose, ip }: { purpose: EmailDispatchPurpose; ip: string }) => {
- const appCfg = getConfig();
- const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
- KeyStorePrefixes.EmailDispatchSourceSends(purpose, computeHash(ip, appCfg.AUTH_SECRET)),
- MAX_SENDS_PER_SOURCE,
- KeyStoreTtls.EmailDispatchSourceWindowInSeconds
- );
+ const startMailboxCooldown = async ({
+ purpose,
+ mailboxHash
+ }: {
+ purpose: EmailDispatchPurpose;
+ mailboxHash: string;
+ }) => {
+ const cooldownKey = KeyStorePrefixes.EmailDispatchCooldown(purpose, mailboxHash);
+ const cooldownSeconds = KeyStoreTtls.EmailDispatchCooldownInSeconds;
- if (count === OVER_LIMIT) {
- throw new RateLimitError({
- message: "Too many requests from this network. Please try again later."
+ const acquired = await keyStore.setItemWithExpiryNX(cooldownKey, cooldownSeconds, "1");
+ if (!acquired) {
+ const remaining = await keyStore.ttl(cooldownKey);
+ throw new BadRequestError({
+ message: "Please wait before requesting another email",
+ details: { cooldownSeconds: Math.max(1, remaining) }
});
}
};
@@ -130,8 +135,8 @@ export const emailDispatchGuardFactory = ({
return {
hashAddress,
- acquireMailboxCooldown,
- consumeSourceAllowance,
+ checkMailboxCooldown,
+ startMailboxCooldown,
consumeMailboxAllowance,
clearMailboxThrottle,
probeTraffic