Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions apps/web/src/app/api/__tests__/billing-activate-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
import { NextRequest } from 'next/server';
import { POST } from '@/app/api/billing/activate/route';
import { getKaizenTraces, resetKaizenTracesForTests } from '@/lib/billing/kaizen-trace';

vi.mock('@/lib/billing/stripe-checkout', () => ({
getCheckoutSession: vi.fn(),
}));

vi.mock('@/lib/billing/checkout-session-store', () => ({
getCheckoutActivation: vi.fn().mockResolvedValue(null),
}));

vi.mock('@/lib/billing/subscription-events', () => ({
activateFromCheckoutSession: vi.fn(),
}));

import { getCheckoutSession } from '@/lib/billing/stripe-checkout';
import { activateFromCheckoutSession } from '@/lib/billing/subscription-events';

afterEach(() => {
vi.restoreAllMocks();
resetKaizenTracesForTests();
});

function activateRequest(sessionId: string): NextRequest {
return new NextRequest('http://localhost/api/billing/activate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sessionId }),
});
}

// This route is on PUBLIC_API_EXACT — unauthenticated, so any internet caller
// can trigger the failure branch and read the response.
describe('POST /api/billing/activate error leakage', () => {
it('never returns raw Stripe SDK error text', async () => {
const stripeMessage =
"No such checkout.session: 'cs_live_secret'; Invalid API Key provided: sk_live_****ABCD";
vi.mocked(getCheckoutSession).mockRejectedValue(new Error(stripeMessage));
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'info').mockImplementation(() => {});

const res = await POST(activateRequest('cs_live_secret'));
const raw = await res.text();

expect(res.status).toBe(500);
expect(JSON.parse(raw)).toEqual({ error: 'activation_failed', code: 'activation_failed' });
for (const token of ['sk_live', 'No such checkout.session', 'Invalid API Key']) {
expect(raw).not.toContain(token);
}

// Raw detail is retained for operators only.
expect(JSON.stringify(consoleError.mock.calls)).toContain('sk_live_****ABCD');
expect(getKaizenTraces('billing').some((t) => t.observation === stripeMessage)).toBe(true);
});

it('rejects a malformed body without echoing parser internals', async () => {
const req = new NextRequest('http://localhost/api/billing/activate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{not json',
});
const res = await POST(req);
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'invalid_json', code: 'invalid_json' });
});
});

// Every error branch must carry a stable machine-readable `code`, not only the
// two that were sanitized for CWE-209 — otherwise a client cannot branch on the
// contract this route declares.
describe('POST /api/billing/activate error-code contract', () => {
it('returns session_id_required with a matching code', async () => {
const res = await POST(activateRequest(' '));

expect(res.status).toBe(400);
expect(await res.json()).toEqual({
error: 'session_id_required',
code: 'session_id_required',
});
});

it('returns not_eligible with a matching code', async () => {
vi.mocked(getCheckoutSession).mockResolvedValue({ id: 'cs_free' } as never);
vi.mocked(activateFromCheckoutSession).mockResolvedValue(null);
vi.spyOn(console, 'info').mockImplementation(() => {});

const res = await POST(activateRequest('cs_free'));

expect(res.status).toBe(402);
expect(await res.json()).toEqual({
error: 'not_eligible',
code: 'not_eligible',
sessionId: 'cs_free',
});
});
});
Comment thread
groupthinking marked this conversation as resolved.
67 changes: 65 additions & 2 deletions apps/web/src/app/api/__tests__/billing-checkout-route.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
import { NextRequest } from 'next/server';
import { POST } from '@/app/api/billing/checkout/route';
import { resetKaizenTracesForTests } from '@/lib/billing/kaizen-trace';
import { getKaizenTraces, resetKaizenTracesForTests } from '@/lib/billing/kaizen-trace';

