log_reader.py 9.6 KB

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