Gate passkey removal on the same step-up as second-factor removal

DELETE /api/auth/passkeys/{id} took a plain cookie session or a wildcard
Bearer, while DELETE /api/auth/me/mfa/webauthn/{id} beside it demanded a
fresh factor proof. The softer gate sat on the primary sign-in credential:
the last-method check stops an account locking itself out, but nothing
stopped a hijacked session stripping the credentials the owner signs in
with.

The route now goes through requireMfaManagementAuth, the same gate the
security-key removal uses, in a new "if-enrolled" mode. An account with a
second factor pays the full price on either transport — a freshly verified
cookie session, or a factor-proved X-Step-Up elevation on Bearer, so the
native client keeps the capability rather than being sent to the website.
An account with no second factor keeps the contract it had, because a gate
it can never satisfy is not a safeguard but a locked door in front of its
own credential list.

The elevation is spent immediately before the delete, so a foreign id or a
refused last credential does not burn a proof that then has to be minted
again. The route is added to the elevation allowlist with its reason, and
the either-factor enrolment test that was written out three times in the
API kit is now one function.
This commit is contained in:
Marc-André Bombeck committed 2026-08-23 16:55:59 +02:00
1 parent fffdc83ca4
commit e3be71f0e5
7 files changed
+392 -42

No files matched your search

