telegram_config_service.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. """Telegram configuration persistence service.
  2. Reads and writes Telegram notification settings to the ``telegram_config``
  3. database table (single-row pattern, same as backup_config and ldap_config).
  4. Sensitive fields (api_hash, bot_token) are encrypted at rest using Fernet
  5. symmetric encryption. The encryption key is stored alongside the row and
  6. is derived from a randomly-generated secret on first save.
  7. """
  8. from __future__ import annotations
  9. import base64
  10. import hashlib
  11. import os
  12. from datetime import datetime
  13. from cryptography.fernet import Fernet, InvalidToken
  14. from loguru import logger
  15. from database.database import get_session
  16. from database.models.models import TelegramConfig
  17. _SENSITIVE_FIELDS = ("api_hash", "bot_token")
  18. _SECRET_PLACEHOLDER = "".join(chr(8226) for _ in range(8))
  19. def _default_config() -> dict:
  20. return {
  21. "enabled": False,
  22. "api_id": "",
  23. "api_hash": "",
  24. "bot_token": "",
  25. "phone": "",
  26. "session_name": "squidstats_bot",
  27. "recipients": [],
  28. }
  29. def _get_fernet(raw_key: str | None) -> Fernet:
  30. if not raw_key:
  31. raise RuntimeError("No encryption key available")
  32. key_bytes = raw_key.encode() if isinstance(raw_key, str) else raw_key
  33. if len(key_bytes) != 44:
  34. key_bytes = base64.urlsafe_b64encode(hashlib.sha256(key_bytes).digest())
  35. return Fernet(key_bytes)
  36. def _generate_encryption_key() -> str:
  37. return base64.urlsafe_b64encode(os.urandom(32)).decode()
  38. def _encrypt(value: str, encryption_key: str) -> str:
  39. if not value:
  40. return ""
  41. cipher = _get_fernet(encryption_key)
  42. return cipher.encrypt(value.encode()).decode()
  43. def _decrypt(encrypted: str, encryption_key: str) -> str:
  44. if not encrypted:
  45. return ""
  46. try:
  47. cipher = _get_fernet(encryption_key)
  48. return cipher.decrypt(encrypted.encode()).decode()
  49. except InvalidToken:
  50. logger.warning(
  51. "telegram_config: could not decrypt field, returning empty string"
  52. )
  53. return ""
  54. def _recipients_to_list(raw: str) -> list[str]:
  55. """Convert comma-separated recipients string to a clean list."""
  56. if not raw:
  57. return []
  58. return [r.strip() for r in raw.split(",") if r.strip()]
  59. def _recipients_to_str(recipients: list[str] | str) -> str:
  60. """Normalise recipients to a comma-separated string for storage."""
  61. if isinstance(recipients, list):
  62. return ",".join(r.strip() for r in recipients if r.strip())
  63. return recipients or ""
  64. def load_config() -> dict:
  65. """Return Telegram config from the DB. Returns defaults if no row exists."""
  66. session = get_session()
  67. try:
  68. row = session.query(TelegramConfig).first()
  69. if row is None:
  70. return _default_config()
  71. api_hash = row.api_hash or ""
  72. bot_token = row.bot_token or ""
  73. if row.encryption_key:
  74. api_hash = _decrypt(api_hash, row.encryption_key)
  75. bot_token = _decrypt(bot_token, row.encryption_key)
  76. return {
  77. "enabled": bool(row.enabled),
  78. "api_id": row.api_id or "",
  79. "api_hash": api_hash,
  80. "bot_token": bot_token,
  81. "phone": row.phone or "",
  82. "session_name": row.session_name or "squidstats_bot",
  83. "recipients": _recipients_to_list(row.recipients or ""),
  84. }
  85. except Exception as exc:
  86. logger.warning(f"Could not read telegram_config from DB, using defaults: {exc}")
  87. return _default_config()
  88. finally:
  89. session.close()
  90. def save_config(data: dict) -> None:
  91. """Persist Telegram configuration to the DB."""
  92. session = get_session()
  93. try:
  94. row = session.query(TelegramConfig).first()
  95. if row is None:
  96. row = TelegramConfig(created_at=datetime.now())
  97. session.add(row)
  98. # Ensure an encryption key exists
  99. if not row.encryption_key:
  100. row.encryption_key = _generate_encryption_key()
  101. row.enabled = 1 if data.get("enabled") else 0
  102. row.api_id = str(data.get("api_id") or "").strip()
  103. row.phone = str(data.get("phone") or "").strip()
  104. row.session_name = (
  105. str(data.get("session_name") or "squidstats_bot").strip()
  106. or "squidstats_bot"
  107. )
  108. row.recipients = _recipients_to_str(data.get("recipients", []))
  109. row.updated_at = datetime.now()
  110. # Encrypt sensitive fields only when a non-empty value is provided.
  111. # An empty string means "leave unchanged" (placeholder masking in the UI).
  112. new_api_hash = str(data.get("api_hash") or "").strip()
  113. if new_api_hash and new_api_hash != _SECRET_PLACEHOLDER:
  114. row.api_hash = _encrypt(new_api_hash, row.encryption_key)
  115. new_bot_token = str(data.get("bot_token") or "").strip()
  116. if new_bot_token and new_bot_token != _SECRET_PLACEHOLDER:
  117. row.bot_token = _encrypt(new_bot_token, row.encryption_key)
  118. session.commit()
  119. logger.info("Telegram configuration saved to DB")
  120. except Exception as exc:
  121. session.rollback()
  122. logger.error(f"Error saving telegram_config: {exc}")
  123. raise
  124. finally:
  125. session.close()