Skip to content

Commit 621202a

Browse files
fix: harden report publication and serialization (#19)
1 parent 5eb2249 commit 621202a

3 files changed

Lines changed: 63 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,6 @@ Dual licensed: [AGPL-3.0](LICENSE), including commercial use that meets its term
9696
<a href="https://complete.tech"><img src="assets/logo.png" alt="CompleteTech LLC" width="160"></a><br>
9797
<sub>Built by <a href="https://complete.tech">CompleteTech LLC</a> · Innovation at Every Integration</sub>
9898
</p>
99+
100+
An interruption after a complete report is published preserves that report and exits 130.
101+
CSV rejects NUL characters before writing a report.

‎node2shell_check.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import argparse
99
import base64
1010
import csv
11+
import io
1112
import html
1213
import json
1314
import math
@@ -678,6 +679,8 @@ def positive_float(value):
678679
def csv_safe(value):
679680
if isinstance(value, list):
680681
value = " | ".join(value)
682+
if isinstance(value, str) and "\x00" in value:
683+
raise ValueError("CSV values cannot contain NUL characters")
681684
# Prevent spreadsheet formulas from untrusted page titles / response fields.
682685
if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")):
683686
return "'" + value
@@ -820,7 +823,9 @@ def write_report(output, rows, *, format="csv", logo=DEFAULT_LOGO, brand="Comple
820823
def save_report(path, rows, *, force=False, **options):
821824
"""Publish a complete file atomically, refusing an existing path by default."""
822825
if path is None:
823-
write_report(sys.stdout, rows, **options)
826+
rendered = io.StringIO(newline="")
827+
write_report(rendered, rows, **options)
828+
sys.stdout.write(rendered.getvalue())
824829
return
825830
path = Path(path)
826831
temporary = None
@@ -910,7 +915,10 @@ def main(argv=None) -> int:
910915
print("Interrupted; preserving completed results.", file=sys.stderr)
911916
try:
912917
save_report(args.output, rows, force=args.force, format=args.format, logo=logo, brand=args.brand, complete=complete)
913-
except (OSError, ValueError) as exc:
918+
except KeyboardInterrupt:
919+
print("Interrupted while writing the report; output may be incomplete.", file=sys.stderr)
920+
return 130
921+
except (OSError, ValueError, csv.Error) as exc:
914922
print(f"Cannot write report: {exc}", file=sys.stderr)
915923
return 2
916924
if not complete:

‎test_publication_boundaries.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""Portable CSV and single-output publication regressions; offline fixtures only."""
2+
import contextlib
3+
import csv
4+
import io
5+
import json
6+
from pathlib import Path
7+
import tempfile
8+
import unittest
9+
from unittest import mock
10+
import node2shell_check as c
11+
class CsvPublicationTests(unittest.TestCase):
12+
def run_cli(self,*args):
13+
with contextlib.redirect_stdout(io.StringIO()) as out,contextlib.redirect_stderr(io.StringIO()) as err:
14+
code=c.main(list(args))
15+
return code,out.getvalue(),err.getvalue()
16+
def test_nul_inventory_csv_rejects_before_publication(self):
17+
with tempfile.TemporaryDirectory() as directory:
18+
inventory=Path(directory)/'inventory.json'
19+
inventory.write_text(json.dumps({'schema_version':1,'runtime':'node','node_version':'24.22.1','label':'example\x00asset'}))
20+
for mode in ['stdout','new','force']:
21+
target=Path(directory)/(mode+'.csv');extra=[]
22+
if mode!='stdout':extra=['--output',str(target)]
23+
if mode=='force':target.write_text('KEEP');extra+=['--force']
24+
code,out,err=self.run_cli('--inventory',str(inventory),'--format','csv',*extra)
25+
self.assertEqual((2,''),(code,out));self.assertNotIn('Traceback',err)
26+
if mode=='force':self.assertEqual('KEEP',target.read_text())
27+
else:self.assertFalse(target.exists())
28+
code,out,_=self.run_cli('--inventory',str(inventory),'--format','json')
29+
self.assertEqual(0,code);self.assertEqual(1,len(json.loads(out)['results']))
30+
def test_bare_carriage_return_in_inventory_keeps_one_csv_record(self):
31+
with tempfile.TemporaryDirectory() as directory:
32+
inventory=Path(directory)/'inventory.json'
33+
inventory.write_text(json.dumps({'schema_version':1,'runtime':'node','node_version':'24.22.1','label':'example\r=1+1'}))
34+
code,out,_=self.run_cli('--inventory',str(inventory),'--format','csv')
35+
self.assertEqual(0,code)
36+
rows=list(csv.DictReader(io.StringIO(out,newline='')))
37+
self.assertEqual(1,len(rows));self.assertNotIn(None,rows[0])
38+
self.assertTrue(any('\r=1+1' in value for value in rows[0].values()))
39+
def test_partial_stdout_interrupt_has_one_write_and_exit130(self):
40+
class Sink:
41+
calls=0
42+
def write(self,data):self.calls+=1;raise KeyboardInterrupt
43+
sink=Sink()
44+
with contextlib.redirect_stdout(sink),contextlib.redirect_stderr(io.StringIO()):
45+
escaped=False
46+
try:code=c.main(['--node-version','24.22.1','--format','json'])
47+
except KeyboardInterrupt:escaped=True;code=130
48+
self.assertFalse(escaped,'main must handle its publication interruption')
49+
self.assertEqual(130,code);self.assertEqual(1,sink.calls)
50+
if __name__=='__main__':unittest.main()

0 commit comments

Comments
 (0)