main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import logging
  5. import time
  6. import tempfile
  7. from flask import Flask, jsonify
  8. from config import Config
  9. from typing import List, Tuple
  10. # Configure logging with custom handler
  11. class NtfyLogHandler(logging.Handler):
  12. """Custom logging handler that sends logs to ntfy health backends"""
  13. def __init__(self, config_obj):
  14. super().__init__()
  15. self.config = config_obj
  16. def emit(self, record):
  17. """Send log record to health backends"""
  18. if hasattr(self.config, 'ntfy_backends_health') and self.config.send_all_logs:
  19. try:
  20. log_message = self.format(record)
  21. # Get configured log level or default to WARNING
  22. min_level = getattr(logging, self.config.log_level.upper(), logging.WARNING)
  23. if record.levelno >= min_level:
  24. # Format message with appropriate emoji based on log level
  25. emoji = "🚨" if record.levelno >= logging.ERROR else "⚠️" if record.levelno >= logging.WARNING else "ℹ️"
  26. title = f"Emergency Access {record.levelname}"
  27. message = f"{emoji} {record.name}: {record.getMessage()}"
  28. send_ntfy_notification(
  29. self.config.ntfy_backends_health,
  30. message,
  31. title
  32. )
  33. except Exception:
  34. # Don't fail the application if logging notification fails
  35. pass
  36. # Configure logging
  37. logging.basicConfig(
  38. level=logging.INFO,
  39. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  40. handlers=[
  41. logging.FileHandler('/var/log/emergency-access.log'),
  42. logging.StreamHandler()
  43. ]
  44. )
  45. logger = logging.getLogger(__name__)
  46. app = Flask(__name__)
  47. # Global config instance
  48. config = None
  49. def send_ntfy_notification(backends: List[str], message: str, title: str = None) -> Tuple[bool, List[str]]:
  50. """
  51. Send notification using dschep/ntfy with global config
  52. Returns: (success, successful_backends)
  53. """
  54. successful_backends = []
  55. for backend in backends:
  56. try:
  57. # Import ntfy here to avoid import issues during startup
  58. import ntfy
  59. # Send notification using the backend name from global ntfy config
  60. if title:
  61. ntfy.notify(message, title=title, backend=backend)
  62. else:
  63. ntfy.notify(message, backend=backend)
  64. successful_backends.append(backend)
  65. logger.info(f"Notification sent successfully via {backend}")
  66. except ImportError:
  67. logger.error(f"ntfy package not available for backend {backend}")
  68. except Exception as e:
  69. logger.error(f"Failed to send notification to {backend}: {str(e)}")
  70. success = len(successful_backends) > 0
  71. return success, successful_backends
  72. def read_file_safely(file_path: str) -> Tuple[bool, str]:
  73. """
  74. Safely read file content
  75. Returns: (success, content)
  76. """
  77. try:
  78. if not os.path.exists(file_path):
  79. logger.error(f"File not found: {file_path}")
  80. return False, f"File not found: {file_path}"
  81. with open(file_path, 'r') as f:
  82. content = f.read().strip()
  83. if not content:
  84. logger.error(f"File is empty: {file_path}")
  85. return False, f"File is empty: {file_path}"
  86. return True, content
  87. except PermissionError:
  88. logger.error(f"Permission denied reading file: {file_path}")
  89. return False, f"Permission denied: {file_path}"
  90. except Exception as e:
  91. logger.error(f"Failed to read file {file_path}: {str(e)}")
  92. return False, f"Failed to read file: {str(e)}"
  93. def get_key_part():
  94. """Emergency key access endpoint"""
  95. logger.warning("EMERGENCY: Key access attempt detected")
  96. try:
  97. # Send notification first - fail-safe approach
  98. notification_success, successful_backends = send_ntfy_notification(
  99. config.ntfy_backends_key,
  100. config.ntfy_key_message,
  101. "EMERGENCY ACCESS ALERT"
  102. )
  103. if not notification_success:
  104. logger.error("CRITICAL: Failed to send notifications to any backend")
  105. return jsonify({
  106. 'error': 'Notification system failure',
  107. 'message': 'Access denied for security reasons'
  108. }), 500
  109. logger.info(f"Notifications sent successfully to: {successful_backends}")
  110. # Read key file
  111. file_success, content = read_file_safely(config.key_file_path)
  112. if not file_success:
  113. logger.error(f"CRITICAL: Failed to read key file: {content}")
  114. return jsonify({
  115. 'error': 'File access failure',
  116. 'message': 'Unable to retrieve key part'
  117. }), 500
  118. logger.warning("EMERGENCY: Key part successfully retrieved and sent")
  119. return jsonify({
  120. 'success': True,
  121. 'key_part': content,
  122. 'timestamp': time.time(),
  123. 'notified_backends': successful_backends
  124. })
  125. except Exception as e:
  126. logger.error(f"CRITICAL: Unexpected error in key access: {str(e)}")
  127. return jsonify({
  128. 'error': 'System error',
  129. 'message': 'Internal server error'
  130. }), 500
  131. def health_check():
  132. """Health check endpoint with dummy file access"""
  133. logger.info("Health check requested")
  134. try:
  135. # Send notification
  136. notification_success, successful_backends = send_ntfy_notification(
  137. config.ntfy_backends_health,
  138. config.ntfy_health_message,
  139. "Health Check"
  140. )
  141. if not notification_success:
  142. logger.error("Health check notification failed")
  143. return jsonify({
  144. 'status': 'error',
  145. 'message': 'Notification system failure'
  146. }), 500
  147. # Read dummy file
  148. file_success, content = read_file_safely(config.dummy_file_path)
  149. if not file_success:
  150. logger.error(f"Health check file read failed: {content}")
  151. return jsonify({
  152. 'status': 'error',
  153. 'message': 'File system failure'
  154. }), 500
  155. logger.info("Health check completed successfully")
  156. return jsonify({
  157. 'status': 'ok',
  158. 'timestamp': time.time(),
  159. 'notified_backends': successful_backends,
  160. 'dummy_content_length': len(content)
  161. })
  162. except Exception as e:
  163. logger.error(f"Health check error: {str(e)}")
  164. return jsonify({
  165. 'status': 'error',
  166. 'message': 'System error'
  167. }), 500
  168. @app.errorhandler(404)
  169. def not_found(error):
  170. """Handle 404 errors silently for security"""
  171. logger.warning(f"404 attempt: {error}")
  172. return jsonify({'error': 'Not found'}), 404
  173. @app.errorhandler(500)
  174. def internal_error(error):
  175. """Handle internal server errors"""
  176. logger.error(f"Internal server error: {error}")
  177. return jsonify({'error': 'Internal server error'}), 500
  178. def validate_setup():
  179. """Validate system setup before starting"""
  180. logger.info("Validating system setup...")
  181. # Check config files exist
  182. if not os.path.exists(config.key_file_path):
  183. logger.error(f"Key file not found: {config.key_file_path}")
  184. return False
  185. if not os.path.exists(config.dummy_file_path):
  186. logger.error(f"Dummy file not found: {config.dummy_file_path}")
  187. return False
  188. # Test file permissions
  189. try:
  190. with open(config.key_file_path, 'r') as f:
  191. f.read(1)
  192. with open(config.dummy_file_path, 'r') as f:
  193. f.read(1)
  194. except Exception as e:
  195. logger.error(f"File permission test failed: {str(e)}")
  196. return False
  197. # Test notification system
  198. logger.info("Testing notification system...")
  199. try:
  200. key_success, _ = send_ntfy_notification(
  201. config.ntfy_backends_key[:1], # Test only first backend
  202. "System startup test - key notifications",
  203. "Emergency Access Startup Test"
  204. )
  205. health_success, _ = send_ntfy_notification(
  206. config.ntfy_backends_health[:1], # Test only first backend
  207. "System startup test - health notifications",
  208. "Emergency Access Startup Test"
  209. )
  210. if not key_success:
  211. logger.error("Key notification system test failed")
  212. return False
  213. if not health_success:
  214. logger.error("Health notification system test failed")
  215. return False
  216. except Exception as e:
  217. logger.warning(f"Notification test failed, but continuing: {str(e)}")
  218. logger.info("System validation completed successfully")
  219. return True
  220. if __name__ == '__main__':
  221. try:
  222. # Load configuration
  223. config = Config()
  224. logger.info("Configuration loaded successfully")
  225. # Add ntfy log handler after config is loaded
  226. if config.send_all_logs:
  227. ntfy_handler = NtfyLogHandler(config)
  228. min_level = getattr(logging, config.log_level.upper(), logging.WARNING)
  229. ntfy_handler.setLevel(min_level)
  230. # Add to root logger to catch all application logs
  231. logging.getLogger().addHandler(ntfy_handler)
  232. # Validate system setup
  233. if not validate_setup():
  234. logger.error("System validation failed, exiting")
  235. sys.exit(1)
  236. # Add Flask routes with config values
  237. app.add_url_rule(config.key_route, 'get_key_part', get_key_part, methods=['GET'])
  238. app.add_url_rule(config.health_route, 'health_check', health_check, methods=['GET'])
  239. logger.info(f"Starting emergency access server on {config.server_host}:{config.server_port}")
  240. logger.info(f"Key route: {config.key_route}")
  241. logger.info(f"Health route: {config.health_route}")
  242. # Run the server on local port for Caddy reverse proxy
  243. app.run(
  244. host=config.server_host,
  245. port=config.server_port,
  246. debug=False,
  247. threaded=True
  248. )
  249. except Exception as e:
  250. logger.error(f"Failed to start server: {str(e)}")
  251. sys.exit(1)