fix(telegram): redact bot api logs
All checks were successful
CD Pipeline / deploy (push) Successful in 1m4s
All checks were successful
CD Pipeline / deploy (push) Successful in 1m4s
This commit is contained in:
@@ -18,6 +18,7 @@ import os
|
||||
import sys
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, time
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -35,6 +36,37 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger('TelegramBot')
|
||||
|
||||
_TELEGRAM_BOT_URL_RE = re.compile(r"(api\.telegram\.org/bot)[^/\s\"]+")
|
||||
_TELEGRAM_TOKEN_RE = re.compile(r"\b\d{8,12}:[A-Za-z0-9_-]{32,64}\b")
|
||||
|
||||
|
||||
def _redact_sensitive_log_value(value):
|
||||
if not isinstance(value, str):
|
||||
return value
|
||||
value = _TELEGRAM_BOT_URL_RE.sub(r"\1<redacted>", value)
|
||||
return _TELEGRAM_TOKEN_RE.sub("<telegram-token>", value)
|
||||
|
||||
|
||||
class SensitiveTokenFilter(logging.Filter):
|
||||
def filter(self, record):
|
||||
record.msg = _redact_sensitive_log_value(record.msg)
|
||||
if isinstance(record.args, tuple):
|
||||
record.args = tuple(_redact_sensitive_log_value(arg) for arg in record.args)
|
||||
elif isinstance(record.args, dict):
|
||||
record.args = {
|
||||
key: _redact_sensitive_log_value(value)
|
||||
for key, value in record.args.items()
|
||||
}
|
||||
return True
|
||||
|
||||
|
||||
for handler in logging.getLogger().handlers:
|
||||
handler.addFilter(SensitiveTokenFilter())
|
||||
|
||||
# python-telegram-bot uses httpx internally; INFO logs include Telegram Bot API URLs.
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
|
||||
def check_dependencies():
|
||||
"""檢查必要的套件"""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user