From 4cf319aefd68a795f291c09c3cab4d41c1916570 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 11 Aug 2026 11:41:36 +0200 Subject: [PATCH] stree.(add|clear)_hide_log_patterns(): Add functions Add two functions, add_hide_log_patterns() and clear_hide_log_patterns(). Their intended purpose is to keep secrets from leaking into logging. add_hide_log_patterns() takes compiled regular expressions, strings or arrays thereof that are added to the global pattern list. It defaults to ["secret", "password", "token"], case-insensitive. clear_hide_log_patterns() clears the list, so the caller must start from scratch building one. This keeps sensitive keys visible for debugging while suppressing their child values from log output. In addition to these two functions, debug logging was removed in some places where the effort of keeping would have outweighed the gain. Signed-off-by: Jan Lindemann --- src/python/jw/util/stree/StringTree.py | 99 ++++++++++++++++++-------- 1 file changed, 71 insertions(+), 28 deletions(-) diff --git a/src/python/jw/util/stree/StringTree.py b/src/python/jw/util/stree/StringTree.py index f4f662a..ff21353 100644 --- a/src/python/jw/util/stree/StringTree.py +++ b/src/python/jw/util/stree/StringTree.py @@ -13,10 +13,14 @@ from typing import overload from typing import cast if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Iterable from typing import Iterator -from ..log import DEBUG, INFO, get_caller_pos, slog +from ..log import DEBUG, INFO, get_caller_pos, prio_gets_logged, slog + +_RX_HIDE_LOG_PATTERNS: list[re.Pattern[str]] = [ + re.compile(rx, re.IGNORECASE) for rx in ['password', 'secret', 'token'] +] def is_quoted(s: str) -> bool: s = s.strip() @@ -53,6 +57,51 @@ def cleanup_string(s: str | StringTree) -> str | StringTree: return s[1:-1].replace('\\' + s[0], s[0]) return s +def _match_hide_filter(string: str | None) -> bool: + if string is None: + return False + for rx in _RX_HIDE_LOG_PATTERNS: + if re.match(rx, string): + return True + components = string.split('.') + if len(components) > 1: + return _match_hide_filter(components[-1]) + return False + +def _hide_children(parent: StringTree | str | None) -> bool: + if parent is None: + return False + if isinstance(parent, StringTree): + parent = parent.content + return _match_hide_filter(parent) + +def _purge_hidden_log_patterns( + parent: str | StringTree | None, + content: str | StringTree | None, +) -> str | None: + if parent is None: + return None + if _hide_children(parent): + return '' + if isinstance(content, StringTree): + return content.content + return content + +def add_hide_log_patterns( # export + rx: str | Iterable[str] | re.Pattern[str] | Iterable[re.Pattern[str]] + ) -> None: + if isinstance(rx, str): + _RX_HIDE_LOG_PATTERNS.append(re.compile(rx)) + return + if isinstance(rx, re.Pattern): + _RX_HIDE_LOG_PATTERNS.append(rx) + return + for rx_item in rx: + add_hide_log_patterns(rx_item) + +def clear_hide_log_patterns() -> None: # export + _RX_HIDE_LOG_PATTERNS.clear() + class StringTree(MutableMapping[str, Any]): # export class Error(Exception): @@ -87,11 +136,6 @@ class StringTree(MutableMapping[str, Any]): # export content: str | StringTree | None, split: bool = True ) -> StringTree: - slog( - DEBUG, - ('At "{}": '.format(str(self.content)) if hasattr(self, "content") else "") - + f'Setting "{path}" -> "{content}"' - ) # Not sure what the idea behind this was. It often goes off, and all # works fine without. @@ -108,32 +152,21 @@ class StringTree(MutableMapping[str, Any]): # export self.content = cleanup_string(content) elif isinstance(content, StringTree): self.__adopt_children(content) - slog( - DEBUG, - " -- content = >" + str(content) + "<, self.content = >" + - str(self.content) + "<" - ) return self _path: str = cleanup_string(path) if not _path: - #assert self.content is None or ( - # isinstance(content, StringTree) and content.content == self.content - #) - if isinstance(content, StringTree): - #assert isinstance(content, StringTree), ( - # f'Type: {type(content).__name__ }' - #) self.__adopt_children(content) else: if self.content != content: - #self.content = cleanup_string(content) - slog(DEBUG, f'Changing content: "{self.content}" ->"{content}"') - assert (content != '"[a-zA-Z0-9+_*/-]"') + if prio_gets_logged(DEBUG): + change = ( + '"" -> ""' if _hide_children(self) else + '"{self.content}" ->"{content}"' + ) + slog(DEBUG, f'Changing content: {change}') self.content = content - #assert(content != "'antlr_doesnt_understand_vertical_tab'") - #self.children[content] = StringTree(None, content) return self components: list[str] = _path.split('.') if split else [_path] @@ -164,7 +197,8 @@ class StringTree(MutableMapping[str, Any]): # export def __dump(self, prio: int, indent: int = 0, **kwargs: Any) -> None: caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1) - slog(prio, '|' + (' ' * indent) + str(self.content), caller = caller) + prefix = '|' + (' ' * indent) + slog(prio, prefix + str(self.log_content), caller = caller) indent += 2 for name, child in self.children.items(): child.__dump(prio, indent = indent, caller = caller) @@ -283,7 +317,6 @@ class StringTree(MutableMapping[str, Any]): # export def __init__( self, path: str, content: str, parent: StringTree | None = None ) -> None: - slog(DEBUG, f'Constructing StringTree(path="{path}", content="{content}")') self.__parent: StringTree | None = parent self.children: OrderedDict[str, StringTree] = OrderedDict() self.content: str | None = None @@ -299,6 +332,12 @@ class StringTree(MutableMapping[str, Any]): # export # regex ( content = regex, children = [ '[ \n\t\r]+' ] ) # '[ \n\t\r]+)' ( content = '\n\t\r]+)', children = [] ) + @property + def log_content(self) -> str | None: + if _hide_children(self.__parent): + return '' + return self.content + @property def path(self) -> str: if self.__parent is None: @@ -332,7 +371,9 @@ class StringTree(MutableMapping[str, Any]): # export content: str | StringTree | None = None, split: bool = True ) -> StringTree: - slog(DEBUG, f'-- At "{self.content}": Adding "{path}" -> "{content}"') + if prio_gets_logged(DEBUG): + content_str = _purge_hidden_log_patterns(path, content) + slog(DEBUG, f'-- At "{self.content}": Adding "{path}" -> "{content_str}"') return self.__set(path, content, split) @override @@ -372,7 +413,9 @@ class StringTree(MutableMapping[str, Any]): # export return child.value() if len(self.children) == 0: raise self.Error('tried to get value from leaf "{}"'.format(self.content)) - slog(DEBUG, f'Returning value from children {self.children}') + if prio_gets_logged(DEBUG): + child_str = str(self.children) if not _hide_children(self) else '' + slog(DEBUG, f'Returning value from children {child_str}') return self.children[next(reversed(self.children))].content def child_list(self, depth_first: bool = True) -> list[StringTree]: