Coverage for src/lexigram/admin/services/export/sanitize.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-08-21 14:56 +0800

1from __future__ import annotations 

2 

3from typing import Any 

4 

5RISKY_LEADING_CHARS = ("=", "+", "-", "@", "\t", "\r") 

6 

7 

8def sanitize_cell_value(value: Any) -> Any: 

9 """Neutralize formula/DDE injection in a single cell value. 

10 

11 Spreadsheet applications evaluate cells whose leading character is 

12 ``=``, ``+``, ``-``, ``@``, or a tab/CR as a live formula or DDE 

13 trigger when an operator opens the exported file (OWASP CSV-injection 

14 class). Prefix such values with a single quote so they render as text; 

15 the prefix is lossless — stripping instead would silently corrupt 

16 legitimate ``-``/``+``-leading data. 

17 

18 Args: 

19 value: Raw cell value from the export data source. 

20 

21 Returns: 

22 The sanitized value: non-strings and non-risky strings pass 

23 through unchanged; risky strings gain a leading ``'``. 

24 """ 

25 if not isinstance(value, str) or not value: 

26 return value 

27 if value[0] in RISKY_LEADING_CHARS: 

28 return f"'{value}" 

29 return value