1. <?php
  2. /**
  3. * Sanitizes environment variable input for scheduled runs with rate limiting.
  4. *
  5. * @param array $envVars An array of environment variables.
  6. * @param array $rateLimits An array of rate limits, where keys are variable names and values are arrays
  7. * containing 'max_calls' and 'time_window' (in seconds).
  8. * @return array Sanitized environment variables.
  9. * @throws Exception If rate limits are exceeded.
  10. */
  11. function sanitizeAndRateLimitEnvVars(array $envVars, array $rateLimits): array
  12. {
  13. $sanitizedEnvVars = [];
  14. foreach ($envVars as $name => $value) {
  15. // Sanitize input (e.g., remove potentially malicious characters)
  16. $sanitizedValue = trim(htmlspecialchars($value));
  17. // Check rate limit
  18. if (isset($rateLimits[$name])) {
  19. $limit = $rateLimits[$name];
  20. $maxCalls = $limit['max_calls'];
  21. $timeWindow = $limit['time_window'];
  22. // Implement simple rate limiting logic (can be replaced with a more robust solution)
  23. $calls = 0;
  24. $now = time();
  25. // Check for calls within the time window
  26. foreach ($envVars as $key => $val) {
  27. if ($key === $name) continue; // Skip the current variable
  28. if (isset($rateLimits[$key])) {
  29. $limitKey = $rateLimits[$key]['max_calls'];
  30. $timeWindowKey = $rateLimits[$key]['time_window'];
  31. $lastCallTime = $_SESSION['last_call_' . $key] ?? 0;
  32. if ($now - $lastCallTime < $timeWindowKey) {
  33. $calls++;
  34. }
  35. }
  36. }
  37. if ($calls >= $maxCalls) {
  38. throw new Exception("Rate limit exceeded for: " . $name);
  39. }
  40. // Update last call time for this variable
  41. $_SESSION['last_call_' . $name] = $now;
  42. }
  43. $sanitizedEnvVars[$name] = $sanitizedValue;
  44. }
  45. return $sanitizedEnvVars;
  46. }
  47. //Example usage (for testing)
  48. /*
  49. $envVars = [
  50. 'INPUT_DATA' => 'test input',
  51. 'API_KEY' => 'some_key',
  52. 'OTHER_VAR' => 'another value'
  53. ];
  54. $rateLimits = [
  55. 'API_KEY' => ['max_calls' => 5, 'time_window' => 60],
  56. 'INPUT_DATA' => ['max_calls' => 10, 'time_window' => 30]
  57. ];
  58. try {
  59. $sanitizedVars = sanitizeAndRateLimitEnvVars($envVars, $rateLimits);
  60. print_r($sanitizedVars);
  61. } catch (Exception $e) {
  62. echo "Error: " . $e->getMessage();
  63. }
  64. */
  65. ?>

Add your comment