Cap the profile email-address conflict answer

Changing the profile address asks whether another account already holds
it, and the answer is 409 versus 200 — an existence check over every
address on the instance, open to any signed-in caller. Neither route
that reaches it had a ceiling of any kind and the API wrapper supplies
no default, so the only bound on a sweep was the network.

Both routes now share one per-account bucket, ten an hour, charged
before the question is asked so a refused caller learns nothing. Only a
request whose address actually differs from the one on file is counted,
so re-saving a settings form that carries the unchanged address stays
free. The refusal is the standard 429 with Retry-After and the
X-RateLimit triple, carries `profile.update.emailRateLimited`, and is
published on both operations.
This commit is contained in:
Marc-André Bombeck committed 2026-09-11 14:05:25 +02:00
1 parent 6a5fb338b1
commit fe420f76d8
17 files changed
+596 -181

No files matched your search

@@ -0,0 +1,148 @@
/**
* The email-address conflict answer is metered, and metered before it answers.
*
* `applyProfileUpdate` is the one place both profile routes reach, and its
* 409 tells any signed-in caller whether a given address belongs to an
* account on this instance. Until this bucket existed neither route had a
* ceiling of any kind — `apiHandler` supplies none — so one account could
* walk an address book at whatever rate the network allowed.
*
* Three things are pinned here. The charge happens BEFORE the uniqueness
* probe, so a refused request never learns the answer it was refused for.
* A save that carries the address already on file is not charged at all, so
* a settings form that re-posts the whole profile does not spend an honest
* afternoon of edits on the ceiling. And the refusal carries the code the
* contract publishes.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
user: { findUnique: vi.fn(), update: vi.fn() },
},
}));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rate-limit", () => ({
checkProfileEmailRateLimit: vi.fn(),
}));
import { applyProfileUpdate } from "../profile-update";
import { prisma } from "@/lib/db";
import { checkProfileEmailRateLimit } from "@/lib/rate-limit";
const USER_ID = "user-1";
const ON_FILE = "mine@example.test";
/** The `where` clauses the helper can send, told apart by their shape. */
function selfLookups() {
return vi
.mocked(prisma.user.findUnique)
.mock.calls.filter((c) => "id" in (c[0]!.where as object));
}
function emailProbes() {
return vi
.mocked(prisma.user.findUnique)
.mock.calls.filter((c) => "email" in (c[0]!.where as object));
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.user.update).mockResolvedValue({
id: USER_ID,
username: "u",
email: ON_FILE,
} as never);
vi.mocked(checkProfileEmailRateLimit).mockResolvedValue({
allowed: true,
limit: 10,
remaining: 9,
resetAt: Date.now() + 3_600_000,
});
vi.mocked(prisma.user.findUnique).mockImplementation((async (args: {
where: Record<string, unknown>;
}) => {
if ("id" in args.where) return { email: ON_FILE };
return null;
}) as never);
});
describe("applyProfileUpdate — the email conflict is metered", () => {
it("charges the acting account before asking about the address", async () => {
await applyProfileUpdate(USER_ID, { email: "someone@example.test" });
expect(checkProfileEmailRateLimit).toHaveBeenCalledWith(USER_ID);
expect(emailProbes()).toHaveLength(1);
// Ordering, not just presence: the probe must not have run first.
const chargedAt = vi.mocked(checkProfileEmailRateLimit).mock
.invocationCallOrder[0];
const probedAt = vi.mocked(prisma.user.findUnique).mock.invocationCallOrder[
selfLookups().length
];
expect(chargedAt).toBeLessThan(probedAt);
});
it("refuses with 429 and the published code, without asking about the address", async () => {
vi.mocked(checkProfileEmailRateLimit).mockResolvedValue({
allowed: false,
limit: 10,
remaining: 0,
resetAt: Date.now() + 3_600_000,
});
const result = await applyProfileUpdate(USER_ID, {
email: "someone@example.test",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.status).toBe(429);
expect(result.errorCode).toBe("profile.update.emailRateLimited");
}
// The whole point: a refused caller is told nothing about the address.
expect(emailProbes()).toHaveLength(0);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("does not charge a save that carries the address already on file", async () => {
const result = await applyProfileUpdate(USER_ID, {
// Same address, differently typed — normalisation is what decides.
email: " Mine@Example.Test ",
heightCm: 180,
});
expect(result.ok).toBe(true);
expect(checkProfileEmailRateLimit).not.toHaveBeenCalled();
expect(emailProbes()).toHaveLength(0);
expect(prisma.user.update).toHaveBeenCalledTimes(1);
});
it("does not charge an update that never touches the address", async () => {
await applyProfileUpdate(USER_ID, { heightCm: 181 });
expect(checkProfileEmailRateLimit).not.toHaveBeenCalled();
});
it("still answers 409 when the bucket has room and the address is taken", async () => {
vi.mocked(prisma.user.findUnique).mockImplementation((async (args: {
where: Record<string, unknown>;
}) => {
if ("id" in args.where) return { email: ON_FILE };
return { id: "someone-else" };
}) as never);
const result = await applyProfileUpdate(USER_ID, {
email: "taken@example.test",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.status).toBe(409);
expect(result.errorCode).toBe("profile.update.emailInUse");
}
expect(checkProfileEmailRateLimit).toHaveBeenCalledTimes(1);
});
});
@@ -6,6 +6,9 @@ vi.mock("@/lib/db", () => ({
findUnique: vi.fn(),
update: vi.fn(),
},
// The email-address change is metered before it asks whether another
// account holds the address; the limiter talks to Postgres directly.
$queryRaw: vi.fn(),
},
}));
@@ -34,6 +37,10 @@ const STUB_USER = {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.user.update).mockResolvedValue(STUB_USER as never);
// A bucket with room left, unless a test says otherwise.
vi.mocked(prisma.$queryRaw).mockResolvedValue([
{ count: 1, reset_at: new Date(Date.now() + 60_000) },
] as never);
});
describe("applyProfileUpdate timezone validation", () => {
+39 -10
View File
@@ -13,6 +13,7 @@ import {
invalidateUserProfile,
} from "@/lib/cache/invalidate";
import { sanitiseZodIssues, type SanitisedZodIssue } from "@/lib/api-response";
import { checkProfileEmailRateLimit } from "@/lib/rate-limit";
import { z } from "zod/v4";
const extendedProfileSchema = profileSchema.extend({
@@ -238,17 +239,45 @@ export async function applyProfileUpdate(
const normalizedEmail = data.email ? data.email.trim().toLowerCase() : null;
if (data.email !== undefined && normalizedEmail) {
const existing = await prisma.user.findUnique({
where: { email: normalizedEmail },
select: { id: true },
// A settings form re-posts the whole profile, so the address arrives
// with every save whether or not it changed. Those saves ask nothing
// about anyone else's account — the address on file already belongs to
// this caller — so they skip both the uniqueness probe and the budget.
// Charging them would spend an honest afternoon of edits on the
// ceiling and lock the account out of its own settings page.
const current = await prisma.user.findUnique({
where: { id: userId },
select: { email: true },
});
if (existing && existing.id !== userId) {
return {
ok: false,
status: 409,
message: "Email already in use",
errorCode: "profile.update.emailInUse",
};
if (current?.email !== normalizedEmail) {
// Charged BEFORE the probe, not after: a refused request must not
// learn the answer it was refused for. The 409 below tells any
// signed-in caller whether an address is registered here, and until
// this bucket existed neither route that reaches it had a ceiling of
// any kind — `apiHandler` supplies no default.
const rl = await checkProfileEmailRateLimit(userId);
if (!rl.allowed) {
return {
ok: false,
status: 429,
message: "Too many email-address changes. Try again later.",
errorCode: "profile.update.emailRateLimited",
};
}
const existing = await prisma.user.findUnique({
where: { email: normalizedEmail },
select: { id: true },
});
if (existing && existing.id !== userId) {
return {
ok: false,
status: 409,
message: "Email already in use",
errorCode: "profile.update.emailInUse",
};
}
}
}