<?php
/**
* Sanitizes environment variable input for scheduled runs with rate limiting.
*
* @param array $envVars An array of environment variables.
* @param array $rateLimits An array of rate limits, where keys are variable names and values are arrays
* containing 'max_calls' and 'time_window' (in seconds).
* @return array Sanitized environment variables.
* @throws Exception If rate limits are exceeded.
*/
function sanitizeAndRateLimitEnvVars(array $envVars, array $rateLimits): array
{
$sanitizedEnvVars = [];
foreach ($envVars as $name => $value) {
// Sanitize input (e.g., remove potentially malicious characters)
$sanitizedValue = trim(htmlspecialchars($value));
// Check rate limit
if (isset($rateLimits[$name])) {
$limit = $rateLimits[$name];
$maxCalls = $limit['max_calls'];
$timeWindow = $limit['time_window'];
// Implement simple rate limiting logic (can be replaced with a more robust solution)
$calls = 0;
$now = time();
// Check for calls within the time window
foreach ($envVars as $key => $val) {
if ($key === $name) continue; // Skip the current variable
if (isset($rateLimits[$key])) {
$limitKey = $rateLimits[$key]['max_calls'];
$timeWindowKey = $rateLimits[$key]['time_window'];
$lastCallTime = $_SESSION['last_call_' . $key] ?? 0;
if ($now - $lastCallTime < $timeWindowKey) {
$calls++;
}
}
}
if ($calls >= $maxCalls) {
throw new Exception("Rate limit exceeded for: " . $name);
}
// Update last call time for this variable
$_SESSION['last_call_' . $name] = $now;
}
$sanitizedEnvVars[$name] = $sanitizedValue;
}
return $sanitizedEnvVars;
}
//Example usage (for testing)
/*
$envVars = [
'INPUT_DATA' => 'test input',
'API_KEY' => 'some_key',
'OTHER_VAR' => 'another value'
];
$rateLimits = [
'API_KEY' => ['max_calls' => 5, 'time_window' => 60],
'INPUT_DATA' => ['max_calls' => 10, 'time_window' => 30]
];
try {
$sanitizedVars = sanitizeAndRateLimitEnvVars($envVars, $rateLimits);
print_r($sanitizedVars);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
*/
?>
Add your comment