This document explains the security measures implemented in the Mockbird application to protect API routes with user session authentication and CSRF protection.
The application now implements a comprehensive security layer that includes:
- Session-based Authentication: All API routes (except signin) require valid user sessions
- CSRF Protection: All state-changing operations (POST, PUT, DELETE, PATCH) require valid CSRF tokens
- Middleware Protection: Edge-level protection for routes and pages
- Type-safe Utilities: Reusable functions for consistent security implementation
This module provides:
validateSession(): Validates user session and returns user IDvalidateCSRFToken(): Validates CSRF tokens from requestsvalidateSessionAndCSRF(): Combined validation for complete protection
- Endpoint:
GET /api/csrf - Purpose: Generates and returns CSRF tokens for authenticated users
- Security: Only authenticated users can obtain CSRF tokens
- Implementation: Sets tokens in both response body and HTTP-only cookies
Provides:
protectedFetch(): Utility function for making CSRF-protected API requests
- Scope: Edge-level protection for all routes
- Features:
- Redirects unauthenticated users from protected pages
- Validates authentication for API routes
- Allows CSRF endpoint to handle its own auth
All API routes now use the protection utilities:
// Example: Protected route handler
import { validateSessionAndCSRF } from '@/lib/api-protection';
export async function POST(request: NextRequest) {
const validation = await validateSessionAndCSRF(request);
if (!validation.isValid) {
return validation.response;
}
// Route logic with validated user ID
const userId = validation.userId!;
// ... rest of the handler
}The frontend uses the CSRF-protected fetch utility:
// Example: Making a protected API request
import { protectedFetch } from '@/lib/protected-fetch';
const response = await protectedFetch('/api/schemas', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});- Token Generation: Client requests token from
/api/csrf - Token Storage: Token stored in HTTP-only cookie and returned in response
- Token Usage: Client includes token in
X-CSRF-TOKENheader for state-changing requests - Token Validation: Server validates token against secret and cookie
- Database Sessions: Uses NextAuth with database session strategy
- Session Validation: Every protected route validates session existence
- User Isolation: Data access restricted to authenticated user's own resources
- Token-based: Uses cryptographically secure tokens
- Double Submit Pattern: Token in both cookie and header
- State-changing Only: CSRF protection applied to POST, PUT, DELETE, PATCH
- Automatic Rotation: Tokens can be refreshed as needed
- HTTPS Enforcement: Secure cookies in production
- SameSite Cookies: Prevents cross-site request forgery
- HTTP-only Cookies: Prevents XSS token theft
- Path Restriction: Cookies scoped to application paths
Add to your .env.local:
CSRF_SECRET="your-secure-csrf-secret-key"
NEXTAUTH_SECRET="your-secure-nextauth-secret-key"
NEXTAUTH_URL="http://localhost:3000"Generate secure secrets:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"POST /api/schemas- Create schemaPUT /api/schemas/[id]- Update schemaDELETE /api/schemas/[id]- Delete schemaPOST /api/generate- Generate data
GET /api/schemas- List schemasGET /api/schemas/[id]- Get schemaGET /api/csrf- Get CSRF token
GET|POST /api/auth/[...nextauth]- NextAuth endpoints
- Always Use protectedFetch: Use the utility function for all API calls
- Handle Token Refresh: The utility automatically fetches tokens when needed
- Error Handling: Implement proper error handling for authentication failures
- Secure Environment: Use HTTPS in production
- Regular Token Rotation: Consider implementing token expiration
To test the security implementation:
- Authentication Test: Try accessing protected routes without authentication
- CSRF Test: Try making state-changing requests without CSRF tokens
- Cross-origin Test: Verify CSRF protection works against cross-origin attacks
- Session Test: Verify session validation works correctly
- CSRF Token Missing: Ensure
protectedFetchis used for state-changing operations - Session Validation Failed: Check that NextAuth is properly configured
- Middleware Conflicts: Verify middleware matcher patterns are correct
- Cookie Issues: Ensure cookies are properly set and transmitted
- Check browser network tab for CSRF token requests
- Verify session tokens in browser cookies
- Check server logs for validation errors
- Ensure environment variables are set correctly
If updating existing code:
- Replace direct
fetchcalls withprotectedFetch - Update route handlers to use protection utilities
- Add CSRF_SECRET to environment variables
- Test all protected routes
This implementation provides comprehensive security while maintaining ease of use and development efficiency.