CallOut Security
Introduction
CallOut is the api endpoint managing most of the API calls in the frontend. It is crucial to ensure that it is secure and protected against common vulnerabilities.
Security validation
The callOut goes through a security validation process before processing the request. This includes:
- CSRF token validation
- Rate limiting by user ID or IP address
/**
* Function to make security checks before processing the request (CSRF token validation and rate limiting)
* @param request Request object
* @param keyPrefix Prefix to uniquely identify the rate limit key eg. GET-key or POST-key because we don't want similar limits for different methods
* @param limit number of requests allowed in a time frame (10 seconds)
* @returns { status: number; error: string }
*/
async function securityValidation(
request: NextRequest,
keyPrefix: string,
limit?: number
): Promise<{ status: number; error: string }> {
let response: { status: number; error: string } = { status: 200, error: "" };
try {
// Validate CSRF token
const csrfToken = request.headers.get("x-csrf-token") || "";
const urlReferer = request.headers.get("referer");
response = validateCsrfToken(csrfToken, urlReferer || "");
if (response.status !== 200) {
return response;
}
// Rate limit by user ID or IP address
const userId = request.headers.get("x-user-id");
if (userId) {
response = await rateLimitByKey(`${keyPrefix}-${userId}`, limit);
} else {
const ipAddress =
request.headers.get("x-real-ip") ||
request.headers.get("x-forwarded-for");
if (ipAddress)
response = await rateLimitByKey(`${keyPrefix}-${ipAddress}`, limit);
}
} catch (error: any) {
errorHandler(error);
} finally {
return response;
}
}Last updated on