main.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import logging
  5. import time
  6. import tempfile
  7. import threading
  8. import subprocess
  9. from flask import Flask, jsonify, request
  10. from werkzeug.security import check_password_hash
  11. from werkzeug.serving import WSGIRequestHandler
  12. from functools import wraps
  13. from config import Config
  14. from typing import List, Tuple
  15. import base64
  16. import signal
  17. # Configure logging with custom handler
  18. class NtfyLogHandler(logging.Handler):
  19. """Custom logging handler that sends logs to ntfy health backends"""
  20. def __init__(self, config_obj):
  21. super().__init__()
  22. self.config = config_obj
  23. def emit(self, record):
  24. """Send log record to health backends"""
  25. if hasattr(self.config, 'ntfy_backends_health') and self.config.send_all_logs:
  26. try:
  27. log_message = self.format(record)
  28. # Get configured log level or default to WARNING
  29. min_level = getattr(logging, self.config.log_level.upper(), logging.WARNING)
  30. if record.levelno >= min_level:
  31. # Format message with appropriate emoji based on log level
  32. emoji = "🚨" if record.levelno >= logging.ERROR else "⚠️" if record.levelno >= logging.WARNING else "ℹ️"
  33. title = f"Emergency Access {record.levelname}"
  34. message = f"{emoji} {record.name}: {record.getMessage()}"
  35. send_ntfy_notification(
  36. self.config.ntfy_backends_health,
  37. message,
  38. title
  39. )
  40. except Exception:
  41. # Don't fail the application if logging notification fails
  42. pass
  43. # Configure logging with secure-file fallback
  44. log_path = '/var/log/emergency-access.log'
  45. try:
  46. os.makedirs(os.path.dirname(log_path), exist_ok=True)
  47. # Ensure the log file exists with restrictive permissions
  48. if not os.path.exists(log_path):
  49. open(log_path, 'a').close()
  50. try:
  51. os.chmod(log_path, 0o600)
  52. except Exception:
  53. # Best-effort; if this fails we continue with stream logging
  54. pass
  55. log_handlers = [
  56. logging.FileHandler(log_path),
  57. logging.StreamHandler()
  58. ]
  59. except Exception:
  60. # If any issue creating the file (permissions, etc.), fall back to stream-only logging
  61. log_handlers = [logging.StreamHandler()]
  62. logging.basicConfig(
  63. level=logging.INFO,
  64. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  65. handlers=log_handlers
  66. )
  67. logger = logging.getLogger(__name__)
  68. app = Flask(__name__)
  69. # Global config instance - initialized during main execution
  70. config = None
  71. def require_auth(key_config=None, is_health=False):
  72. """Decorator for HTTP Basic Authentication with simple in-memory rate limiting.
  73. This implements a small, best-effort per-(IP,username) rate limiter and lockout
  74. to mitigate brute-force attempts. It is intentionally simple and in-memory:
  75. - MAX_ATTEMPTS: number of failed attempts within WINDOW before lockout
  76. - WINDOW: window (seconds) to count attempts
  77. - LOCKOUT: lockout duration (seconds) after exceeding MAX_ATTEMPTS
  78. Notes:
  79. - Because this is in-memory, it resets on process restart.
  80. - For multi-process deployments, offload rate limiting to the reverse proxy (Caddy)
  81. or a shared store (redis).
  82. - On repeated lockouts a notification is sent (best-effort) to configured health backends
  83. and, when applicable, to the key's backends.
  84. """
  85. # Initialize shared state on the require_auth function object (module-global alternative)
  86. if not hasattr(require_auth, "_state"):
  87. require_auth._state = {
  88. 'attempts': {}, # (ip, username) -> list[timestamps]
  89. 'blocked': {}, # (ip, username) -> blocked_until_timestamp
  90. 'lock': threading.Lock()
  91. }
  92. MAX_ATTEMPTS = 5
  93. WINDOW = 300 # seconds
  94. LOCKOUT = 900 # seconds
  95. def decorator(f):
  96. @wraps(f)
  97. def decorated_function(*args, **kwargs):
  98. if config is None:
  99. logger.error("Configuration not loaded")
  100. return jsonify({'error': 'Server configuration error'}), 500
  101. auth = request.authorization
  102. client_ip = request.remote_addr or 'unknown'
  103. # determine username for rate limit key; use placeholder if missing
  104. username_for_key = auth.username if auth and auth.username else "<no_auth>"
  105. key = (client_ip, username_for_key)
  106. now_ts = time.time()
  107. state = require_auth._state
  108. # Check block list
  109. with state['lock']:
  110. blocked_until = state['blocked'].get(key)
  111. if blocked_until and now_ts < blocked_until:
  112. retry_after = int(blocked_until - now_ts)
  113. logger.warning(f"Blocked auth attempt from {client_ip} for user '{username_for_key}' (locked until {blocked_until})")
  114. # Return 429 Too Many Requests
  115. return jsonify({'error': 'Too many authentication attempts, temporarily locked'}), 429, {
  116. 'Retry-After': str(retry_after)
  117. }
  118. if not auth:
  119. # For missing auth, still account for attempts keyed by ip and '<no_auth>'
  120. # Increment attempt count and possibly lock
  121. with state['lock']:
  122. attempts = state['attempts'].setdefault(key, [])
  123. # prune old timestamps
  124. attempts = [t for t in attempts if now_ts - t <= WINDOW]
  125. attempts.append(now_ts)
  126. state['attempts'][key] = attempts
  127. if len(attempts) > MAX_ATTEMPTS:
  128. # Lock out
  129. state['blocked'][key] = now_ts + LOCKOUT
  130. logger.error(f"Locking out {client_ip} for missing/invalid auth (no credentials) after repeated attempts")
  131. # Try to notify about brute force (best-effort)
  132. try:
  133. if config and hasattr(config, 'ntfy_backends_health'):
  134. send_ntfy_notification(
  135. config.ntfy_backends_health,
  136. f"🚨 Brute-force lockout: {client_ip} (no credentials) on server",
  137. "Emergency Access ALERT"
  138. )
  139. except Exception:
  140. pass
  141. return jsonify({'error': 'Too many authentication attempts, temporarily locked'}), 429, {
  142. 'Retry-After': str(LOCKOUT)
  143. }
  144. return jsonify({'error': 'Authentication required'}), 401, {
  145. 'WWW-Authenticate': 'Basic realm="Emergency Access"'
  146. }
  147. # Determine expected credentials
  148. if is_health:
  149. expected_username = config.health_username
  150. expected_password_hash = config.health_password_hash
  151. auth_type = "health check"
  152. else:
  153. if key_config is None:
  154. logger.error("Key configuration not provided for authentication")
  155. return jsonify({'error': 'Server configuration error'}), 500
  156. expected_username = key_config.username
  157. expected_password_hash = key_config.password_hash
  158. auth_type = f"key '{key_config.key_id}'"
  159. # Verify credentials
  160. credential_ok = (auth.username == expected_username and
  161. Config.verify_password(auth.password, expected_password_hash))
  162. if not credential_ok:
  163. # record failed attempt and check for lockout
  164. with state['lock']:
  165. attempts = state['attempts'].setdefault(key, [])
  166. attempts = [t for t in attempts if now_ts - t <= WINDOW]
  167. attempts.append(now_ts)
  168. state['attempts'][key] = attempts
  169. if len(attempts) > MAX_ATTEMPTS:
  170. state['blocked'][key] = now_ts + LOCKOUT
  171. logger.error(f"Locking out {client_ip} for user '{username_for_key}' after repeated failed attempts")
  172. # Notify about brute-force lockout (best-effort)
  173. try:
  174. notify_backends = []
  175. if config and hasattr(config, 'ntfy_backends_health'):
  176. notify_backends.extend(config.ntfy_backends_health)
  177. # Include key-specific backends when available
  178. if key_config and getattr(key_config, 'backends', None):
  179. notify_backends.extend(key_config.backends)
  180. if notify_backends:
  181. send_ntfy_notification(
  182. list(dict.fromkeys(notify_backends)), # deduplicate
  183. f"🚨 Brute-force lockout: {client_ip} user='{username_for_key}' on {auth_type}",
  184. "Emergency Access ALERT"
  185. )
  186. except Exception:
  187. pass
  188. return jsonify({'error': 'Too many authentication attempts, temporarily locked'}), 429, {
  189. 'Retry-After': str(LOCKOUT)
  190. }
  191. logger.warning(f"Authentication failed for {auth_type}: invalid credentials from {client_ip}")
  192. return jsonify({'error': 'Invalid credentials'}), 401, {
  193. 'WWW-Authenticate': 'Basic realm="Emergency Access"'
  194. }
  195. # On success, clear recorded failed attempts for this key
  196. with state['lock']:
  197. if key in state['attempts']:
  198. try:
  199. del state['attempts'][key]
  200. except KeyError:
  201. pass
  202. if key in state['blocked']:
  203. try:
  204. del state['blocked'][key]
  205. except KeyError:
  206. pass
  207. logger.info(f"Authentication successful for {auth_type}")
  208. return f(*args, **kwargs)
  209. return decorated_function
  210. return decorator
  211. def send_ntfy_notification(backends: List[str], message: str, title: str = None) -> Tuple[bool, List[str]]:
  212. """
  213. Send notification using dschep/ntfy with dedicated config file
  214. Returns: (success, successful_backends)
  215. """
  216. successful_backends = []
  217. max_retries = 3
  218. retry_delay = 1
  219. for backend in backends:
  220. success = False
  221. last_error = None
  222. for attempt in range(max_retries):
  223. try:
  224. # Import ntfy here to avoid import issues during startup
  225. try:
  226. import ntfy
  227. from ntfy.config import load_config
  228. except ImportError:
  229. raise Exception("ntfy package not available. Please install with: pip install ntfy")
  230. if config is None:
  231. raise Exception("Configuration not loaded")
  232. # Load the ntfy config file
  233. ntfy_config = load_config(config.ntfy_config_path)
  234. ntfy_config["backends"] = [backend]
  235. # Add timeout to prevent hanging using threading
  236. result = [None]
  237. exception = [None]
  238. def notify_with_timeout():
  239. try:
  240. # Send notification using the backend name from our config file
  241. if title:
  242. result[0] = ntfy.notify(message, title=title, config=ntfy_config)
  243. else:
  244. result[0] = ntfy.notify(message, config=ntfy_config, title="Note")
  245. except Exception as e:
  246. exception[0] = e
  247. thread = threading.Thread(target=notify_with_timeout)
  248. thread.daemon = True
  249. thread.start()
  250. thread.join(timeout=15) # 15 second timeout
  251. if thread.is_alive():
  252. raise Exception("Notification timeout")
  253. if exception[0]:
  254. raise exception[0]
  255. ret = result[0]
  256. if ret == 0:
  257. successful_backends.append(backend)
  258. logger.info(f"Notification sent successfully via {backend}")
  259. success = True
  260. break
  261. else:
  262. raise Exception(f"ntfy returned error code {ret}")
  263. except ImportError as e:
  264. logger.error(f"ntfy package not available for backend {backend}: {e}")
  265. last_error = e
  266. break # Don't retry import errors
  267. except Exception as e:
  268. last_error = e
  269. if attempt < max_retries - 1:
  270. logger.warning(f"Notification attempt {attempt + 1} failed for {backend}: {str(e)}, retrying...")
  271. time.sleep(retry_delay * (attempt + 1)) # Exponential backoff
  272. else:
  273. logger.error(f"All notification attempts failed for {backend}: {str(e)}")
  274. if not success and last_error:
  275. # Don't raise exception - just log failure and continue with other backends
  276. logger.error(f"Failed to send notification to {backend} after {max_retries} attempts: {str(last_error)}")
  277. success = len(successful_backends) > 0
  278. return success, successful_backends
  279. def read_file_safely(file_path: str) -> Tuple[bool, str]:
  280. """
  281. Safely read file content
  282. Returns: (success, content)
  283. """
  284. try:
  285. if not os.path.exists(file_path):
  286. logger.error(f"File not found: {file_path}")
  287. return False, f"File not found: {file_path}"
  288. with open(file_path, 'r') as f:
  289. content = f.read().strip()
  290. if not content:
  291. logger.error(f"File is empty: {file_path}")
  292. return False, f"File is empty: {file_path}"
  293. return True, content
  294. except PermissionError:
  295. logger.error(f"Permission denied reading file: {file_path}")
  296. return False, f"Permission denied: {file_path}"
  297. except Exception as e:
  298. logger.error(f"Failed to read file {file_path}: {str(e)}")
  299. return False, f"Failed to read file: {str(e)}"
  300. def create_key_handler(key_config):
  301. """Create a key access handler for a specific key configuration"""
  302. @require_auth(key_config=key_config)
  303. def get_key_part():
  304. """Emergency key access endpoint"""
  305. if key_config is None:
  306. logger.error("Key configuration is None in get_key_part")
  307. return jsonify({'error': 'Server configuration error'}), 500
  308. logger.warning(f"EMERGENCY: Key access attempt detected for key '{key_config.key_id}'")
  309. try:
  310. # Send notification first - fail-safe approach
  311. notification_success, successful_backends = send_ntfy_notification(
  312. key_config.backends,
  313. key_config.message,
  314. "EMERGENCY ACCESS ALERT"
  315. )
  316. if not notification_success:
  317. logger.error(f"CRITICAL: Failed to send notifications to any backend for key '{key_config.key_id}'")
  318. return jsonify({
  319. 'error': 'Notification system failure',
  320. 'message': 'Access denied for security reasons'
  321. }), 500
  322. logger.info(f"Notifications sent successfully to: {successful_backends} for key '{key_config.key_id}'")
  323. # Read key file
  324. file_success, content = read_file_safely(key_config.file_path)
  325. if not file_success:
  326. logger.error(f"CRITICAL: Failed to read key file for '{key_config.key_id}': {content}")
  327. return jsonify({
  328. 'error': 'File access failure',
  329. 'message': 'Unable to retrieve key part'
  330. }), 500
  331. logger.warning(f"EMERGENCY: Key part successfully retrieved and sent for key '{key_config.key_id}'")
  332. resp = jsonify({
  333. 'success': True,
  334. 'key_id': key_config.key_id,
  335. 'key_part': content,
  336. 'timestamp': time.time(),
  337. 'notified_backends': successful_backends
  338. })
  339. # Ensure responses with secret material are never cached by clients or intermediaries
  340. resp.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, private'
  341. resp.headers['Pragma'] = 'no-cache'
  342. resp.headers['Expires'] = '0'
  343. # Additional defensive headers
  344. resp.headers['X-Content-Type-Options'] = 'nosniff'
  345. resp.headers['Content-Security-Policy'] = "default-src 'none'; frame-ancestors 'none'; sandbox"
  346. return resp
  347. except Exception as e:
  348. logger.error(f"CRITICAL: Unexpected error in key access for '{key_config.key_id}': {str(e)}")
  349. return jsonify({
  350. 'error': 'System error',
  351. 'message': 'Internal server error'
  352. }), 500
  353. return get_key_part
  354. @require_auth(is_health=True)
  355. def health_check():
  356. """Health check endpoint that verifies both health monitoring and all key request functionality"""
  357. logger.info("Health check requested")
  358. if config is None:
  359. logger.error("Configuration not loaded during health check")
  360. return jsonify({'status': 'error', 'message': 'Configuration not loaded'}), 500
  361. try:
  362. # Test health notification system
  363. health_notification_success, health_backends = send_ntfy_notification(
  364. config.ntfy_backends_health,
  365. config.ntfy_health_message,
  366. "Health Check"
  367. )
  368. # Test dummy file access
  369. dummy_file_success, dummy_content = read_file_safely(config.dummy_file_path)
  370. # Test all key files access (without exposing content)
  371. key_files_status = {}
  372. all_key_files_ok = True
  373. for key_id, key_config in config.keys.items():
  374. key_file_success, key_content = read_file_safely(key_config.file_path)
  375. key_files_status[key_id] = key_file_success
  376. if not key_file_success:
  377. all_key_files_ok = False
  378. # Test all key notification backends
  379. key_backends_status = {}
  380. all_key_backends_ok = True
  381. for key_id, key_config in config.keys.items():
  382. try:
  383. # Test notification without actually sending
  384. backend_test_success = len(key_config.backends) > 0
  385. key_backends_status[key_id] = {
  386. 'backends': key_config.backends,
  387. 'success': backend_test_success
  388. }
  389. if not backend_test_success:
  390. all_key_backends_ok = False
  391. except Exception as e:
  392. key_backends_status[key_id] = {
  393. 'backends': key_config.backends,
  394. 'success': False,
  395. 'error': str(e)
  396. }
  397. all_key_backends_ok = False
  398. # Determine overall health status
  399. all_systems_ok = (health_notification_success and
  400. dummy_file_success and
  401. all_key_files_ok and
  402. all_key_backends_ok)
  403. if not all_systems_ok:
  404. error_details = []
  405. if not health_notification_success:
  406. error_details.append("health notifications failed")
  407. if not dummy_file_success:
  408. error_details.append(f"dummy file access failed: {dummy_content}")
  409. # Add key-specific errors
  410. for key_id, status in key_files_status.items():
  411. if not status:
  412. error_details.append(f"key file access failed for '{key_id}'")
  413. for key_id, status in key_backends_status.items():
  414. if not status['success']:
  415. error_msg = f"key backends failed for '{key_id}'"
  416. if 'error' in status:
  417. error_msg += f": {status['error']}"
  418. error_details.append(error_msg)
  419. logger.error(f"Health check failed: {', '.join(error_details)}")
  420. return jsonify({
  421. 'status': 'error',
  422. 'message': 'System components failed',
  423. 'details': error_details,
  424. 'health_notifications': health_notification_success,
  425. 'dummy_file_access': dummy_file_success,
  426. 'key_files_status': key_files_status,
  427. 'key_backends_status': key_backends_status
  428. }), 500
  429. logger.info("Health check completed successfully - all systems operational")
  430. return jsonify({
  431. 'status': 'ok',
  432. 'timestamp': time.time(),
  433. 'health_backends_notified': health_backends,
  434. 'dummy_content_length': len(dummy_content),
  435. 'keys_accessible': len(key_files_status),
  436. 'key_files_status': key_files_status,
  437. 'key_backends_status': key_backends_status,
  438. 'emergency_system_ready': True
  439. })
  440. except Exception as e:
  441. logger.error(f"Health check error: {str(e)}")
  442. return jsonify({
  443. 'status': 'error',
  444. 'message': 'System error',
  445. 'error': str(e)
  446. }), 500
  447. @app.errorhandler(404)
  448. def not_found(error):
  449. """Handle 404 errors silently for security"""
  450. logger.warning(f"404 attempt: {error}")
  451. return jsonify({'error': 'Not found'}), 404
  452. @app.errorhandler(500)
  453. def internal_error(error):
  454. """Handle internal server errors"""
  455. logger.error(f"Internal server error: {error}")
  456. return jsonify({'error': 'Internal server error'}), 500
  457. def validate_setup():
  458. """Validate system setup before starting"""
  459. logger.info("Validating system setup...")
  460. if config is None:
  461. logger.error("Configuration not loaded")
  462. return False
  463. # Check dummy file exists
  464. if not os.path.exists(config.dummy_file_path):
  465. logger.error(f"Dummy file not found: {config.dummy_file_path}")
  466. return False
  467. # Test dummy file permissions
  468. try:
  469. with open(config.dummy_file_path, 'r') as f:
  470. f.read(1)
  471. except Exception as e:
  472. logger.error(f"Dummy file permission test failed: {str(e)}")
  473. return False
  474. # Validate all key configurations
  475. for key_id, key_config in config.keys.items():
  476. logger.info(f"Validating key '{key_id}'...")
  477. # Check key file exists
  478. if not os.path.exists(key_config.file_path):
  479. logger.error(f"Key file not found for '{key_id}': {key_config.file_path}")
  480. return False
  481. # Test key file permissions
  482. try:
  483. with open(key_config.file_path, 'r') as f:
  484. f.read(1)
  485. except Exception as e:
  486. logger.error(f"Key file permission test failed for '{key_id}': {str(e)}")
  487. return False
  488. # Validate backends are configured
  489. if not key_config.backends:
  490. logger.error(f"No notification backends configured for key '{key_id}'")
  491. return False
  492. # Test notification system
  493. logger.info("Testing notification system...")
  494. try:
  495. # Test health notification system
  496. health_success, _ = send_ntfy_notification(
  497. config.ntfy_backends_health[:1], # Test only first backend
  498. "System startup test - health notifications",
  499. "Emergency Access Startup Test"
  500. )
  501. if not health_success:
  502. logger.error("Health notification system test failed")
  503. return False
  504. # Test each key's notification backends
  505. for key_id, key_config in config.keys.items():
  506. key_success, _ = send_ntfy_notification(
  507. key_config.backends[:1], # Test only first backend
  508. f"System startup test - key '{key_id}' notifications",
  509. "Emergency Access Startup Test"
  510. )
  511. if not key_success:
  512. logger.error(f"Key notification system test failed for '{key_id}'")
  513. return False
  514. except Exception as e:
  515. logger.warning(f"Notification test failed, but continuing: {str(e)}")
  516. logger.info("System validation completed successfully")
  517. return True
  518. class ProductionRequestHandler(WSGIRequestHandler):
  519. """Custom request handler with improved error handling"""
  520. def log_error(self, format, *args):
  521. """Override to use our logger"""
  522. logger.error(f"HTTP Error: {format % args}")
  523. def log_message(self, format, *args):
  524. """Override to use our logger"""
  525. logger.info(f"HTTP: {format % args}")
  526. def main():
  527. global config
  528. try:
  529. # Load configuration
  530. config = Config()
  531. logger.info("Configuration loaded successfully")
  532. # Add ntfy log handler after config is loaded
  533. if config.send_all_logs:
  534. ntfy_handler = NtfyLogHandler(config)
  535. min_level = getattr(logging, config.log_level.upper(), logging.WARNING)
  536. ntfy_handler.setLevel(min_level)
  537. # Add to root logger to catch all application logs
  538. logging.getLogger().addHandler(ntfy_handler)
  539. # Validate system setup
  540. if not validate_setup():
  541. logger.error("System validation failed, exiting")
  542. sys.exit(1)
  543. # Add Flask routes dynamically for each key
  544. for key_id, key_config in config.keys.items():
  545. handler = create_key_handler(key_config)
  546. endpoint_name = f'get_key_part_{key_id}'
  547. app.add_url_rule(key_config.route, endpoint_name, handler, methods=['GET'])
  548. logger.info(f"Registered authenticated key route for '{key_id}': {key_config.route}")
  549. # Add health check route
  550. app.add_url_rule(config.health_route, 'health_check', health_check, methods=['GET'])
  551. logger.info(f"Starting emergency access server on {config.server_host}:{config.server_port}")
  552. logger.info(f"Health route: {config.health_route}")
  553. logger.info(f"Configured {len(config.keys)} key(s)")
  554. # Use production-ready server with better error handling
  555. try:
  556. from waitress import serve
  557. logger.info("Using Waitress WSGI server for production")
  558. serve(
  559. app,
  560. host=config.server_host,
  561. port=config.server_port,
  562. threads=6,
  563. connection_limit=100,
  564. cleanup_interval=30,
  565. channel_timeout=120
  566. )
  567. except ImportError:
  568. logger.critical("Waitress WSGI server not installed. This application must run under a production WSGI server such as 'waitress' or 'gunicorn'. Aborting startup.")
  569. # Attempt to notify configured health backends about startup failure (best-effort)
  570. try:
  571. if config and hasattr(config, 'ntfy_backends_health'):
  572. send_ntfy_notification(
  573. config.ntfy_backends_health,
  574. "🚨 Emergency Access server failed to start: waitress not installed",
  575. "Emergency Access CRITICAL"
  576. )
  577. except Exception:
  578. # Do not raise further - we are already aborting startup
  579. pass
  580. sys.exit(1)
  581. except KeyboardInterrupt:
  582. logger.info("Received keyboard interrupt, shutting down gracefully")
  583. except Exception as e:
  584. logger.error(f"Failed to start server: {str(e)}")
  585. if config and hasattr(config, 'ntfy_backends_health'):
  586. try:
  587. send_ntfy_notification(
  588. config.ntfy_backends_health,
  589. f"🚨 Emergency Access server failed to start: {str(e)}",
  590. "Emergency Access CRITICAL"
  591. )
  592. except Exception:
  593. pass
  594. sys.exit(1)
  595. finally:
  596. logger.info("Emergency Access server shutdown complete")
  597. if __name__ == '__main__':
  598. main()