Security Case StudyEvidence: Verified8 min read•October 30, 2026

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.

Ajay Thakkar
Ajay ThakkarAuthor
Full-Stack Developer & Software Architect
Editorial architectural diagram of 2FA bypass and edge proxy matcher remediation
Cover: Architectural schematic of Next.js 16 Edge Proxy matcher bypass and controller invariant guard.
⚡ Engineering Metrics & Invariant Profile
Vulnerability Class
CWE-287 / Broken 2FA
CVSS v3.1 Severity
7.5 (High / AV:N)
Evidence Status
Verified (Lab Repro)
Remediation
Zero-Trust Defense

Responsible Disclosure & Scope Notice

🔒 RESPONSIBLE DISCLOSURE
Safe Lab Reproduction: This security case study was conducted and reproduced exclusively in an authorized local development sandbox. All customer data, production secrets, and database credentials have been omitted or sanitized in accordance with OWASP Coordinated Vulnerability Disclosure standards. The underlying vulnerability was patched and verified with automated regression tests before public publication.


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.

DimensionDetails
ApplicationIndrani Jewellers — Luxury E-Commerce & Inventory Management Engine
Technology StackNext.js 16.2 (Turbopack, App Router), TypeScript, NextAuth, MongoDB Atlas, Mongoose
Affected FeatureAdmin Catalog Creation Pipeline (POST /api/products)
Vulnerability ClassCWE-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.

codeSanitized Environment
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 Mutation

The 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/products route 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:

typescriptSanitized Environment
// 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:

bashSanitized Environment
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 Forbidden with error payload:
{"error": "Two-factor authentication required", "code": "2FA_REQUIRED"}
  • Actual (Vulnerable) Behavior: HTTP/1.1 201 Created with 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):

typescriptSanitized Environment
// 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):

typescriptSanitized Environment
// 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 reusable verifyAdminSession helper that strictly verifies both role AND is2FAVerified:

typescriptSanitized Environment
// 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:

CheckSafeguard RulePurpose
1Controller Defense InvariantEvery state-changing API must independently verify 2FA status, even if behind middleware.
2Partial Session IsolationDo not issue JWTs containing role: 'admin' until the second factor has been validated.
3Namespace SeparationPrefix all privileged endpoints with /api/admin/ rather than sharing public root namespaces.
4Deny-by-Default MatchersRoute matchers should use allowlists for public assets and protect everything else by default.
5CI/CD Security TestsAutomated 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:

typescriptSanitized Environment
// 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 in app/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.

Connected Production System

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.

Tags:#Security Case Study#Next.js 16#Indrani Jewellers#2FA Bypass#Edge Proxy#OWASP API1#Zero Trust Architecture#CWE-287
← Back to Engineering Hub
Open to Contract & Full-Time Roles

Ready to build your next product?

Whether you need a high-scale SaaS platform, a bespoke e-commerce store, or a high-performance web app, I'm ready to collaborate.

© 2026 Ajay Thakkar. Built with Next.js, TypeScript & Tailwind CSS.