vi.mock('@/lib/billing/stripe-checkout', () => ({
createProCheckoutSession: vi.fn().mockResolvedValue({
Expand Down Expand Up @@ -33,10 +33,44 @@ describe('POST /api/billing/checkout', () => {
const res = await POST(req);
expect(res.status).toBe(403);
const body = await res.json();
expect(body.error).toBe('turnstile_verification_failed');
// `error` stays verbatim for client compatibility; `code` is the stable key.
expect(body).toEqual({
error: 'turnstile_verification_failed',
code: 'turnstile_rejected',
});
expect(createProCheckoutSession).not.toHaveBeenCalled();
});

// `TurnstileVerifyResult.error` is optional, so an `ok: false` result carrying
// no reason must still produce a usable pair rather than `{ error: undefined }`.
it('falls back to a stable error and code when Turnstile reports no reason', async () => {
vi.mocked(verifyTurnstileToken).mockResolvedValue({ ok: false });
const req = new NextRequest('http://localhost/api/billing/checkout', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ annual: false, turnstileToken: 'bad' }),
});
const res = await POST(req);

expect(res.status).toBe(403);
expect(await res.json()).toEqual({
error: 'turnstile_rejected',
code: 'turnstile_rejected',
});
});

it('rejects a malformed body with a matching code', async () => {
const req = new NextRequest('http://localhost/api/billing/checkout', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{not json',
});
const res = await POST(req);

expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'invalid_json', code: 'invalid_json' });
});

it('creates Stripe session on valid Turnstile token', async () => {
vi.mocked(verifyTurnstileToken).mockResolvedValue({ ok: true });
const req = new NextRequest('http://localhost/api/billing/checkout', {
Expand All @@ -54,4 +88,33 @@ describe('POST /api/billing/checkout', () => {
flow: 'acquisition',
});
});

// This route is on PUBLIC_API_EXACT — unauthenticated, so any internet caller
// can trigger this branch and read the response.
it('never returns raw Stripe SDK error text', async () => {
const stripeMessage =
"No such price: 'price_1QLiveSecret'; Invalid API Key provided: sk_live_****ABCD";
vi.mocked(verifyTurnstileToken).mockResolvedValue({ ok: true });
vi.mocked(createProCheckoutSession).mockRejectedValue(new Error(stripeMessage));
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'info').mockImplementation(() => {});

const req = new NextRequest('http://localhost/api/billing/checkout', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ annual: false, turnstileToken: 'valid' }),
});
const res = await POST(req);
const raw = await res.text();

expect(res.status).toBe(500);
expect(JSON.parse(raw)).toEqual({ error: 'checkout_failed', code: 'checkout_failed' });
for (const secret of ['price_1QLiveSecret', 'sk_live', 'No such price']) {
expect(raw).not.toContain(secret);
}

// Raw detail is retained for operators only.
expect(JSON.stringify(consoleError.mock.calls)).toContain('sk_live_****ABCD');
expect(getKaizenTraces('billing').some((t) => t.observation === stripeMessage)).toBe(true);
});
});
39 changes: 39 additions & 0 deletions apps/web/src/app/api/__tests__/billing-renew-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,43 @@ describe('POST /api/billing/renew', () => {
expect(traces.some((t) => t.stage === 'renewal_start')).toBe(true);
expect(traces.some((t) => t.stage === 'renewal_session')).toBe(true);
});

// This route is on PUBLIC_API_EXACT — unauthenticated, so any internet caller
// can trigger this branch and read the response.
it('never returns raw Stripe SDK error text', async () => {
const stripeMessage = "Invalid API Key provided: sk_live_****ABCD (account acct_1QLive)";
vi.mocked(createProCheckoutSession).mockRejectedValue(new Error(stripeMessage));
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'info').mockImplementation(() => {});

const req = new NextRequest('http://localhost/api/billing/renew', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ annual: false }),
});
const res = await POST(req);
const raw = await res.text();

expect(res.status).toBe(500);
expect(JSON.parse(raw)).toEqual({ error: 'renewal_failed', code: 'renewal_failed' });
for (const token of ['sk_live', 'acct_1QLive', 'Invalid API Key']) {
expect(raw).not.toContain(token);
}

// Raw detail is retained for operators only.
expect(JSON.stringify(consoleError.mock.calls)).toContain('sk_live_****ABCD');
expect(getKaizenTraces('billing').some((t) => t.observation === stripeMessage)).toBe(true);
});

it('rejects a malformed body with a matching code', async () => {
const req = new NextRequest('http://localhost/api/billing/renew', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{not json',
});
const res = await POST(req);

expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'invalid_json', code: 'invalid_json' });
});
});
126 changes: 126 additions & 0 deletions apps/web/src/app/api/__tests__/billing-webhook-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
import { NextRequest } from 'next/server';
import { POST } from '@/app/api/billing/webhook/route';
import { getKaizenTraces, resetKaizenTracesForTests } from '@/lib/billing/kaizen-trace';

