Coverage for chalicelib/utils/log.py: 88%

13 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 12:56 +0000

1import re 

2 

3_NEWLINE_RE = re.compile(r"[\r\n]+") 

4_CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") 

5_DEFAULT_MAX_LEN = 512 

6 

7 

8def sanitize(value, max_length: int = _DEFAULT_MAX_LEN) -> str: 

9 """Sanitize a value before interpolating it into a log message. 

10 

11 Strips CR/LF (prevents log forging), null bytes and ANSI/control 

12 characters, then truncates. Use for any externally-sourced data: 

13 request bodies, headers, URLs, JWT contents, third-party responses. 

14 """ 

15 if value is None: 15 ↛ 16line 15 didn't jump to line 16 because the condition on line 15 was never true

16 return "" 

17 s = value if isinstance(value, str) else repr(value) 

18 s = _NEWLINE_RE.sub(" ", s) 

19 s = _CONTROL_CHARS_RE.sub("", s) 

20 if len(s) > max_length: 

21 s = s[:max_length] + "...(truncated)" 

22 return s