cellsafe 0.1.2__tar.gz

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-0.1.2/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cellsafe contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,609 @@
1
+ Metadata-Version: 2.4
2
+ Name: cellsafe
3
+ Version: 0.1.2
4
+ Summary: Write and check CSV files so that spreadsheet programs open them without damaging or misusing the data.
5
+ Author: cellsafe contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/RealAoss/cellsafe
8
+ Project-URL: Issues, https://github.com/RealAoss/cellsafe/issues
9
+ Project-URL: Changelog, https://github.com/RealAoss/cellsafe/blob/main/CHANGELOG.md
10
+ Keywords: csv,excel,spreadsheet,csv-injection,formula-injection,utf-8,bom
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
22
+ Classifier: Topic :: Security
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # cellsafe
29
+
30
+ Write and check CSV files so that spreadsheet programs (Excel, LibreOffice
31
+ Calc, Google Sheets) open them without damaging or misusing the data.
32
+
33
+ A CSV file has no types. When a spreadsheet opens one it guesses, and the
34
+ guesses can run a cell as a formula, turn `00123` into `123`, turn `MAR1`
35
+ into a date, cut a 16-digit number down to 15 digits, or show Arabic text as
36
+ mojibake. cellsafe is a thin layer over Python's standard `csv` module that
37
+
38
+ - neutralises formula-like cells when writing,
39
+ - picks an encoding, separator and line ending that suit the program that
40
+ will open the file,
41
+ - detects cells a spreadsheet would silently change and, if you ask it to,
42
+ protects them,
43
+ - audits existing CSV files and reports every such cell with its row and
44
+ column.
45
+
46
+ Python 3.10 or later. Standard library only.
47
+
48
+ **Read this first.** The rules in this package come from documented and
49
+ widely reported spreadsheet behaviour. They were **not tested against a
50
+ running copy of Excel, Google Sheets or LibreOffice** while it was written.
51
+ What the test suite proves is what cellsafe writes, byte for byte, and that
52
+ the original data can always be read back. See
53
+ [What was and was not tested](#what-was-and-was-not-tested).
54
+
55
+ No CSV trick is perfect. If the people opening your file must get exact
56
+ values with exact types, give them a real `.xlsx` file with typed cells.
57
+ cellsafe does not write `.xlsx`.
58
+
59
+ ## Install
60
+
61
+ cellsafe is not on PyPI. Install it from the repository:
62
+
63
+ ```
64
+ pip install git+https://github.com/RealAoss/cellsafe
65
+ ```
66
+
67
+ ## Quick start
68
+
69
+ ```pycon
70
+ >>> import cellsafe
71
+ >>> rows = [["id", "name", "total"], ["00123", "=1+1", -5]]
72
+ >>> print(cellsafe.dumps(rows), end="")
73
+ id,name,total
74
+ 00123,'=1+1,-5
75
+ >>> report = cellsafe.audit("id,name,total\n00123,=1+1,-5\n")
76
+ >>> for finding in report.findings:
77
+ ... print(finding.cell, finding.kind, "-", finding.action)
78
+ A2 leading-zero - reported only
79
+ B2 formula - prefixed with an apostrophe
80
+
81
+ ```
82
+
83
+ Writing a file works like `csv.writer`:
84
+
85
+ ```python
86
+ import cellsafe
87
+
88
+ with cellsafe.writer("report.csv", target="excel") as w:
89
+ w.writerow(["id", "name", "total"])
90
+ w.writerows(rows)
91
+ ```
92
+
93
+ ## The problems
94
+
95
+ ### 1. Formula injection
96
+
97
+ A cell that starts with `=`, `+`, `-` or `@` is evaluated as a formula. The
98
+ [OWASP guidance on CSV injection](https://owasp.org/www-community/attacks/CSV_Injection)
99
+ also lists a leading tab and carriage return. cellsafe looks past leading
100
+ whitespace and quote characters as well, and recognises the full-width forms
101
+ (U+FF1D, U+FF0B, U+FF0D, U+FF20). The risk kind is `formula`.
102
+
103
+ | Value | Written by default |
104
+ | --- | --- |
105
+ | `=SUM(A1:A2)` | `'=SUM(A1:A2)` |
106
+ | `+1+1` | `'+1+1` |
107
+ | `@SUM(1)` | `'@SUM(1)` |
108
+ | `-5` | `-5` |
109
+ | `-3.2e4` | `-3.2e4` |
110
+ | `+962 7 9000 0000` | `'+962 7 9000 0000` |
111
+ | `@handle` | `'@handle` |
112
+
113
+ ```pycon
114
+ >>> cellsafe.sanitize("=SUM(A1:A2)")
115
+ "'=SUM(A1:A2)"
116
+ >>> cellsafe.sanitize("-5"), cellsafe.sanitize("-3.2e4")
117
+ ('-5', '-3.2e4')
118
+ >>> cellsafe.sanitize("-5", policy="strict")
119
+ "'-5"
120
+ >>> cellsafe.sanitize("=SUM(A1:A2)", policy="tab")
121
+ '\t=SUM(A1:A2)'
122
+
123
+ ```
124
+
125
+ Two neutralising strategies are implemented:
126
+
127
+ - **Apostrophe prefix** (`formula="quote"`, the default). This is what OWASP
128
+ recommends. The cell becomes text. The apostrophe is visible in the opened
129
+ sheet, which is ugly but tells the reader that the cell was altered.
130
+ - **Tab prefix** (`formula="tab"`). Invisible in the sheet. It is not the
131
+ default because OWASP lists a leading tab as a trigger character itself,
132
+ so by the same reference a tab-prefixed cell is still a suspect cell, and
133
+ some import paths trim leading whitespace.
134
+
135
+ OWASP also asks for every field to be wrapped in double quotes with embedded
136
+ quotes doubled. The purpose is to stop a value from breaking out of its
137
+ cell; the `csv` module's quoting already guarantees that. Pass
138
+ `quoting=csv.QUOTE_ALL` if you want the quotes on every field anyway.
139
+
140
+ **Numbers.** OWASP's rule, taken literally, turns every negative number into
141
+ text, and sums over that column then stop working. The default policy
142
+ (`numbers="keep"`) leaves a cell alone when it is nothing but a number:
143
+ optional sign, ASCII digits, `.` or `,` separators, an optional exponent and
144
+ an optional `%`. Such a cell contains no letters, cell references or
145
+ operators, so it cannot call a function. The `strict` policy
146
+ (`numbers="escape"`) follows OWASP to the letter. The trade-off is yours:
147
+ `default` keeps numeric columns usable and relies on the argument above;
148
+ `strict` relies on nothing and costs you the numbers.
149
+
150
+ **Phone numbers and handles.** `+962 7 9000 0000` and `@handle` are not
151
+ plain numbers, and a spreadsheet would try to evaluate them (`@handle` can
152
+ resolve to a named range or, if it looks like `@A1`, to a cell). Leaving
153
+ them alone would let the spreadsheet change them, so they get the prefix.
154
+ The value is not lost: it stays readable in the sheet, and
155
+ `cellsafe.reader` or `cellsafe.unprotect` returns the original.
156
+
157
+ ```pycon
158
+ >>> cellsafe.sanitize("+962 7 9000 0000")
159
+ "'+962 7 9000 0000"
160
+ >>> cellsafe.unprotect("'+962 7 9000 0000")
161
+ '+962 7 9000 0000'
162
+
163
+ ```
164
+
165
+ ### 2. Mojibake for non-ASCII text
166
+
167
+ Excel on Windows has long opened a double-clicked CSV file in the system
168
+ ANSI code page unless the file starts with a byte order mark, so UTF-8
169
+ Arabic, Hebrew, Cyrillic or accented text turns into garbage: `café` shows
170
+ as `café` in code page 1252, and `שלום` as a run of `×` and punctuation.
171
+
172
+ | Output | Bytes at the start | When it is the right choice |
173
+ | --- | --- | --- |
174
+ | `utf-8-sig`, comma (default for `target="excel"`) | `EF BB BF` | The usual choice. Other tools can still read the file, though they should open it as `utf-8-sig` so the mark does not end up in the first header. |
175
+ | `utf-16` (UTF-16 LE with BOM), tab | `FF FE` | When the readers use Excel in a locale whose list separator is not the comma (see problem 4): tabs do not depend on the locale. Poor choice for anything that is not a spreadsheet: twice the size for ASCII text, and few tools expect it. |
176
+
177
+ ```pycon
178
+ >>> cellsafe.dumpb([["name"], ["שלום"]])[:3]
179
+ b'\xef\xbb\xbf'
180
+ >>> cellsafe.dumpb([["a", "b"]], encoding="utf-16")
181
+ b'\xff\xfea\x00\t\x00b\x00\r\x00\n\x00'
182
+
183
+ ```
184
+
185
+ `cellsafe.audit` reports `missing-bom` for a UTF-8 file that has non-ASCII
186
+ text and no mark (only for the `excel` target), and `encoding-fallback` when
187
+ a file was not UTF-8 at all.
188
+
189
+ A byte order mark can only be written when cellsafe does the encoding, that
190
+ is, when you pass a path or a binary stream. If you pass a text stream (or
191
+ use `dumps`, which returns a `str`), the encoding is yours to choose.
192
+
193
+ ### 3. Silent data damage on open
194
+
195
+ `cellsafe.risks(value)` lists what a spreadsheet would do to one cell:
196
+
197
+ | Kind | Example | What happens |
198
+ | --- | --- | --- |
199
+ | `precision-loss` | `1234567890123456` | More than 15 significant digits: the rest become zeros. Card numbers, account numbers, barcodes, long IDs. |
200
+ | `scientific-display` | `123456789012` | Integers of 12 to 15 digits are shown as `1.23457E+11`; saving the sheet as CSV writes that form. |
201
+ | `leading-zero` | `00123`, `0790000000` | Leading zeros are dropped. Postal codes, phone numbers, IDs. |
202
+ | `plus-sign` | `+96279000000` | The `+` is dropped. |
203
+ | `date-like` | `1-2`, `3/4`, `MAR1`, `SEPT2` | Converted to a date; the text is not kept. |
204
+ | `locale-date` | `01/02/2024` | Day/month order depends on the reader's locale. |
205
+ | `exponent` | `1E5`, `12E3` | Read as `100000` and `12000`. |
206
+ | `boolean` | `TRUE`, `false` | Becomes a boolean, shown in capitals. |
207
+ | `leading-apostrophe` | `'hello` | The apostrophe is a text marker in spreadsheets; report-only. |
208
+
209
+ ```pycon
210
+ >>> cellsafe.risks("00123")
211
+ [Risk(kind='leading-zero', message='leading zeros are dropped')]
212
+ >>> for value in ["1234567890123456", "1-2", "MAR1", "1E5", "TRUE", "2024-01-15", "-5", "hello"]:
213
+ ... print(value, [risk.kind for risk in cellsafe.risks(value)])
214
+ 1234567890123456 ['precision-loss']
215
+ 1-2 ['date-like']
216
+ MAR1 ['date-like']
217
+ 1E5 ['exponent']
218
+ TRUE ['boolean']
219
+ 2024-01-15 []
220
+ -5 []
221
+ hello []
222
+
223
+ ```
224
+
225
+ A complete year-first date such as `2024-01-15` is not reported: turning it
226
+ into a date is normally what you want. If you also want `01/02/2024` or
227
+ `1-Feb` converted, put those kinds in the policy's ignore set:
228
+
229
+ ```pycon
230
+ >>> policy = cellsafe.resolve_policy("excel-text", ignore={"date-like", "locale-date"})
231
+ >>> cellsafe.sanitize("1-Feb", policy), cellsafe.sanitize("00123", policy)
232
+ ('1-Feb', '="00123"')
233
+
234
+ ```
235
+
236
+ What to do about these cells is a policy decision, and every option has a
237
+ cost:
238
+
239
+ | `data=` | Writes | Good | Bad |
240
+ | --- | --- | --- | --- |
241
+ | `report` (default) | `00123` | The file stays ordinary CSV. Nothing is hidden: `audit` and `writer.findings` tell you what is at risk. | The spreadsheet will still change the cell. |
242
+ | `formula` | `="00123"` | Excel evaluates the formula and shows `00123` as text. | Every program that does not evaluate formulas on import (pandas, databases, text editors, and spreadsheet imports with formula evaluation off) sees the literal text `="00123"`. Not usable for values over 255 characters (cellsafe leaves those unprotected and says so). |
243
+ | `tab` | a tab, then `00123` | Nothing visible in the sheet. | The cell value now starts with a tab: lookups and comparisons against `00123` fail, copy and paste carries the tab along, importers that trim whitespace undo the protection, and `audit` flags the cell as `formula` because a leading tab is on OWASP's list. |
244
+ | `zero-width` | U+200B, then `00123` | Nothing visible in the sheet. | Same as the tab, and harder to notice: an invisible character that survives in whatever the data is pasted into next. |
245
+
246
+ ```pycon
247
+ >>> cellsafe.sanitize("00123", policy="excel-text")
248
+ '="00123"'
249
+ >>> cellsafe.sanitize("00123", policy="tab")
250
+ '\t00123'
251
+ >>> cellsafe.sanitize("00123", policy="zero-width")
252
+ '\u200b00123'
253
+ >>> cellsafe.sanitize("00123")
254
+ '00123'
255
+
256
+ ```
257
+
258
+ The default is `report` because all three protections change the bytes that
259
+ every non-spreadsheet reader of the file gets. That should be something you
260
+ choose, not something that happens to you.
261
+
262
+ The robust answer is not a CSV trick: write an `.xlsx` file with the cells
263
+ typed as text, or have the users import the CSV through the spreadsheet's
264
+ import dialog and set the column types there.
265
+
266
+ ### 4. Structure
267
+
268
+ **Quoting.** cellsafe uses the `csv` module, so separators, quotes and line
269
+ breaks inside a cell are quoted correctly. Rows that contain a line break in
270
+ a cell are written with every field quoted.
271
+
272
+ **Line endings.** Every record ends the same way: CRLF for the `excel`,
273
+ `sheets` and `libreoffice` targets, LF for `plain`. Line breaks inside a
274
+ cell are kept as they are.
275
+
276
+ **The list separator.** Excel splits a double-clicked CSV on the Windows
277
+ regional *list separator*. In many locales where the comma is the decimal
278
+ mark that is the semicolon, and a comma-separated file lands entirely in
279
+ column A. There is no encoding of this in CSV itself. The options:
280
+
281
+ - `sep_hint=True` writes a first line `sep=,` (or whatever the delimiter
282
+ is). Excel reads the hint. It is an Excel convention: other programs show
283
+ it as a data row, and there are reports that Excel ignores the UTF-8 byte
284
+ order mark when the hint line is present, which brings back problem 2.
285
+ - `encoding="utf-16"` writes UTF-16 LE with tabs, which does not depend on
286
+ the list separator.
287
+ - `delimiter=";"` if you know the readers' locale.
288
+
289
+ ```pycon
290
+ >>> print(cellsafe.dumps([["a;b", 'say "hi"'], ["1", "2"]], delimiter=";", sep_hint=True), end="")
291
+ sep=;
292
+ "a;b";"say ""hi"""
293
+ 1;2
294
+
295
+ ```
296
+
297
+ **Checks.** `audit` reports `ragged-row`, `empty-header`,
298
+ `duplicate-header`, `mixed-line-endings` and `sep-directive` (below).
299
+
300
+ ```pycon
301
+ >>> report = cellsafe.audit("id,name,name\n1,x\n")
302
+ >>> [(f.kind, f.cell or f"row {f.row}") for f in report.findings]
303
+ [('duplicate-header', 'C1'), ('ragged-row', 'row 2')]
304
+
305
+ ```
306
+
307
+ **Data that looks like a `sep=` line** (`sep-directive`). Excel and
308
+ `cellsafe.reader` take a first line such as `sep=;` for the separator hint,
309
+ not for data, so a first cell holding that text would vanish. When the
310
+ writer does not add its own hint line, it quotes a first cell that starts
311
+ with `sep=` (in any letter case, after spaces), under every policy, and
312
+ reports it. The value is unchanged and reads back as it was written. Cells
313
+ in later rows or columns are left alone. `audit` reports a first line that
314
+ starts with `sep=` but is not a hint line it accepts (such as `SEP=;` or
315
+ `Sep=x,y`).
316
+
317
+ ```pycon
318
+ >>> rows = [["sep=;"], ["a;b"]]
319
+ >>> data = cellsafe.dumpb(rows)
320
+ >>> data
321
+ b'\xef\xbb\xbf"sep=;"\r\na;b\r\n'
322
+ >>> list(cellsafe.reader(data)) == rows
323
+ True
324
+ >>> [(f.kind, f.cell, f.value) for f in cellsafe.audit("Sep=x,y\n1,2\n").findings]
325
+ [('sep-directive', 'A1', 'Sep=x')]
326
+
327
+ ```
328
+
329
+ ### 5. Right-to-left text
330
+
331
+ Nothing in a CSV file can set the direction of a sheet, a column or a cell.
332
+ A spreadsheet opens the file left-to-right and the user switches the sheet
333
+ direction by hand. cellsafe cannot change that and does not pretend to.
334
+
335
+ Two things it does handle:
336
+
337
+ - **Digits.** A number written in Arabic-Indic (`٠١٢٣٤٥٦٧٨٩`) or Persian
338
+ (`۰۱۲۳۴۵۶۷۸۹`) digits is usually kept as text, so it cannot be summed
339
+ (`non-ascii-digits`). With `digits="ascii"` cells that consist only of such
340
+ a number are rewritten in ASCII digits; digits inside other text are left
341
+ alone.
342
+ - **Bidi control characters.** LRM, RLM, ALM, the embedding and override
343
+ characters and the isolates are invisible, change the displayed order of
344
+ text and make equal-looking cells unequal (`bidi-control`). They are
345
+ reported. `bidi="strip"` removes them; they are sometimes needed for mixed
346
+ right-to-left and left-to-right text to display correctly, which is why
347
+ stripping is not the default.
348
+
349
+ ```pycon
350
+ >>> [risk.kind for risk in cellsafe.risks("١٢٣")]
351
+ ['non-ascii-digits']
352
+ >>> cellsafe.sanitize("١٢٣", digits="ascii")
353
+ '123'
354
+ >>> [risk.kind for risk in cellsafe.risks("abc\u202edef")]
355
+ ['bidi-control']
356
+ >>> cellsafe.sanitize("abc\u202edef", bidi="strip")
357
+ 'abcdef'
358
+
359
+ ```
360
+
361
+ Neither rewrite can be undone by `cellsafe.reader`.
362
+
363
+ ## Policies
364
+
365
+ A policy says what to do about each kind of risk. Pass a name or a
366
+ `cellsafe.Policy`.
367
+
368
+ | Policy | Formula cells | Plain signed numbers | Data-risk cells | Trade-off |
369
+ | --- | --- | --- | --- | --- |
370
+ | `default` | apostrophe | kept | reported only | Numeric columns keep working; data risks are visible in the report but the spreadsheet will still act on them. |
371
+ | `strict` | apostrophe | apostrophe | reported only | OWASP to the letter; negative numbers become text. |
372
+ | `excel-text` | apostrophe | kept | `="..."` | Best result in Excel; the file is no longer plain CSV for other programs. |
373
+ | `tab` | tab | kept | tab prefix | Nothing visible, but a tab in every protected value and weaker formula protection. |
374
+ | `zero-width` | apostrophe | kept | U+200B prefix | Nothing visible, and an invisible character in every protected value. |
375
+ | `off` | unchanged | kept | reported only | Changes nothing. For auditing only. |
376
+
377
+ `default` is the default because it applies the one change that is a
378
+ security matter (formulas), with the strategy OWASP documents, and leaves
379
+ every other byte of your data as you wrote it.
380
+
381
+ Fields of `cellsafe.Policy`, all combinable:
382
+
383
+ ```pycon
384
+ >>> policy = cellsafe.Policy(formula="quote", numbers="keep", data="formula",
385
+ ... digits="ascii", bidi="strip", ignore={"boolean"})
386
+ >>> cellsafe.sanitize("TRUE", policy), cellsafe.sanitize("٠١٢", policy)
387
+ ('TRUE', '="012"')
388
+ >>> cellsafe.resolve_policy("strict", data="tab").numbers
389
+ 'escape'
390
+
391
+ ```
392
+
393
+ ## Targets
394
+
395
+ | Target | Encoding | Separator | Line ending | Why |
396
+ | --- | --- | --- | --- | --- |
397
+ | `excel` (default) | UTF-8 with BOM | `,` | CRLF | Excel needs the mark to read UTF-8. |
398
+ | `sheets` | UTF-8 | `,` | CRLF | Google Sheets imports UTF-8. |
399
+ | `libreoffice` | UTF-8 | `,` | CRLF | LibreOffice shows an import dialog where the encoding and separator are chosen. |
400
+ | `plain` | UTF-8 | `,` | LF | For programs, not spreadsheets. Formula neutralisation still applies unless the policy is `off`. |
401
+
402
+ `encoding=`, `delimiter=`, `lineterminator=` and `sep_hint=` override the
403
+ target. `encoding="utf-16"` always means UTF-16 little endian with a byte
404
+ order mark, and switches the default separator to a tab.
405
+
406
+ ## API
407
+
408
+ ```python
409
+ cellsafe.writer(file, *, target="excel", policy="default", encoding=None,
410
+ delimiter=None, lineterminator=None, sep_hint=False, **csv_options)
411
+ cellsafe.DictWriter(file, fieldnames, restval="", extrasaction="raise", **same_options)
412
+ cellsafe.dumps(rows, **same_options) -> str # no byte order mark
413
+ cellsafe.dumpb(rows, **same_options) -> bytes # encoded, with the mark
414
+ cellsafe.reader(file, *, target="excel", policy="default", delimiter=None,
415
+ encoding=None, fallback_encoding="cp1252") -> iterator of rows
416
+ cellsafe.sanitize(value, policy="default", **policy_fields) -> str
417
+ cellsafe.unprotect(text, policy="default", **policy_fields) -> str
418
+ cellsafe.risks(value, policy="default", **policy_fields) -> list[Risk]
419
+ cellsafe.audit(source, *, target="excel", policy="default", delimiter=None,
420
+ fallback_encoding="cp1252", header=True, protected=False) -> Report
421
+ cellsafe.resolve_policy(name_or_policy, **policy_fields) -> Policy
422
+ ```
423
+
424
+ - `file` for `writer` is a path, a binary stream or a text stream (open text
425
+ files with `newline=""`, as for `csv.writer`). `writer.findings` collects
426
+ a `Finding` for every risky cell written, `writer.changed` counts the
427
+ cells that were altered. Call `close()` or use `with`; a stream you passed
428
+ in is flushed, not closed.
429
+ - Python numbers are written as `csv.writer` writes them. A `float` or
430
+ `bool` is taken to be meant as a number; an `int` or `Decimal` is still
431
+ checked for `precision-loss` and `scientific-display`.
432
+ - `audit(source)`: `source` is a path (`os.PathLike`, or a `str` with no
433
+ line break in it), CSV text (a `str` containing a line break), `bytes`, or
434
+ a readable stream.
435
+ - `Report` has `ok`, `findings`, `counts()`, `to_dict()`, `format_text()`
436
+ and the detected `encoding`, `bom`, `delimiter`, `line_endings`, `rows`,
437
+ `columns`. A `Finding` has `kind`, `message`, `row`, `column`, `cell`
438
+ (such as `B3`), `value`, `action` and `fix` (the cell text the policy
439
+ would write, or `None`). Rows are counted as the opened sheet counts them:
440
+ a `sep=` line is not a row.
441
+
442
+ ```pycon
443
+ >>> report = cellsafe.audit("id,value\n00123,=1+1\n", policy="excel-text")
444
+ >>> report.ok
445
+ False
446
+ >>> for f in report.findings:
447
+ ... print(f.row, f.column, f.cell, f.kind, repr(f.fix))
448
+ 2 1 A2 leading-zero '="00123"'
449
+ 2 2 B2 formula "'=1+1"
450
+ >>> report.counts()
451
+ {'leading-zero': 1, 'formula': 1}
452
+
453
+ ```
454
+
455
+ ### Reading the data back
456
+
457
+ Protection is reversible. `cellsafe.reader` reads a file and removes what
458
+ the writer added; `cellsafe.unprotect` does it for one cell. Both need the
459
+ policy the file was written with. The test suite checks this for every
460
+ policy, including for values that already start with an apostrophe, a tab,
461
+ a zero-width space or `="`.
462
+
463
+ ```pycon
464
+ >>> import io
465
+ >>> rows = [["id", "v"], ["00123", "=1+1"], ["'kept", "-5"]]
466
+ >>> text = cellsafe.dumps(rows, policy="excel-text")
467
+ >>> print(text, end="")
468
+ id,v
469
+ "=""00123""",'=1+1
470
+ 'kept,-5
471
+ >>> list(cellsafe.reader(io.StringIO(text, newline=""), policy="excel-text")) == rows
472
+ True
473
+
474
+ ```
475
+
476
+ Not reversible: `digits="ascii"`, `bidi="strip"`, and the `off` policy has
477
+ nothing to reverse. `sanitize` is not idempotent: protecting a protected
478
+ file again adds a second layer, so tell `fix` what it is looking at with
479
+ `--from-policy`.
480
+
481
+ `reader` reads the whole input into memory, and a `str` argument is always a
482
+ path.
483
+
484
+ ## Command line
485
+
486
+ ```
487
+ cellsafe audit FILE [--format text|json] [--target T] [--policy P] [--protected]
488
+ [--delimiter CHAR] [--fallback-encoding ENC] [--no-header]
489
+ [--ignore KIND]... [--digits ascii] [--bidi strip]
490
+ cellsafe fix IN -o OUT [--target T] [--policy P] [--encoding utf-8-sig|utf-8|utf-16]
491
+ [--out-delimiter CHAR] [--sep-hint] [--from-policy P] [--force]
492
+ [--delimiter CHAR] [--fallback-encoding ENC]
493
+ [--ignore KIND]... [--digits ascii] [--bidi strip]
494
+ cellsafe explain KIND
495
+ cellsafe kinds
496
+ ```
497
+
498
+ - `audit` prints one line per finding and exits with status 1 if there are
499
+ any, 0 if there are none, 2 on errors. `--protected` says the file was
500
+ written by cellsafe with the given policy, so cells that are already
501
+ protected are not reported again.
502
+ - `fix` writes a protected copy. It never edits in place: the output must be
503
+ a different file, and an existing output file is only replaced with
504
+ `--force`.
505
+ - `explain KIND` prints what a kind means and what can be done about it;
506
+ `kinds` lists all kinds and policies.
507
+ - `python -m cellsafe` works the same way.
508
+
509
+ ```
510
+ $ cellsafe audit orders.csv
511
+ orders.csv: 3 rows, 3 columns, utf-8, no BOM, delimiter ',', line endings CRLF
512
+ file missing-bom non-ASCII text in UTF-8 without a byte order mark; Excel on Windows reads it in the ANSI code page
513
+ A2 leading-zero leading zeros are dropped; value '00123' (reported only)
514
+ C2 formula starts with '='; value '=1+1' -> "'=1+1" (prefixed with an apostrophe)
515
+ 3 finding(s) under policy 'default': missing-bom: 1, leading-zero: 1, formula: 1
516
+ $ cellsafe fix orders.csv -o orders-safe.csv --policy excel-text
517
+ wrote orders-safe.csv: 3 rows, 2 cell(s) changed, encoding utf-8-sig, delimiter ','
518
+ ```
519
+
520
+ **Input encoding.** cellsafe does not guess encodings. For input it
521
+ recognises byte order marks (UTF-8, UTF-16, UTF-32), then tries strict
522
+ UTF-8, then uses the fallback encoding you supply (`cp1252` unless you say
523
+ otherwise) and reports `encoding-fallback`. If that fails too, it stops
524
+ with an error.
525
+
526
+ **Input separator.** Taken from a `sep=` line, else from `--delimiter`,
527
+ else the most frequent of `,` `;` tab `|` in the first record. That is a
528
+ simple count, not a sniffer; name the delimiter when in doubt.
529
+
530
+ ## Limits
531
+
532
+ - Not handled: times (`1:30`), fractions written with a space (`1 1/2`),
533
+ currency and percent conversion, trailing zeros in decimals (`1.10`
534
+ becomes `1.1`), thousands separators, month names in languages other than
535
+ English, boolean words other than `TRUE`/`FALSE`.
536
+ - The date patterns approximate Excel in an English locale. They will flag
537
+ some text Excel leaves alone and miss some it converts.
538
+ - `exponent` only matches digits, `E`, digits. `1.5E3` or `1E-5` as an
539
+ identifier is not reported.
540
+ - Detection is per cell. There is no notion of "this column is an ID
541
+ column"; use `ignore` to switch kinds off for a whole file.
542
+ - The digit rewrite covers Arabic-Indic and Persian digits only.
543
+ - `audit`, `reader` and `fix` read the whole file into memory.
544
+ - The `"..."` formula wrapper, the tab and the zero-width space are tricks.
545
+ A spreadsheet update can change how any of them is treated.
546
+ - No `.xlsx` output.
547
+
548
+ ## What was and was not tested
549
+
550
+ Tested, by the `unittest` suite in `tests/` (standard library only, no
551
+ network): which cells are detected; the exact text and bytes written for
552
+ each policy, target and encoding, including the byte order marks; that
553
+ `csv.reader` parses the output back into the same cells; that
554
+ `cellsafe.reader`/`unprotect` recover the original value for every policy;
555
+ the audit report; the command line; and the examples in this README.
556
+
557
+ **Not tested: the behaviour of real Excel, Google Sheets or LibreOffice.**
558
+ No spreadsheet program was opened while this package was written. Whether a
559
+ given cell is then displayed, converted or evaluated the way this document
560
+ says rests on the sources below, not on an experiment.
561
+
562
+ Well established (vendor documentation, OWASP, or long and consistent public
563
+ record):
564
+
565
+ - Cells starting with `=`, `+`, `-`, `@` are evaluated; the OWASP
566
+ recommendation is the apostrophe prefix.
567
+ - Excel keeps 15 significant digits; long integers are shown in scientific
568
+ notation; leading zeros are dropped.
569
+ - Excel converts `1-2`, `3/4`, `MAR1`, `SEPT2` to dates and `1E5` to a
570
+ number (the cause of the gene-name errors reported in the scientific
571
+ literature), and `TRUE`/`FALSE` to booleans.
572
+ - Excel on Windows needs a byte order mark to read a double-clicked UTF-8
573
+ CSV correctly, and splits on the regional list separator.
574
+ - `="00123"` in a CSV cell is shown by Excel as the text `00123`.
575
+ - An apostrophe-prefixed CSV cell is not evaluated, and the apostrophe is
576
+ shown.
577
+
578
+ Less sure (plausible and commonly reported, but version- or
579
+ setting-dependent, and not verified here):
580
+
581
+ - That current Excel builds still need the byte order mark in every case;
582
+ and how far the automatic data conversion settings in newer builds, where
583
+ the user has switched conversions off, make some of the data-damage kinds
584
+ moot.
585
+ - That Excel ignores the byte order mark when a `sep=` line is present.
586
+ - Which variants of a first line starting with `sep=` (letter case, spaces,
587
+ more than one character after `=`) Excel takes for a hint, and that it
588
+ does not take a quoted first cell such as `"sep=;"` for one.
589
+ - That a tab-separated UTF-16 file with a `.csv` extension opens in columns
590
+ in every Excel version.
591
+ - That a leading tab or zero-width space keeps a cell as text in all three
592
+ programs; LibreOffice and Google Sheets may trim or handle them
593
+ differently.
594
+ - How Google Sheets and LibreOffice treat `="00123"` and a leading
595
+ apostrophe on import (LibreOffice has an import option that controls
596
+ formula evaluation).
597
+ - That the full-width characters trigger formula evaluation outside East
598
+ Asian editions of Excel. Flagging them is the cautious choice.
599
+ - That Arabic-Indic and Persian digits are never parsed as numbers; this
600
+ may depend on the locale and settings of the spreadsheet.
601
+ - The exact set of date-like patterns, which differs between programs,
602
+ versions and locales.
603
+
604
+ If you can test any of these against a real program, a report is welcome;
605
+ see [CONTRIBUTING.md](CONTRIBUTING.md).
606
+
607
+ ## License
608
+
609
+ MIT. See [LICENSE](LICENSE).