1. import time
  2. import hashlib
  3. def guard_api_payload(payload, monitoring_key, monitoring_interval=5):
  4. """
  5. Guards API payload execution for monitoring purposes.
  6. Args:
  7. payload (dict): The API payload to be executed.
  8. monitoring_key (str): A unique key for monitoring the payload.
  9. monitoring_interval (int): The interval (in seconds) for monitoring.
  10. Returns:
  11. bool: True if the payload is executed, False otherwise. Returns False if monitoring fails.
  12. """
  13. try:
  14. # Generate a hash of the payload for monitoring
  15. payload_hash = hashlib.sha256(str(payload).encode('utf-8')).hexdigest()
  16. # Check if the payload has been monitored recently
  17. timestamp = time.time()
  18. # Retrieve the last monitored payload hash and timestamp (simulated storage)
  19. last_monitored_hash = get_last_monitored_hash(monitoring_key)
  20. last_monitored_timestamp = get_last_monitored_timestamp(monitoring_key)
  21. # Check if the payload is new or if it's older than the monitoring interval
  22. if payload_hash != last_monitored_hash or (timestamp - last_monitored_timestamp) > monitoring_interval:
  23. # Payload is new or hasn't been monitored recently
  24. log_payload(payload, monitoring_key) # Log the payload for monitoring
  25. execute_api_payload(payload) # Execute the API payload
  26. # Update the last monitored hash and timestamp
  27. update_last_monitored(monitoring_key, payload_hash, timestamp)
  28. return True # Execution successful
  29. else:
  30. # Payload has been monitored recently, prevent execution
  31. log_ignored_payload(payload, monitoring_key) # Log that the payload was ignored
  32. return False # Execution blocked
  33. except Exception as e:
  34. log_error(f"Error during payload guarding: {e}")
  35. return False # Indicate failure
  36. def get_last_monitored_hash(key):
  37. """Simulates retrieving the last monitored hash from a storage."""
  38. # Replace with your actual storage mechanism (e.g., database, file)
  39. try:
  40. with open("payload_monitoring_data.txt", "r") as f:
  41. lines = f.readlines()
  42. if lines:
  43. return lines[0].strip()
  44. else:
  45. return None
  46. except FileNotFoundError:
  47. return None
  48. def get_last_monitored_timestamp(key):
  49. """Simulates retrieving the last monitored timestamp from a storage."""
  50. # Replace with your actual storage mechanism
  51. try:
  52. with open("payload_monitoring_data.txt", "r") as f:
  53. lines = f.readlines()
  54. if lines:
  55. return lines[1].strip()
  56. else:
  57. return 0
  58. except FileNotFoundError:
  59. return 0
  60. def update_last_monitored(key, hash_value, timestamp):
  61. """Simulates updating the last monitored hash and timestamp in storage."""
  62. # Replace with your actual storage mechanism
  63. with open("payload_monitoring_data.txt", "w") as f:
  64. f.write(hash_value + "\n")
  65. f.write(str(timestamp) + "\n")
  66. def log_payload(payload, key):
  67. """Logs the payload for monitoring purposes."""
  68. print(f"Monitoring Key: {key}, Payload: {payload}")
  69. def log_ignored_payload(payload, key):
  70. """Logs the ignored payload for monitoring purposes."""
  71. print(f"Monitoring Key: {key}, Payload: {payload} - Ignored (already monitored)")
  72. def log_error(message):
  73. """Logs error messages."""
  74. print(f"Error: {message}")
  75. def execute_api_payload(payload):
  76. """Simulates executing the API payload."""
  77. print(f"Executing API payload: {payload}")
  78. if __name__ == '__main__':
  79. # Example Usage
  80. monitoring_key = "my_api_key"
  81. # First execution - payload is monitored
  82. payload1 = {"data": "some data"}
  83. guard_api_payload(payload1, monitoring_key)
  84. # Second execution - payload is blocked
  85. payload2 = {"data": "different data"}
  86. guard_api_payload(payload2, monitoring_key

Add your comment