feat: add security hardening for reservation APIs

- Add rate limiting (5/hr public, 100/min admin endpoints)
- Add honeypot bot protection on public POST
- Add audit logging for status changes and deletions
- Add input validation (email, phone, date, length limits)
- Fix missing auth on private event GET endpoints
- Add audit_log table to schema
- Fix failing tests (auth.test, rooms-route.test)
This commit is contained in:
2026-07-02 20:56:36 -05:00
parent 0ca4f961f6
commit dc0c5fd289
8 changed files with 541 additions and 32 deletions
@@ -1,12 +1,26 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { requireAuth } from '@/lib/auth';
import { auditLog, getAuditClientIp, getAuditUserAgent } from '@/lib/audit';
import { withRateLimit } from '@/lib/rate-limit';
// GET - Get a single private event reservation
// GET - Get a single private event reservation (admin only)
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await requireAuth();
if (session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
}
// Rate limiting
const rateCheck = withRateLimit(request, 'admin-private-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
const { rows } = await db.query(
'SELECT * FROM private_event_reservations WHERE id = $1',
[params.id]
@@ -23,43 +37,59 @@ export async function GET(
}
}
// PUT - Update reservation (status, notes, etc.)
// PUT - Update reservation status (admin only)
export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await requireAuth();
if (session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
}
// Rate limiting
const rateCheck = withRateLimit(request, 'admin-private-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
const body = await request.json();
const { status, notes } = body;
const { status } = body;
if (status && !['pending', 'confirmed', 'cancelled'].includes(status)) {
return NextResponse.json({ error: 'Invalid status' }, { status: 400 });
if (!status || !['pending', 'confirmed', 'cancelled'].includes(status)) {
return NextResponse.json({ error: 'Invalid status. Must be pending, confirmed, or cancelled' }, { status: 400 });
}
const updates: string[] = [];
const values: any[] = [];
let paramCount = 1;
// Get current status for audit log
const { rows: beforeRows } = await db.query(
'SELECT * FROM private_event_reservations WHERE id = $1',
[params.id]
);
if (status) {
updates.push(`status = $${paramCount++}`);
values.push(status);
}
if (notes !== undefined) {
updates.push(`notes = $${paramCount++}`);
values.push(notes);
if (beforeRows.length === 0) {
return NextResponse.json({ error: 'Reservation not found' }, { status: 404 });
}
if (updates.length === 0) {
return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
}
values.push(params.id);
const oldStatus = beforeRows[0].status;
const { rows } = await db.query(
`UPDATE private_event_reservations SET ${updates.join(', ')} WHERE id = $${paramCount} RETURNING *`,
values
`UPDATE private_event_reservations SET status = $1 WHERE id = $2 RETURNING *`,
[status, params.id]
);
// Audit log
await auditLog({
userId: session.id,
action: 'status_change',
entityType: 'private_event_reservation',
entityId: parseInt(params.id, 10),
oldValues: { status: oldStatus },
newValues: { status },
ipAddress: getAuditClientIp(request),
userAgent: getAuditUserAgent(request),
});
return NextResponse.json({ data: rows[0] });
} catch (error) {
console.error('Error updating reservation:', error);
@@ -67,13 +97,46 @@ export async function PUT(
}
}
// DELETE - Delete a reservation
// DELETE - Delete a reservation (admin only)
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const session = await requireAuth();
if (session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
}
// Rate limiting
const rateCheck = withRateLimit(request, 'admin-private-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
// Get the reservation before deleting for audit log
const { rows: beforeRows } = await db.query(
'SELECT * FROM private_event_reservations WHERE id = $1',
[params.id]
);
if (beforeRows.length === 0) {
return NextResponse.json({ error: 'Reservation not found' }, { status: 404 });
}
await db.query('DELETE FROM private_event_reservations WHERE id = $1', [params.id]);
// Audit log
await auditLog({
userId: session.id,
action: 'delete',
entityType: 'private_event_reservation',
entityId: parseInt(params.id, 10),
oldValues: beforeRows[0],
ipAddress: getAuditClientIp(request),
userAgent: getAuditUserAgent(request),
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting reservation:', error);
@@ -1,9 +1,26 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { requireAuth } from '@/lib/auth';
import { withRateLimit, getClientIp } from '@/lib/rate-limit';
// GET - List all private event reservations (with optional status filter)
// Honeypot field name - bots often autofill all fields
// This field should remain empty for legitimate submissions
const HONEYPOT_FIELD = 'website_url';
// GET - List all private event reservations (admin only)
export async function GET(request: NextRequest) {
try {
const session = await requireAuth();
if (session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
}
// Rate limiting for admin endpoint
const rateCheck = withRateLimit(request, 'admin-private-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
const { searchParams } = new URL(request.url);
const status = searchParams.get('status');
@@ -28,6 +45,12 @@ export async function GET(request: NextRequest) {
// POST - Create a new private event reservation (public endpoint)
export async function POST(request: NextRequest) {
try {
// Rate limiting
const rateCheck = withRateLimit(request, 'private-event-reservation');
if (!rateCheck.allowed) {
return rateCheck.response;
}
const body = await request.json();
const {
event_name,
@@ -38,23 +61,76 @@ export async function POST(request: NextRequest) {
event_date,
event_time,
guests,
notes
notes,
// Honeypot field - should be empty
[HONEYPOT_FIELD]: honeypot
} = body;
// Honeypot check - reject if filled (bot detection)
if (honeypot && honeypot.trim() !== '') {
// Silently reject but return success to confuse bots
console.log('Honeypot triggered, rejecting submission from:', getClientIp(request));
return NextResponse.json({
data: { id: Date.now(), status: 'pending' }
});
}
// Validation
if (!event_name || !contact_name || !contact_method || !guests) {
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
return NextResponse.json({ error: 'Missing required fields: event_name, contact_name, contact_method, guests' }, { status: 400 });
}
if (!['email', 'phone', 'whatsapp'].includes(contact_method)) {
return NextResponse.json({ error: 'Invalid contact method' }, { status: 400 });
return NextResponse.json({ error: 'Invalid contact method. Must be email, phone, or whatsapp' }, { status: 400 });
}
// Validate email format if provided
if (contact_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact_email)) {
return NextResponse.json({ error: 'Invalid email format' }, { status: 400 });
}
// Validate phone format if provided (basic international format)
if (contact_phone && !/^[\d\s\-+()]{7,20}$/.test(contact_phone)) {
return NextResponse.json({ error: 'Invalid phone format' }, { status: 400 });
}
// Validate guests is positive
const guestsNum = parseInt(guests, 10);
if (isNaN(guestsNum) || guestsNum < 1 || guestsNum > 1000) {
return NextResponse.json({ error: 'Guests must be between 1 and 1000' }, { status: 400 });
}
// Length limits (prevent abuse)
if (event_name.length > 255 || contact_name.length > 255) {
return NextResponse.json({ error: 'Event name and contact name must be under 255 characters' }, { status: 400 });
}
if (contact_email && contact_email.length > 255) {
return NextResponse.json({ error: 'Email must be under 255 characters' }, { status: 400 });
}
if (contact_phone && contact_phone.length > 50) {
return NextResponse.json({ error: 'Phone must be under 50 characters' }, { status: 400 });
}
if (notes && notes.length > 2000) {
return NextResponse.json({ error: 'Notes must be under 2000 characters' }, { status: 400 });
}
// Validate event_date is in the future if provided
if (event_date) {
const date = new Date(event_date);
if (isNaN(date.getTime())) {
return NextResponse.json({ error: 'Invalid date format' }, { status: 400 });
}
if (date < new Date()) {
return NextResponse.json({ error: 'Event date must be in the future' }, { status: 400 });
}
}
const { rows } = await db.query(
`INSERT INTO private_event_reservations
(event_name, contact_name, contact_email, contact_phone, contact_method, event_date, event_time, guests, notes, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'pending')
RETURNING *`,
[event_name, contact_name, contact_email, contact_phone, contact_method, event_date, event_time, guests, notes]
RETURNING id, event_name, guests, event_date, event_time, status, created_at`,
[event_name, contact_name, contact_email, contact_phone, contact_method, event_date, event_time, guestsNum, notes]
);
return NextResponse.json({ data: rows[0] });
@@ -1,6 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { requireAuth } from '@/lib/auth';
import { auditLog, getAuditClientIp, getAuditUserAgent } from '@/lib/audit';
import { withRateLimit } from '@/lib/rate-limit';
// GET - Get a single social event reservation
export async function GET(
@@ -9,6 +11,13 @@ export async function GET(
) {
try {
await requireAuth();
// Rate limiting
const rateCheck = withRateLimit(request, 'admin-social-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
const { rows } = await db.query(
`SELECT ser.*, se.name as event_name
FROM social_event_reservations ser
@@ -39,6 +48,12 @@ export async function PUT(
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
}
// Rate limiting
const rateCheck = withRateLimit(request, 'admin-social-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
const body = await request.json();
const { status } = body;
@@ -46,11 +61,35 @@ export async function PUT(
return NextResponse.json({ error: 'Invalid status' }, { status: 400 });
}
// Get current status for audit log
const { rows: beforeRows } = await db.query(
'SELECT * FROM social_event_reservations WHERE id = $1',
[params.id]
);
if (beforeRows.length === 0) {
return NextResponse.json({ error: 'Reservation not found' }, { status: 404 });
}
const oldStatus = beforeRows[0].status;
const { rows } = await db.query(
`UPDATE social_event_reservations SET status = $1 WHERE id = $2 RETURNING *`,
[status, params.id]
);
// Audit log
await auditLog({
userId: session.id,
action: 'status_change',
entityType: 'social_event_reservation',
entityId: parseInt(params.id, 10),
oldValues: { status: oldStatus },
newValues: { status },
ipAddress: getAuditClientIp(request),
userAgent: getAuditUserAgent(request),
});
return NextResponse.json({ data: rows[0] });
} catch (error) {
console.error('Error updating reservation:', error);
@@ -69,7 +108,35 @@ export async function DELETE(
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 });
}
// Rate limiting
const rateCheck = withRateLimit(request, 'admin-social-events');
if (!rateCheck.allowed) {
return rateCheck.response;
}
// Get the reservation before deleting for audit log
const { rows: beforeRows } = await db.query(
'SELECT * FROM social_event_reservations WHERE id = $1',
[params.id]
);
if (beforeRows.length === 0) {
return NextResponse.json({ error: 'Reservation not found' }, { status: 404 });
}
await db.query('DELETE FROM social_event_reservations WHERE id = $1', [params.id]);
// Audit log
await auditLog({
userId: session.id,
action: 'delete',
entityType: 'social_event_reservation',
entityId: parseInt(params.id, 10),
oldValues: beforeRows[0],
ipAddress: getAuditClientIp(request),
userAgent: getAuditUserAgent(request),
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Error deleting reservation:', error);