Security Case Study: Product Creation Bypassed Admin 2FA in Next.js 16
A complete engineering post-mortem analyzing how an edge proxy matcher gap and controller-level trust assumption allowed direct API product injection without 2FA verification in a luxury e-commerce platform.

Responsible Disclosure & Scope Notice
01 · Introduction
The Problem
During an architecture and security audit of the Indrani Jewellers inventory management system, a high-severity authentication bypass was discovered in the catalog creation pipeline.Although the application strictly enforces Time-based One-Time Password (TOTP) two-factor authentication (2FA) for administrators logging into the web management dashboard, an attacker possessing primary credentials (email and password) could completely bypass the 2FA requirement and create, mutate, or inject inventory into the public jewelry catalog.
| Dimension | Details |
|---|---|
| Application | Indrani Jewellers — Luxury E-Commerce & Inventory Management Engine |
| Technology Stack | Next.js 16.2 (Turbopack, App Router), TypeScript, NextAuth, MongoDB Atlas, Mongoose |
| Affected Feature | Admin Catalog Creation Pipeline (POST /api/products) |
| Vulnerability Class | CWE-287: Improper Authentication / Broken Two-Factor Authentication |
| Evidence Status | ✓ Verified: In-Lab Repro — Confirmed with automated cURL exploitation script |
Why It Mattered
In a fine jewelry platform where individual items carry retail valuations between ₹50,000 and ₹5,00,000+ (certified natural diamonds, BIS hallmarked 22K/18K gold), catalog integrity is mission-critical. A compromised catalog allows rogue listings, artificial price slashing for automated checkout bots, and fraudulent certificate injection.02 · Technical Explanation
How It Works: The Architectural Disconnect
In Next.js 16 with App Router, authorization is commonly split between two operational tiers: 1. The Edge Boundary (src/proxy.ts or middleware.ts): Runs at the edge routing layer, evaluating incoming paths against a regex matcher configuration and redirecting unverified sessions to /verify-2fa.
2. The Route Handler (src/app/api/products/route.ts): Runs inside the Node.js server runtime, executing database mutations after inspecting the user session.Client Browser / Attacker
│
▼
┌──────────────────────────────────────┐
│ Next.js 16 Edge Proxy (proxy.ts) │ ◄── Evaluates matcher: ['/admin/:path*', '/api/admin/:path*']
└──────────────────┬───────────────────┘
│
[Match] │ [No Match] ──► (Bypasses Edge Inspection!)
▼ │
Redirect to /verify-2fa ▼
┌───────────────────────────────┐
│ Route Handler: /api/products │
│ Checks: role === 'admin' │
│ Omits: is2FAVerified check │
└───────────────┬───────────────┘
▼
MongoDB Catalog MutationThe vulnerability manifested because Tier 1 assumed Tier 2 would never be called without going through edge route filters, while Tier 2 assumed Tier 1 had already verified 2FA completion.
03 · Vulnerability / Failure Scenario
How It Can Be Exploited
An attacker can exploit this vulnerability if they possess or compromise an administrator's primary credentials (e.g., via password reuse, staff phishing, or credential stuffing), without needing physical access to the administrator's authenticator app or hardware token.Attacker Prerequisites
- Primary credentials (email + password) for any account possessing
role: 'admin'. - Network access to the application's public HTTP endpoints.
- No access required to the victim's TOTP device or recovery codes.
Sequence of Exploitation
1. Primary Authentication: The attacker submits credentials to/api/auth/callback/credentials. NextAuth issues a session JWT containing role: 'admin' and is2FAVerified: false.
2. Proxy Bypass: The attacker bypasses the browser dashboard UI (which would display the 2FA prompt) and directly constructs a programmatic POST request to /api/products.
3. Absence of Edge Matcher: The edge proxy skips inspection because /api/products is not included in the proxy's protected matcher array.
4. Permissive Route Handler: The route handler checks session.user.role === 'admin', finds it valid, but never evaluates session.user.is2FAVerified.
5. Database Execution: The new product is inserted directly into MongoDB Atlas.Evidence Classification of Exploitability
- ✓ Verified Direct product insertion via raw cURL using a pre-2FA session cookie.
- ✓ Verified Catalog display of injected items on the public storefront.
- ⚡ Conditional Product deletion/mutation endpoints depending on whether they share the
/api/productsroute path.
04 · Reproduction
How to Reproduce the Issue Safely
This reproduction can be executed in an isolated local environment (localhost:3000).Step 1: Establish a Semi-Authenticated Session
Simulate an admin who has submitted password credentials but has not entered their TOTP code:// Mock session state in test runner
const mockSession = {
user: {
id: "admin_test_99",
email: "admin@indranijewellers.com",
role: "admin",
isTwoFactorEnabled: true,
is2FAVerified: false // ⚠️ 2FA NOT YET COMPLETED
}
};Step 2: Issue Direct POST Request
Execute a cURL command targeting the product creation endpoint with the semi-authenticated cookie:curl -X POST http://localhost:3000/api/products \
-H "Cookie: next-auth.session-token=eyJhbGciOi..." \
-H "Content-Type: application/json" \
-d '{
"name": "Exploit Verification 18K Diamond Ring",
"mainCategory": "Rings",
"subCategory": "Diamond Rings",
"price": 100,
"grossWeight": 4.5,
"purity": "18K",
"stock": 10
}'Step 3: Observed vs Expected Behavior
- Expected Behavior:
HTTP/1.1 403 Forbiddenwith error payload:
{"error": "Two-factor authentication required", "code": "2FA_REQUIRED"}
- Actual (Vulnerable) Behavior:
HTTP/1.1 201 Createdwith payload:
{"success": true, "productId": "prod_6722a498b2"}
- Storefront Verification: The injected product immediately rendered on
http://localhost:3000/shop/rings.
05 · Root Cause and Fix
The Vulnerable Logic
Two separate files contributed to the root cause:1. The Edge Proxy Blindspot (src/proxy.ts line 133):
// VULNERABLE: Only /api/admin/ was intercepted; /api/products was omitted!
export const config = {
matcher: [
"/admin/:path*",
"/api/admin/:path*",
"/verify-2fa"
],
};2. The Route Handler Trust Assumption (src/app/api/products/route.ts line 114):
// VULNERABLE: Checked administrative role, but completely ignored 2FA verification status!
export async function POST(req: NextRequest) {
const session = await getServerSession(authOptions);
if (!session || session.user.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// ❌ Missing: if (!session.user.is2FAVerified) { ... }
const product = await Product.create(await req.json());
return NextResponse.json(product, { status: 201 });
}The Corrected Implementation (Defense-in-Depth)
We resolved the vulnerability using a two-tier zero-trust enforcement architecture:Tier 1: Controller-Level Invariant Guard
Never trust that upstream gateways or proxies have executed checks. We created a reusableverifyAdminSession helper that strictly verifies both role AND is2FAVerified:// src/lib/adminAuth.ts
import { getServerSession } from "next-auth";
import { NextResponse } from "next/server";
import { authOptions } from "@/lib/auth";
export interface AdminAuthResult {
authorized: boolean;
response?: NextResponse;
adminId?: string;
}
export async function verifyAdminSession(): Promise<AdminAuthResult> {
const session = await getServerSession(authOptions);
if (!session || !session.user?.id) {
return {
authorized: false,
response: NextResponse.json({ error: "Authentication required" }, { status: 401 }),
};
}
if (session.user.role !== "admin") {
return {
authorized: false,
response: NextResponse.json({ error: "Administrative privilege required" }, { status: 403 }),
};
}
// 🛡️ CRITICAL DEFENSE: Enforce TOTP 2FA verification invariant
if (!session.user.is2FAVerified) {
return {
authorized: false,
response: NextResponse.json(
{
error: "Two-factor authentication verification required",
code: "2FA_VERIFICATION_REQUIRED",
},
{ status: 403 }
),
};
}
return { authorized: true, adminId: session.user.id };
}Tier 2: Namespace & Proxy Matcher Realignment
All administrative API mutations were migrated under the protected/api/admin/ namespace:
- Product creation:
POST /api/admin/products - Public catalog browsing: Read-only
GET /api/products - Proxy matcher updated with strict catch-all guards.
06 · Prevention
How to Prevent This in Full-Stack Applications
Use this architectural checklist when implementing multi-factor authentication in Next.js, Remix, or Express:| Check | Safeguard Rule | Purpose |
|---|---|---|
| 1 | Controller Defense Invariant | Every state-changing API must independently verify 2FA status, even if behind middleware. |
| 2 | Partial Session Isolation | Do not issue JWTs containing role: 'admin' until the second factor has been validated. |
| 3 | Namespace Separation | Prefix all privileged endpoints with /api/admin/ rather than sharing public root namespaces. |
| 4 | Deny-by-Default Matchers | Route matchers should use allowlists for public assets and protect everything else by default. |
| 5 | CI/CD Security Tests | Automated test runners must send semi-authenticated requests to all endpoints on every pull request. |
07 · Verification
How We Proved It Was Fixed
To guarantee immunity against regressions, we constructed an automated security integration test suite:// src/scripts/test-2fa-enforcement.ts
describe('Catalog API Security Invariants', () => {
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).post('/api/admin/products').send(mockProduct);
expect(res.status).toBe(401);
});
it('rejects semi-authenticated session (2FA pending) with 403', async () => {
const res = await request(app)
.post('/api/admin/products')
.set('Cookie', pre2FaSessionCookie)
.send(mockProduct);
expect(res.status).toBe(403);
expect(res.body.code).toBe('2FA_VERIFICATION_REQUIRED');
});
it('permits fully verified session with 201', async () => {
const res = await request(app)
.post('/api/admin/products')
.set('Cookie', fullyVerifiedSessionCookie)
.send(mockProduct);
expect(res.status).toBe(201);
});
});Test Limitations & Residual Risks
- ✓ Verified The direct API bypass is 100% mitigated across product creation and mutation handlers.
- ⚡ Conditional If third-party webhooks (e.g., payment gateway callbacks) interact with inventory, they must use distinct HMAC signature verification rather than session authentication.
08 · Conclusion
Lessons Learned
1. Never conflate UI route groups with API route security: Placing a file inapp/admin/(secure)/page.tsx does not protect the API routes it calls.
2. Beware the "Partial Session" trap: Multi-factor workflows must treat intermediate tokens as strictly unprivileged until the full verification chain resolves.
3. Defense-in-depth is non-negotiable: Gateways provide performance and traffic shaping; controllers provide security and data integrity.Indrani Jewells — Luxury E-Commerce
An elegant high-end jewelry storefront built with high-trust buying workflows, rich product zoom galleries, curated bridal collection showcases, and custom order consultation requests.