const constructEvent = vi.fn();

vi.mock('@/lib/billing/stripe-checkout', () => ({
getStripeClient: () => ({ webhooks: { constructEvent } }),
}));

vi.mock('@/lib/billing/subscription-events', () => ({
activateFromCheckoutSession: vi.fn(),
syncFromSubscription: vi.fn(),
}));

import { activateFromCheckoutSession } from '@/lib/billing/subscription-events';

const ORIGINAL_SECRET = process.env.STRIPE_WEBHOOK_SECRET;

beforeEach(() => {
process.env.STRIPE_WEBHOOK_SECRET = 'whsec_test';
});

afterEach(() => {
if (ORIGINAL_SECRET === undefined) delete process.env.STRIPE_WEBHOOK_SECRET;
else process.env.STRIPE_WEBHOOK_SECRET = ORIGINAL_SECRET;
constructEvent.mockReset();
vi.restoreAllMocks();
resetKaizenTracesForTests();
});

function webhookRequest(body: string): NextRequest {
return new NextRequest('http://localhost/api/billing/webhook', {
method: 'POST',
headers: { 'stripe-signature': 't=1,v1=deadbeef' },
body,
});
}

// This route is on PUBLIC_API_EXACT — unauthenticated, so any internet caller
// can trigger both failure branches and read the response.
describe('POST /api/billing/webhook error leakage', () => {
it('never returns signature-verification internals', async () => {
const stripeMessage =
'No signatures found matching the expected signature for payload (tolerance 300s, scheme v1, key sk_live_****ABCD)';
constructEvent.mockImplementation(() => {
throw new Error(stripeMessage);
});
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'info').mockImplementation(() => {});

const res = await POST(webhookRequest('{"id":"evt_1"}'));
const raw = await res.text();

expect(res.status).toBe(400);
expect(JSON.parse(raw)).toEqual({ error: 'invalid_payload', code: 'invalid_payload' });
for (const token of ['sk_live', 'tolerance', 'scheme v1', 'No signatures found']) {
expect(raw).not.toContain(token);
}

// Raw detail is retained for operators only.
expect(JSON.stringify(consoleError.mock.calls)).toContain('sk_live_****ABCD');
expect(getKaizenTraces('billing').some((t) => t.observation === stripeMessage)).toBe(true);
});

it('never returns handler internals', async () => {
const handlerMessage = 'Redis connection refused at 10.0.3.14:6379 for customer cus_live_secret';
constructEvent.mockReturnValue({
type: 'checkout.session.completed',
data: { object: { id: 'cs_test_1' } },
});
vi.mocked(activateFromCheckoutSession).mockRejectedValue(new Error(handlerMessage));
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'info').mockImplementation(() => {});

const res = await POST(webhookRequest('{"id":"evt_2"}'));
const raw = await res.text();

expect(res.status).toBe(500);
expect(JSON.parse(raw)).toEqual({
error: 'webhook_handler_failed',
code: 'webhook_handler_failed',
});
for (const token of ['10.0.3.14', 'cus_live_secret', 'Redis connection refused']) {
expect(raw).not.toContain(token);
}

expect(JSON.stringify(consoleError.mock.calls)).toContain('10.0.3.14:6379');
expect(getKaizenTraces('billing').some((t) => t.observation === handlerMessage)).toBe(true);
});
});

// The two pre-flight rejections short-circuit before Stripe is ever called, so
// they never carried leaked text — but they are part of the same error contract
// and must return a stable `code` like every other branch.
describe('POST /api/billing/webhook error-code contract', () => {
it('returns webhook_not_configured with a matching code', async () => {
delete process.env.STRIPE_WEBHOOK_SECRET;

const res = await POST(webhookRequest('{"id":"evt_3"}'));

expect(res.status).toBe(503);
expect(await res.json()).toEqual({
error: 'webhook_not_configured',
code: 'webhook_not_configured',
});
expect(constructEvent).not.toHaveBeenCalled();
});

it('returns missing_signature with a matching code', async () => {
const req = new NextRequest('http://localhost/api/billing/webhook', {
method: 'POST',
body: '{"id":"evt_4"}',
});

const res = await POST(req);

expect(res.status).toBe(400);
expect(await res.json()).toEqual({
error: 'missing_signature',
code: 'missing_signature',
});
expect(constructEvent).not.toHaveBeenCalled();
});
});
Loading
Loading