log_reader.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """Shared primitives for reading, parsing, and sanitizing the Bambuddy app log.
  2. Extracted from ``routes/support.py`` so service-layer code (e.g. the log-health
  3. scanner in ``log_health.py``) can reuse log reading and redaction without
  4. importing from the API layer. ``support.py`` re-imports these helpers and keeps
  5. its own route handlers.
  6. """
  7. import logging
  8. import re
  9. from pydantic import BaseModel
  10. from sqlalchemy import select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.config import settings
  13. from backend.app.core.logging_filters import URL_CREDENTIALS_PATTERN
  14. from backend.app.models.printer import Printer
  15. from backend.app.models.settings import Settings
  16. from backend.app.models.user import User
  17. logger = logging.getLogger(__name__)
  18. # Log line format: "2024-01-15 10:30:45,123 INFO [module.name] [trace_id] Message"
  19. # The trace_id is left as part of the message group — callers that need it can
  20. # parse it out; the log-health scanner does not.
  21. LOG_LINE_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d{3})\s+(\w+)\s+\[([^\]]+)\]\s+(.*)$")
  22. # LDAP Distinguished Names carry PII — the leaf ``CN=`` is the user's real name
  23. # (#2681). Match a run of at least two ``attr=value`` RDN components joined by
  24. # commas, where ``attr`` is a known LDAP attribute type. Requiring two components
  25. # keeps this from clobbering an incidental ``key=value`` in an unrelated log line,
  26. # while still catching DNs wherever they surface — the deliberate "auth successful"
  27. # line, ldap3 exception strings, and group DNs alike. Bias is intentionally toward
  28. # redaction: over-redacting a rare debug line to ``[DN]`` is a safe failure; leaking
  29. # a name is not.
  30. # The value char class excludes `<>;+` — RFC 4514 requires those escaped inside a
  31. # DN value, so an unescaped one marks the end of the DN, not part of it. That stops
  32. # the final (comma-unbounded) component from greedily swallowing trailing log text
  33. # such as ``… -> GroupName``.
  34. _LDAP_RDN = r"(?:CN|OU|DC|UID|O|L|ST|C|SN|GN|DN|E|MAIL|STREET|GIVENNAME|SURNAME)=[^,\n<>;+]+"
  35. _LDAP_DN_PATTERN = re.compile(rf"(?i)\b{_LDAP_RDN}(?:\s*,\s*{_LDAP_RDN})+")
  36. class LogEntry(BaseModel):
  37. """A single parsed log entry."""
  38. timestamp: str
  39. level: str
  40. logger_name: str
  41. message: str
  42. def parse_log_line(line: str) -> LogEntry | None:
  43. """Parse a single log line into a LogEntry, or None if it is not a line start."""
  44. match = LOG_LINE_PATTERN.match(line.strip())
  45. if match:
  46. return LogEntry(
  47. timestamp=match.group(1),
  48. level=match.group(2),
  49. logger_name=match.group(3),
  50. message=match.group(4),
  51. )
  52. return None
  53. def read_log_entries(
  54. limit: int = 200,
  55. level_filter: str | None = None,
  56. search: str | None = None,
  57. ) -> tuple[list[LogEntry], int]:
  58. """Read and parse log entries from ``bambuddy.log``, newest first.
  59. Continuation lines (tracebacks etc.) are folded into the message of the
  60. entry they belong to. Returns ``(entries, total_lines_in_file)``.
  61. """
  62. log_file = settings.log_dir / "bambuddy.log"
  63. if not log_file.exists():
  64. return [], 0
  65. entries: list[LogEntry] = []
  66. total_lines = 0
  67. try:
  68. with open(log_file, encoding="utf-8", errors="replace") as f:
  69. lines = f.readlines()
  70. total_lines = len(lines)
  71. # Parse lines in reverse order (newest first)
  72. current_entry: LogEntry | None = None
  73. multi_line_buffer: list[str] = []
  74. for line in reversed(lines):
  75. parsed = parse_log_line(line)
  76. if parsed:
  77. # Found a new log entry start
  78. if current_entry:
  79. # Apply filters and add previous entry (without multi_line_buffer - it belongs to new entry)
  80. should_include = True
  81. # Level filter
  82. if level_filter and current_entry.level.upper() != level_filter.upper():
  83. should_include = False
  84. # Search filter (case-insensitive)
  85. if search and should_include:
  86. search_lower = search.lower()
  87. if not (
  88. search_lower in current_entry.message.lower()
  89. or search_lower in current_entry.logger_name.lower()
  90. ):
  91. should_include = False
  92. if should_include:
  93. entries.append(current_entry)
  94. if len(entries) >= limit:
  95. break
  96. # Set new entry and attach any accumulated multi-line content to it
  97. # (in reverse order, continuation lines come before their parent entry)
  98. current_entry = parsed
  99. if multi_line_buffer:
  100. current_entry.message += "\n" + "\n".join(reversed(multi_line_buffer))
  101. multi_line_buffer = []
  102. elif line.strip():
  103. # Continuation of multi-line log entry (will be attached to next parsed entry)
  104. multi_line_buffer.append(line.rstrip())
  105. # Don't forget the last (oldest) entry
  106. # Note: any remaining multi_line_buffer would be orphaned lines before the first entry
  107. if current_entry and len(entries) < limit:
  108. should_include = True
  109. if level_filter and current_entry.level.upper() != level_filter.upper():
  110. should_include = False
  111. if search and should_include:
  112. search_lower = search.lower()
  113. if not (
  114. search_lower in current_entry.message.lower()
  115. or search_lower in current_entry.logger_name.lower()
  116. ):
  117. should_include = False
  118. if should_include:
  119. entries.append(current_entry)
  120. except Exception as e:
  121. logger.error("Error reading log file: %s", e)
  122. return [], 0
  123. # Entries are already in newest-first order
  124. return entries, total_lines
  125. def sanitize_log_content(content: str, sensitive_strings: dict[str, str] | None = None) -> str:
  126. """Remove sensitive data from log content.
  127. ``sensitive_strings`` maps known exact values (printer names, serials, etc.)
  128. to replacement labels; pass the result of :func:`collect_sensitive_strings`.
  129. Regex passes additionally redact credentials in URLs, emails, serials, and
  130. IP addresses that were not captured by exact matching.
  131. """
  132. # First, replace known sensitive values (database-aware exact matching)
  133. # This catches printer names, usernames, and other arbitrary user-chosen strings
  134. # that regex patterns cannot detect
  135. if sensitive_strings:
  136. # Sort by length descending to avoid partial matches (e.g. "My Printer 1" before "My Printer")
  137. for value, label in sorted(sensitive_strings.items(), key=lambda x: len(x[0]), reverse=True):
  138. if len(value) < 3:
  139. continue # Skip very short strings to prevent over-redaction
  140. content = re.sub(re.escape(value), label, content)
  141. # Replace credentials in URLs (e.g. http://user:pass@host, rtsps://bblp:code@host).
  142. # Shares its pattern with the log-pipeline redaction in ``core.logging_filters`` so
  143. # the two can't drift; the bundle drops the username too, where the live log keeps
  144. # it for diagnosis.
  145. content = URL_CREDENTIALS_PATTERN.sub(r"\g<scheme>[CREDENTIALS]@", content)
  146. # Replace email addresses
  147. content = re.sub(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]", content)
  148. # Replace LDAP Distinguished Names (#2681) — PII on par with email.
  149. content = _LDAP_DN_PATTERN.sub("[DN]", content)
  150. # Replace Bambu Lab printer serial numbers (format: 00M/01D/01S/01P/03W + alphanumeric, 12-16 chars total)
  151. content = re.sub(r"\b0[0-3][A-Z0-9][A-Z0-9]{9,13}\b", "[SERIAL]", content, flags=re.IGNORECASE)
  152. # Replace IPv4 addresses (skip firmware versions like 01.09.01.00 which have leading zeros)
  153. content = re.sub(
  154. r"\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\b",
  155. "[IP]",
  156. content,
  157. )
  158. # Replace paths with usernames
  159. content = re.sub(r"/home/[^/\s]+/", "/home/[user]/", content)
  160. content = re.sub(r"/Users/[^/\s]+/", "/Users/[user]/", content)
  161. content = re.sub(r"/opt/[^/\s]+/", "/opt/[user]/", content)
  162. return content
  163. async def collect_sensitive_strings(db: AsyncSession) -> dict[str, str]:
  164. """Collect known sensitive values from the database for log redaction.
  165. Covers printer names, serial numbers, IP addresses, access codes, auth
  166. usernames, and the Bambu Cloud email. Pass the result to
  167. :func:`sanitize_log_content`.
  168. """
  169. sensitive_strings: dict[str, str] = {}
  170. # Printer names, serial numbers, IP addresses, and access codes
  171. result = await db.execute(select(Printer.name, Printer.serial_number, Printer.ip_address, Printer.access_code))
  172. for name, serial, ip_address, access_code in result.all():
  173. if name:
  174. sensitive_strings[name] = "[PRINTER]"
  175. if serial:
  176. sensitive_strings[serial] = "[SERIAL]"
  177. if ip_address:
  178. sensitive_strings[ip_address] = "[IP]"
  179. if access_code:
  180. sensitive_strings[access_code] = "[ACCESS_CODE]"
  181. # Auth usernames
  182. result = await db.execute(select(User.username))
  183. for (username,) in result.all():
  184. if username:
  185. sensitive_strings[username] = "[USER]"
  186. # Bambu Cloud email
  187. result = await db.execute(select(Settings.value).where(Settings.key == "bambu_cloud_email"))
  188. cloud_email = result.scalar_one_or_none()
  189. if cloud_email:
  190. sensitive_strings[cloud_email] = "[EMAIL]"
  191. return sensitive_strings