cellsafe 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cellsafe/_kinds.py ADDED
@@ -0,0 +1,253 @@
1
+ """Catalogue of the risk kinds cellsafe knows about.
2
+
3
+ The texts here are what ``cellsafe explain KIND`` prints. They describe
4
+ documented or widely reported spreadsheet behaviour. None of it was verified
5
+ against a running copy of Excel, LibreOffice or Google Sheets while this
6
+ package was written; see the README section "What was and was not tested".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Kind:
16
+ """Description of one risk kind."""
17
+
18
+ name: str
19
+ scope: str # "cell" or "file"
20
+ summary: str
21
+ explanation: str
22
+
23
+
24
+ def _k(name: str, scope: str, summary: str, explanation: str) -> Kind:
25
+ return Kind(name, scope, summary, " ".join(explanation.split()))
26
+
27
+
28
+ _ALL = [
29
+ _k(
30
+ "formula",
31
+ "cell",
32
+ "Cell would be evaluated as a formula (CSV/formula injection).",
33
+ """A cell that starts with '=', '+', '-' or '@' is treated as a formula
34
+ by spreadsheet programs. OWASP also lists a leading tab and carriage
35
+ return. cellsafe additionally looks past leading whitespace and quote
36
+ characters and recognises the full-width forms of the four trigger
37
+ characters. The fix is to make the cell text: the 'quote' strategy
38
+ puts an apostrophe in front (the OWASP recommendation; the apostrophe
39
+ is visible in the opened sheet), the 'tab' strategy puts a tab in
40
+ front (invisible, but OWASP lists a leading tab as a trigger itself,
41
+ so it is the weaker choice). With numbers='keep' (the default) a cell
42
+ that is nothing but a signed number, such as -5 or -3.2e4, is left
43
+ alone because it contains no letters, references or operators and so
44
+ cannot call anything; numbers='escape' follows OWASP to the letter and
45
+ turns those into text as well.""",
46
+ ),
47
+ _k(
48
+ "precision-loss",
49
+ "cell",
50
+ "Number has more than 15 significant digits; the rest become zeros.",
51
+ """Spreadsheets store numbers as IEEE 754 doubles and Excel keeps 15
52
+ significant digits. A 16-digit card number, a long account number or
53
+ a barcode opened as a number has its trailing digits replaced by
54
+ zeros, and the original cannot be recovered from the sheet. Such
55
+ values are identifiers, not quantities, and need to arrive as text.""",
56
+ ),
57
+ _k(
58
+ "scientific-display",
59
+ "cell",
60
+ "Integer with 12 to 15 digits is shown in scientific notation.",
61
+ """Excel's General format shows integers of 12 or more digits as, for
62
+ example, 1.23457E+11. Up to 15 digits the stored value is still
63
+ exact, but the cell looks wrong, and if the sheet is saved as CSV
64
+ again the displayed form is what gets written, which does lose the
65
+ digits.""",
66
+ ),
67
+ _k(
68
+ "leading-zero",
69
+ "cell",
70
+ "Leading zeros are dropped when the cell is read as a number.",
71
+ """Values such as 00123, 007 or 0790000000 (postal codes, phone
72
+ numbers, IDs) are parsed as numbers and shown without their leading
73
+ zeros.""",
74
+ ),
75
+ _k(
76
+ "plus-sign",
77
+ "cell",
78
+ "Explicit plus sign is dropped when the cell is read as a number.",
79
+ """A value such as +96279000000 (an international phone number written
80
+ without spaces) is a valid number, so the spreadsheet stores the
81
+ number and the plus sign is gone. This kind is reported when the cell
82
+ is a plain number with a leading '+'. With numbers='escape' the cell
83
+ is reported as 'formula' instead and neutralised as text.""",
84
+ ),
85
+ _k(
86
+ "date-like",
87
+ "cell",
88
+ "Text that is not a full date is converted to a date.",
89
+ """Excel converts short patterns such as 1-2, 3/4, MAR1, SEPT2 or
90
+ 1-Feb into dates (this is the cause of the well-known gene-name
91
+ errors in published spreadsheets). The original text is not kept.
92
+ cellsafe matches numeric pairs and triples separated by '-' or '/'
93
+ and English month names or abbreviations next to a number. The
94
+ patterns are an approximation of Excel's behaviour in an English
95
+ locale; other locales recognise other month names and separators.
96
+ A complete year-first date such as 2024-01-15 is not reported,
97
+ because converting it to a date is normally what is wanted.""",
98
+ ),
99
+ _k(
100
+ "locale-date",
101
+ "cell",
102
+ "Numeric date whose day/month order depends on the reader's locale.",
103
+ """A date written as 01/02/2024 is 1 February in day-first locales and
104
+ 2 January in month-first locales, and the spreadsheet decides
105
+ silently. A date such as 15/01/2024 becomes a date in day-first
106
+ locales and stays text in month-first ones. Writing dates year-first
107
+ (2024-01-15) avoids the ambiguity. If you want these cells converted
108
+ anyway, add 'locale-date' to the policy's ignore set.""",
109
+ ),
110
+ _k(
111
+ "exponent",
112
+ "cell",
113
+ "Identifier such as 1E5 or 12E3 is read as a number in E notation.",
114
+ """Digits, the letter E, digits: a spreadsheet reads 1E5 as 100000 and
115
+ 12E3 as 12000. cellsafe reports only the bare identifier-like form
116
+ (no sign, no decimal point, no sign in the exponent). Floats written
117
+ by Python always carry a sign in the exponent (1e+16, 1e-05) and are
118
+ therefore not reported.""",
119
+ ),
120
+ _k(
121
+ "boolean",
122
+ "cell",
123
+ "The words TRUE and FALSE become boolean values.",
124
+ """In any letter case, the English words TRUE and FALSE are converted
125
+ to booleans and shown in capitals. Localised versions of Excel
126
+ recognise their own words as well; cellsafe only checks the English
127
+ ones.""",
128
+ ),
129
+ _k(
130
+ "leading-apostrophe",
131
+ "cell",
132
+ "Value starts with an apostrophe, which spreadsheets use as a text marker.",
133
+ """Typed into a cell, a leading apostrophe means 'treat the rest as
134
+ text' and is not displayed. When a CSV file is opened the apostrophe
135
+ is, as far as documented behaviour goes, kept as a visible character,
136
+ but it disappears as soon as the cell is edited, and other tools that
137
+ strip the OWASP apostrophe on import would strip this one too. The
138
+ kind is report-only; cellsafe's own reader does not confuse it with
139
+ its formula prefix.""",
140
+ ),
141
+ _k(
142
+ "non-ascii-digits",
143
+ "cell",
144
+ "Number written with Arabic-Indic or Persian digits stays text.",
145
+ """A cell made only of Arabic-Indic (U+0660 to U+0669) or Persian /
146
+ Extended Arabic-Indic (U+06F0 to U+06F9) digits is, in most
147
+ configurations, not recognised as a number, so it cannot be summed or
148
+ sorted numerically. With digits='ascii' cellsafe rewrites such cells
149
+ with ASCII digits (and maps the Arabic decimal and thousands
150
+ separators and percent sign). Digits inside ordinary text are never
151
+ touched. The rewrite is not reversible by cellsafe.reader.""",
152
+ ),
153
+ _k(
154
+ "bidi-control",
155
+ "cell",
156
+ "Cell contains invisible bidirectional control characters.",
157
+ """Characters such as LRM, RLM, ALM, the embeddings and overrides
158
+ (U+202A to U+202E) and the isolates (U+2066 to U+2069) are invisible
159
+ but change the order in which text is displayed, and they make two
160
+ cells that look the same compare as different. They are sometimes
161
+ needed to render mixed right-to-left and left-to-right text
162
+ correctly, so the default is to report them; bidi='strip' removes
163
+ them, which is not reversible.""",
164
+ ),
165
+ _k(
166
+ "missing-bom",
167
+ "file",
168
+ "UTF-8 file with non-ASCII text and no byte order mark.",
169
+ """Excel on Windows has long opened a double-clicked CSV file in the
170
+ system ANSI code page unless the file starts with a byte order mark,
171
+ so Arabic, Hebrew, Cyrillic or accented text shows as mojibake.
172
+ Writing the file as 'utf-8-sig' (UTF-8 with BOM) fixes this. The
173
+ check is only made for the 'excel' target.""",
174
+ ),
175
+ _k(
176
+ "encoding-fallback",
177
+ "file",
178
+ "File is not valid UTF-8 and has no BOM; a fallback encoding was used.",
179
+ """cellsafe does not guess encodings. It recognises byte order marks,
180
+ then tries strict UTF-8, then decodes with the fallback encoding the
181
+ caller supplied (cp1252 unless told otherwise). When the fallback
182
+ was needed the decoded text may be wrong, and so may every finding
183
+ based on it.""",
184
+ ),
185
+ _k(
186
+ "mixed-line-endings",
187
+ "file",
188
+ "Records end with more than one kind of line terminator.",
189
+ """The file mixes CRLF, LF or bare CR at the end of records. Line
190
+ breaks inside quoted cells are not counted. Some importers split or
191
+ merge records on such files.""",
192
+ ),
193
+ _k(
194
+ "sep-directive",
195
+ "file",
196
+ "File starts with 'sep=' data that could be read as a separator line.",
197
+ """Excel reads a first line of the form sep=; as an instruction naming
198
+ the separator, not as data (a widely reported Excel convention; it is
199
+ not part of the CSV format), and cellsafe's own reader and audit do
200
+ the same with a first line that is exactly sep= plus one character.
201
+ So a data value such as 'sep=;' in the first cell of the first row
202
+ would vanish and could change how the rest of the file is split.
203
+ The writer quotes such a first cell, whatever the policy, so the line
204
+ starts with a quote character instead; the value is not changed and
205
+ reads back unchanged. The check ignores letter case and leading
206
+ spaces, and is skipped when the writer adds its own sep= line
207
+ (sep_hint=True), because the data then starts on the second line.
208
+ audit reports a first line that starts with 'sep=' but is not a
209
+ plain sep= line it accepts as a hint, such as 'SEP=;' or 'sep=;,x'.
210
+ Whether Excel treats every such variant as a directive, and whether it
211
+ ignores a quoted first cell, was not verified.""",
212
+ ),
213
+ _k(
214
+ "ragged-row",
215
+ "file",
216
+ "Row has a different number of cells than the first row.",
217
+ """Rows with too few or too many cells usually mean an unquoted
218
+ separator or line break in the data, or the wrong separator was
219
+ assumed. Empty lines are not reported.""",
220
+ ),
221
+ _k(
222
+ "empty-header",
223
+ "file",
224
+ "A header cell is empty.",
225
+ """The first row is taken as the header (unless told otherwise). An
226
+ empty header cell makes the column hard to refer to in tables, pivot
227
+ tables and data-frame libraries.""",
228
+ ),
229
+ _k(
230
+ "duplicate-header",
231
+ "file",
232
+ "A header name appears more than once.",
233
+ """Duplicate column names are renamed or rejected by tables, pivot
234
+ tables and data-frame libraries. Names are compared exactly, after
235
+ trimming surrounding spaces.""",
236
+ ),
237
+ ]
238
+
239
+ KINDS: dict[str, Kind] = {kind.name: kind for kind in _ALL}
240
+
241
+ #: Data-damage kinds that a ``data`` protection strategy turns into text.
242
+ PROTECTABLE = frozenset(
243
+ {
244
+ "precision-loss",
245
+ "scientific-display",
246
+ "leading-zero",
247
+ "plus-sign",
248
+ "date-like",
249
+ "locale-date",
250
+ "exponent",
251
+ "boolean",
252
+ }
253
+ )
cellsafe/_policy.py ADDED
@@ -0,0 +1,126 @@
1
+ """Policies: what to do about each kind of risk."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ from dataclasses import dataclass, field
7
+
8
+ from ._kinds import KINDS
9
+
10
+ _FORMULA = ("quote", "tab", "none")
11
+ _NUMBERS = ("keep", "escape")
12
+ _DATA = ("report", "formula", "tab", "zero-width")
13
+ _DIGITS = ("keep", "ascii")
14
+ _BIDI = ("keep", "strip")
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Policy:
19
+ """How cells are neutralised and protected.
20
+
21
+ formula
22
+ ``"quote"``: prefix formula-like cells with an apostrophe (OWASP).
23
+ ``"tab"``: prefix them with a tab character.
24
+ ``"none"``: leave them alone (they are still reported).
25
+ numbers
26
+ ``"keep"``: a cell that is only a signed number (``-5``, ``-3.2e4``)
27
+ is not treated as a formula. ``"escape"``: it is, as OWASP says.
28
+ data
29
+ What to do with cells a spreadsheet would silently change (long digit
30
+ strings, leading zeros, date-like text, ...).
31
+ ``"report"``: nothing, only report. ``"formula"``: write ``="0123"``.
32
+ ``"tab"``: prefix a tab. ``"zero-width"``: prefix U+200B.
33
+ digits
34
+ ``"keep"`` or ``"ascii"`` (rewrite cells that are numbers in
35
+ Arabic-Indic or Persian digits with ASCII digits; not reversible).
36
+ bidi
37
+ ``"keep"`` or ``"strip"`` (remove bidi control characters; not
38
+ reversible).
39
+ ignore
40
+ Risk kinds that are neither reported nor acted on.
41
+ """
42
+
43
+ name: str = "custom"
44
+ formula: str = "quote"
45
+ numbers: str = "keep"
46
+ data: str = "report"
47
+ digits: str = "keep"
48
+ bidi: str = "keep"
49
+ ignore: frozenset[str] = field(default_factory=frozenset)
50
+
51
+ def __post_init__(self) -> None:
52
+ object.__setattr__(self, "ignore", frozenset(self.ignore))
53
+ for attr, allowed in (
54
+ ("formula", _FORMULA),
55
+ ("numbers", _NUMBERS),
56
+ ("data", _DATA),
57
+ ("digits", _DIGITS),
58
+ ("bidi", _BIDI),
59
+ ):
60
+ value = getattr(self, attr)
61
+ if value not in allowed:
62
+ raise ValueError(
63
+ f"policy {attr}={value!r} is not one of {', '.join(allowed)}"
64
+ )
65
+ unknown = sorted(self.ignore - set(KINDS))
66
+ if unknown:
67
+ raise ValueError(f"unknown risk kind(s) in ignore: {', '.join(unknown)}")
68
+ if "formula" in self.ignore:
69
+ raise ValueError(
70
+ "the 'formula' kind cannot be ignored; use formula='none' to "
71
+ "switch formula neutralisation off"
72
+ )
73
+ if self.formula == "none" and self.data != "report":
74
+ raise ValueError(
75
+ "data protection needs formula neutralisation: with "
76
+ "formula='none' the protected cells could not be told apart "
77
+ "from original data"
78
+ )
79
+
80
+ def replace(self, **changes: object) -> "Policy":
81
+ """Return a copy with some fields changed (named ``custom`` unless given)."""
82
+ changes.setdefault("name", "custom")
83
+ return dataclasses.replace(self, **changes) # type: ignore[arg-type]
84
+
85
+
86
+ POLICIES: dict[str, Policy] = {
87
+ "default": Policy(name="default"),
88
+ "strict": Policy(name="strict", numbers="escape"),
89
+ "excel-text": Policy(name="excel-text", data="formula"),
90
+ "tab": Policy(name="tab", formula="tab", data="tab"),
91
+ "zero-width": Policy(name="zero-width", data="zero-width"),
92
+ "off": Policy(name="off", formula="none"),
93
+ }
94
+
95
+ POLICY_SUMMARIES: dict[str, str] = {
96
+ "default": "apostrophe before formulas; plain signed numbers kept; data risks reported only",
97
+ "strict": "apostrophe before every cell starting with = + - @ tab CR, numbers included",
98
+ "excel-text": "like default, and data-risk cells written as =\"...\" so Excel keeps them as text",
99
+ "tab": "tab before formulas and before data-risk cells",
100
+ "zero-width": "like default, and U+200B before data-risk cells",
101
+ "off": "change nothing; findings are still reported",
102
+ }
103
+
104
+
105
+ def resolve_policy(policy: "str | Policy | None" = None, **overrides: object) -> Policy:
106
+ """Turn a policy name or :class:`Policy` into a :class:`Policy`.
107
+
108
+ Keyword arguments override individual fields, for example
109
+ ``resolve_policy("default", digits="ascii", ignore={"locale-date"})``.
110
+ """
111
+ if policy is None:
112
+ policy = "default"
113
+ if isinstance(policy, str):
114
+ try:
115
+ resolved = POLICIES[policy]
116
+ except KeyError:
117
+ raise ValueError(
118
+ f"unknown policy {policy!r}; choose one of {', '.join(POLICIES)}"
119
+ ) from None
120
+ elif isinstance(policy, Policy):
121
+ resolved = policy
122
+ else:
123
+ raise TypeError("policy must be a policy name or a cellsafe.Policy")
124
+ if overrides:
125
+ resolved = resolved.replace(**overrides)
126
+ return resolved
cellsafe/_protect.py ADDED
@@ -0,0 +1,198 @@
1
+ """Apply a policy to a single cell, and reverse it.
2
+
3
+ Round-trip guarantee. For every policy except those with ``formula="none"``
4
+ and for every text value ``v`` whose digits and bidi characters the policy
5
+ does not rewrite::
6
+
7
+ unprotect(sanitize(v, policy), policy) == v
8
+
9
+ Why it holds. Write N(v) for "v needs formula neutralisation" and P(v) for
10
+ "v needs data protection". ``sanitize`` adds the formula prefix exactly when
11
+ N(v), otherwise the data protection exactly when P(v), otherwise nothing.
12
+ ``unprotect`` removes a formula prefix only when the remainder satisfies N,
13
+ and a data protection only when the remainder satisfies P. The detection
14
+ rules are built so that an unprotected original can never look protected:
15
+ a value that starts with the formula prefix followed by something satisfying
16
+ N satisfies N itself (leading quotes and whitespace are skipped, a leading
17
+ tab is a trigger), a value of the form ``="..."`` starts with ``=`` and so
18
+ satisfies N, and P is defined to include values that already start with the
19
+ data prefix followed by something satisfying P.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import numbers
25
+ import re
26
+ from dataclasses import dataclass, field
27
+ from decimal import Decimal
28
+
29
+ from . import _detect
30
+ from ._detect import Risk
31
+ from ._kinds import PROTECTABLE
32
+ from ._policy import Policy, resolve_policy
33
+
34
+ REPORTED_ONLY = "reported only"
35
+
36
+ _FORMULA_PREFIX = {"quote": "'", "tab": "\t"}
37
+ _FORMULA_ACTION = {"quote": "prefixed with an apostrophe", "tab": "prefixed with a tab"}
38
+ _DATA_PREFIX = {"tab": "\t", "zero-width": "​"}
39
+ _DATA_ACTION = {
40
+ "formula": 'wrapped as ="..."',
41
+ "tab": "prefixed with a tab",
42
+ "zero-width": "prefixed with a zero-width space",
43
+ }
44
+ _WRAPPED = re.compile(r'="((?:[^"]|"")*)"')
45
+ #: Excel limits a string literal inside a formula to 255 characters.
46
+ _MAX_WRAP = 255
47
+ _INTEGER_KINDS = ("precision-loss", "scientific-display")
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Outcome:
52
+ """Result of applying a policy to one cell."""
53
+
54
+ original: str
55
+ output: str
56
+ risks: tuple[Risk, ...] = ()
57
+ actions: dict[str, str] = field(default_factory=dict)
58
+
59
+ @property
60
+ def changed(self) -> bool:
61
+ return self.output != self.original
62
+
63
+ def action_for(self, kind: str) -> str:
64
+ return self.actions.get(kind, REPORTED_ONLY)
65
+
66
+
67
+ def to_text(value: object) -> tuple[str, str]:
68
+ """Return ``(text, type_tag)`` the way ``csv.writer`` would write *value*.
69
+
70
+ The tag is ``"text"`` for strings and unknown objects, ``"integer"`` for
71
+ ints and Decimals (still checked for digit loss) and ``"number"`` for
72
+ floats and bools (written as they are; the caller chose a numeric type).
73
+ """
74
+ if value is None:
75
+ return "", "text"
76
+ if isinstance(value, str):
77
+ return value, "text"
78
+ if isinstance(value, (bool, float)):
79
+ return repr(value), "number"
80
+ if isinstance(value, (numbers.Integral, Decimal)):
81
+ return str(value), "integer"
82
+ return str(value), "text"
83
+
84
+
85
+ def _data_kinds(text: str, tag: str, policy: Policy) -> list[Risk]:
86
+ if tag == "number":
87
+ return []
88
+ found = _detect.data_risks(text)
89
+ if tag == "integer":
90
+ found = [r for r in found if r.kind in _INTEGER_KINDS]
91
+ return [r for r in found if r.kind not in policy.ignore]
92
+
93
+
94
+ def _needs_formula(text: str, policy: Policy) -> str | None:
95
+ reason = _detect.formula_reason(text)
96
+ if reason is None:
97
+ return None
98
+ if policy.numbers == "keep" and _detect.is_plain_number(text):
99
+ return None
100
+ return reason
101
+
102
+
103
+ def _needs_data(text: str, tag: str, policy: Policy) -> bool:
104
+ prefix = _DATA_PREFIX.get(policy.data)
105
+ if prefix and tag == "text":
106
+ text = text.lstrip(prefix)
107
+ return any(r.kind in PROTECTABLE for r in _data_kinds(text, tag, policy))
108
+
109
+
110
+ def analyse(value: object, policy: Policy) -> Outcome:
111
+ """Detect the risks in *value* and compute what *policy* would write."""
112
+ original, tag = to_text(value)
113
+ text = original
114
+ found: list[Risk] = []
115
+ actions: dict[str, str] = {}
116
+
117
+ controls = _detect.bidi_controls_in(text)
118
+ if controls:
119
+ names = ", ".join(sorted({f"U+{ord(ch):04X}" for ch in controls}))
120
+ found.append(Risk("bidi-control", f"contains bidi control character(s) {names}"))
121
+ if policy.bidi == "strip":
122
+ text = _detect.strip_bidi_controls(text)
123
+ actions["bidi-control"] = "bidi control characters removed"
124
+
125
+ if _detect.is_non_ascii_number(text):
126
+ found.append(
127
+ Risk("non-ascii-digits", "number in Arabic-Indic or Persian digits stays text")
128
+ )
129
+ if policy.digits == "ascii":
130
+ text = _detect.normalise_digits(text)
131
+ actions["non-ascii-digits"] = "digits rewritten in ASCII"
132
+
133
+ reason = _needs_formula(text, policy)
134
+ if reason is not None:
135
+ found.append(Risk("formula", reason))
136
+ data = _data_kinds(text, tag, policy)
137
+ found.extend(data)
138
+ found = [r for r in found if r.kind not in policy.ignore]
139
+ protectable = [r.kind for r in data if r.kind in PROTECTABLE]
140
+
141
+ output = text
142
+ if reason is not None and policy.formula != "none":
143
+ output = _FORMULA_PREFIX[policy.formula] + text
144
+ actions["formula"] = _FORMULA_ACTION[policy.formula]
145
+ for kind in protectable: # the cell is text now, so these are covered too
146
+ actions[kind] = _FORMULA_ACTION[policy.formula]
147
+ elif policy.data != "report" and _needs_data(text, tag, policy):
148
+ if policy.data == "formula":
149
+ if len(text) <= _MAX_WRAP and "\n" not in text and "\r" not in text:
150
+ output = '="' + text.replace('"', '""') + '"'
151
+ else:
152
+ output = _DATA_PREFIX[policy.data] + text
153
+ if output != text:
154
+ for kind in protectable:
155
+ actions[kind] = _DATA_ACTION[policy.data]
156
+
157
+ return Outcome(original, output, tuple(found), actions)
158
+
159
+
160
+ def sanitize(value: object, policy: "str | Policy | None" = None, **overrides: object) -> str:
161
+ """Return the text to write for *value* under *policy*.
162
+
163
+ ``None`` becomes an empty string and other non-string values are
164
+ converted the way ``csv.writer`` converts them.
165
+ """
166
+ return analyse(value, resolve_policy(policy, **overrides)).output
167
+
168
+
169
+ def risks(value: object, policy: "str | Policy | None" = None, **overrides: object) -> list[Risk]:
170
+ """List the risks in a single cell value.
171
+
172
+ The policy only matters for what counts: ``numbers="escape"`` reports
173
+ plain signed numbers as ``formula``, and kinds in ``ignore`` are left out.
174
+ """
175
+ return list(analyse(value, resolve_policy(policy, **overrides)).risks)
176
+
177
+
178
+ def unprotect(text: str, policy: "str | Policy | None" = None, **overrides: object) -> str:
179
+ """Reverse :func:`sanitize` for a cell read back from a CSV file.
180
+
181
+ Must be called with the policy the file was written with. Digit
182
+ normalisation and bidi stripping cannot be reversed.
183
+ """
184
+ pol = resolve_policy(policy, **overrides)
185
+ prefix = _FORMULA_PREFIX.get(pol.formula)
186
+ if prefix and text.startswith(prefix) and _needs_formula(text[1:], pol):
187
+ return text[1:]
188
+ if pol.data == "formula":
189
+ m = _WRAPPED.fullmatch(text)
190
+ if m:
191
+ inner = m.group(1).replace('""', '"')
192
+ if len(inner) <= _MAX_WRAP and _needs_data(inner, "text", pol):
193
+ return inner
194
+ elif pol.data in _DATA_PREFIX:
195
+ prefix = _DATA_PREFIX[pol.data]
196
+ if text.startswith(prefix) and _needs_data(text[1:], "text", pol):
197
+ return text[1:]
198
+ return text