@@ -16,6 +16,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/api-handler", () => ({
apiHandler: (fn: unknown) => fn,
requireAuth: vi.fn(),
requireMfaManagementAuth: vi.fn(),
}));
vi.mock("@/lib/db", () => ({
@@ -35,8 +36,8 @@ vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
import { PATCH } from "../route";
import { requireAuth } from "@/lib/api-handler";
import { DELETE, PATCH } from "../route";
import { requireAuth, requireMfaManagementAuth } from "@/lib/api-handler";
import { prisma } from "@/lib/db";
const USER = { id: "user-1", username: "u", passwordHash: "argon2id$…" };
@@ -70,9 +71,18 @@ type Handler = (
ctx: { params: Promise<{ id: string }> },
) => Promise<Response>;
const commitElevation = vi.fn().mockResolvedValue(undefined);
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(requireAuth).mockResolvedValue({ user: USER } as never);
commitElevation.mockClear().mockResolvedValue(undefined);
vi.mocked(requireMfaManagementAuth).mockResolvedValue({
transport: "cookie",
user: USER,
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
commitElevation,
} as never);
});
describe("PATCH /api/auth/passkeys/{id} — the rename refusal", () => {
@@ -155,3 +165,104 @@ describe("PATCH /api/auth/passkeys/{id} — the rename refusal", () => {
expect(prisma.passkey.update).not.toHaveBeenCalled();
});
});
/**
* The removal's gate, and what it must NOT be.
*
* A passkey is the primary sign-in credential and it came off a plain session,
* while the second-factor key next door demanded a fresh proof. The route now
* asks the same gate the second-factor removal asks — but with
* `freshFactor: "if-enrolled"`, not `true`. That distinction is the whole
* design: `true` refuses an account with no second factor outright, and most
* accounts holding a passkey have nothing else enrolled, so `true` would take
* their own credential list away from them.
*
* The gate itself is behavioural and lives against a real database in
* `tests/integration/step-up-elevation.test.ts` (E14). What is pinned here is
* what this file can prove without one: the route asks for the right mode, and
* it spends the proof only when it is actually about to delete.
*
* Mutation check: change the option to `true` and the first case goes red; move
* `commitElevation()` above the ownership check and the third goes red; drop it
* altogether and the second goes red.
*/
describe("DELETE /api/auth/passkeys/{id} — the removal's gate", () => {
const mkDelete = () =>
new Request("http://localhost/api/auth/passkeys/pk-1", {
method: "DELETE",
});
it("asks for the step-up gate in its if-enrolled mode", async () => {
vi.mocked(prisma.passkey.findUnique).mockResolvedValue({
id: "pk-1",
userId: USER.id,
name: "Phone",
} as never);
vi.mocked(prisma.passkey.count).mockResolvedValue(2 as never);
vi.mocked(prisma.passkey.delete).mockResolvedValue({} as never);
await (DELETE as unknown as Handler)(mkDelete(), { params });
expect(requireMfaManagementAuth).toHaveBeenCalledWith({
freshFactor: "if-enrolled",
});
// Not `true`: that arm refuses an account with no second factor, which is
// a lockout on this route rather than a safeguard.
expect(requireMfaManagementAuth).not.toHaveBeenCalledWith({
freshFactor: true,
});
});
it("spends the proof once, on the way to the delete", async () => {
vi.mocked(prisma.passkey.findUnique).mockResolvedValue({
id: "pk-1",
userId: USER.id,
name: "Phone",
} as never);
vi.mocked(prisma.passkey.count).mockResolvedValue(2 as never);
vi.mocked(prisma.passkey.delete).mockResolvedValue({} as never);
const res = await (DELETE as unknown as Handler)(mkDelete(), { params });
expect(res.status).toBe(200);
expect(commitElevation).toHaveBeenCalledTimes(1);
expect(prisma.passkey.delete).toHaveBeenCalledWith({
where: { id: "pk-1" },
});
});
it("does not spend the proof on another account's passkey id", async () => {
vi.mocked(prisma.passkey.findUnique).mockResolvedValue({
id: "pk-1",
userId: "someone-else",
name: "Not yours",
} as never);
const res = await (DELETE as unknown as Handler)(mkDelete(), { params });
expect(res.status).toBe(404);
expect(commitElevation).not.toHaveBeenCalled();
expect(prisma.passkey.delete).not.toHaveBeenCalled();
});
it("does not spend the proof when the last credential is refused", async () => {
vi.mocked(prisma.passkey.findUnique).mockResolvedValue({
id: "pk-1",
userId: USER.id,
name: "Only one",
} as never);
vi.mocked(prisma.passkey.count).mockResolvedValue(1 as never);
vi.mocked(requireMfaManagementAuth).mockResolvedValue({
transport: "cookie",
user: { ...USER, passwordHash: null },
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
commitElevation,
} as never);
const res = await (DELETE as unknown as Handler)(mkDelete(), { params });
expect(res.status).toBe(400);
expect(commitElevation).not.toHaveBeenCalled();
expect(prisma.passkey.delete).not.toHaveBeenCalled();
});
});
+40 -2
View File
@@ -8,7 +8,11 @@ import {
safeJson,
} from "@/lib/api-response";
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiHandler,
requireAuth,
requireMfaManagementAuth,
} from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { passkeyRenameSchema } from "@/lib/validations/auth";
@@ -61,12 +65,40 @@ export const PATCH = apiHandler(
},
);
/**
* Remove a passkey — step-up gated, on the same mechanism the second-factor
* security-key removal uses.
*
* The two deletions were not equals. Removing a registered SECOND factor
* demanded a fresh factor proof; removing a passkey, which is the PRIMARY
* sign-in credential, took a plain cookie session or a wildcard Bearer. The
* last-method check below stops an account locking itself out, but it does
* nothing about a hijacked session quietly stripping the credentials the owner
* signs in with. So this route goes through `requireMfaManagementAuth` too.
*
* Two consequences worth stating rather than discovering:
*
* BEARER IS NOT REFUSED. `requireFreshMfa` is cookie-only, so a gate built on
* it alone would have told the native client to go and use the website. The
* gate this route borrows has a Bearer arm — a step-up elevation minted
* against a re-proved factor, exactly what the app already does to remove a
* security key — so the app keeps the capability and pays the same price the
* web pays.
*
* AN ACCOUNT WITH NO SECOND FACTOR IS NOT LOCKED OUT. `freshFactor: true`
* refuses those outright, which is right for a route that manages a second
* factor and wrong here: most accounts with a passkey have nothing else
* enrolled, and they would lose the ability to remove their own credential.
* `"if-enrolled"` gates the accounts that can clear the gate and leaves the
* rest exactly where they were.
*/
export const DELETE = apiHandler(
async (
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const { user } = await requireAuth();
const auth = await requireMfaManagementAuth({ freshFactor: "if-enrolled" });
const { user } = auth;
const { id } = await params;
@@ -91,6 +123,12 @@ export const DELETE = apiHandler(
);
}
// Ownership resolved and the last-method check passed — spend the elevation
// now, so a 404 for someone else's id or a refused last credential does not
// burn a proof the caller then has to mint again. Same ordering as the
// security-key removal.
await auth.commitElevation();
await prisma.passkey.delete({ where: { id } });
await auditLog("auth.passkey.delete", {