Skip to content

Commit 035fdb3

Browse files
committed
Reject missing file checksums in SPDX exports
Stop substituting the empty-file SHA1 for files whose checksum is unknown. Raise a clear error directing users to collect checksums with --info, while preserving known checksums and the empty-file special case. Add writer and CLI regressions for both SPDX formats, document the requirement, and give the Unicode scan fixture the checksum of its included synthetic SVG. The full SPDX suite passes: 38 tests on Windows/Python 3.14.2. Fixes #3453 Assisted-by: OpenAI Codex Signed-off-by: Shrashti1234 <sharishhtia@gmail.com>
1 parent e423b48 commit 035fdb3

7 files changed

Lines changed: 127 additions & 6 deletions

File tree

‎AUTHORS.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ The following organizations or individuals have contributed to ScanCode:
8484
- Sebastian Schuberth @sschuberth
8585
- Shankhadeep Dey @Iamshankhadeep
8686
- Sharikzama @ZamaSharik
87+
- Shrashti @Shrashti1234
8788
- Shrijal Acharya @OctoPie23
8889
- Shivam Chauhan @chashiv
8990
- Shivam Sandbhor @sbs2001

‎CHANGELOG.rst‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ Changelog
44
Next release
55
--------------
66

7+
- Reject SPDX output for non-empty files without a SHA1 checksum instead
8+
of substituting the empty-file hash. Scan with ``--info`` to collect checksums.
9+
https://github.com/aboutcode-org/scancode-toolkit/issues/3453
10+
711
- Fix the optional ``licenses`` extra dependency typo to install
812
``licensedcode-data``.
913
https://github.com/aboutcode-org/scancode-toolkit/pull/5056

‎docs/source/reference/scancode-cli/cli-output-format-options.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,14 @@ Comparing different ``json`` output formats
330330
``--spdx-rdf FILE``
331331
-------------------
332332

333+
.. note::
334+
335+
SPDX RDF and Tag/Value exports require file SHA1 checksums. Include
336+
``--info`` (``-i``) when scanning to collect them. When exporting an existing
337+
scan with ``--from-json``, that scan must already contain the checksums.
338+
Export fails with an error identifying the file if a non-empty file's
339+
checksum is missing; an unknown checksum is not replaced by the empty-file hash.
340+
333341
`SPDX <https://spdx.org/>`_ stands for "Software Package and Data Exchange" and is an open standard
334342
for communicating software bill of material information (including components, licenses,
335343
copyrights, and security references).

‎src/formattedcode/output_spdx.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def check_sha1(codebase):
172172

173173
click.secho(
174174
'WARNING: Files are missing a SHA1 attribute. '
175-
'Incomplete SPDX document created.',
175+
'Include --info when scanning to collect file checksums.',
176176
err=True,
177177
fg='red',
178178
)
@@ -261,8 +261,13 @@ def write_spdx(
261261
if file_data.get('file_type') == 'empty':
262262
checksum = Checksum(ChecksumAlgorithm.SHA1, "da39a3ee5e6b4b0d3255bfef95601890afd80709")
263263
else:
264-
# FIXME: this sets the checksum of a file to the empty string hash if unknown; tracked in https://github.com/nexB/scancode-toolkit/issues/3453
265-
checksum = Checksum(ChecksumAlgorithm.SHA1, file_data.get('sha1') or 'da39a3ee5e6b4b0d3255bfef95601890afd80709')
264+
sha1 = file_data.get('sha1')
265+
if not sha1:
266+
raise ValueError(
267+
f'Cannot create SPDX output: missing SHA1 for file {name!r}. '
268+
'Run a scan with --info to collect file checksums.'
269+
)
270+
checksum = Checksum(ChecksumAlgorithm.SHA1, sha1)
266271

267272
file_entry = File(
268273
spdx_id=f'SPDXRef-{sid}',

‎tests/formattedcode/data/spdx/unicode.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
{
1717
"path": "han/\u636e.svg",
1818
"type": "file",
19-
"scan_errors": []
19+
"scan_errors": [],
20+
"sha1": "c26d7e350178d93f90d9b22482d3d86f1da67180"
2021
}
2122
]
2223
}
Lines changed: 1 addition & 0 deletions
Loading

‎tests/formattedcode/test_output_spdx.py‎

Lines changed: 103 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#
1010

1111
import io
12+
import hashlib
1213
import os
1314
import re
1415

@@ -26,6 +27,100 @@
2627
test_env.test_data_dir = os.path.join(os.path.dirname(__file__), 'data')
2728

2829

30+
def write_spdx_for_checksum_test(file_data, as_tagvalue, monkeypatch):
31+
from formattedcode.output_spdx import write_spdx
32+
from licensedcode import cache
33+
34+
# These inputs contain no license detections and need no license database.
35+
monkeypatch.setattr(cache, 'get_licenses_db', lambda: {})
36+
output = io.StringIO()
37+
write_spdx(
38+
codebase=None,
39+
output_file=output,
40+
files=[file_data],
41+
tool_name='ScanCode',
42+
tool_version='test',
43+
notice='test',
44+
package_name='sample',
45+
as_tagvalue=as_tagvalue,
46+
)
47+
return output.getvalue()
48+
49+
50+
@pytest.mark.parametrize('as_tagvalue', [True, False], ids=['tagvalue', 'rdf'])
51+
@pytest.mark.parametrize('checksum_data', [{}, {'sha1': None}, {'sha1': ''}])
52+
def test_spdx_missing_sha1_rejected(as_tagvalue, checksum_data, monkeypatch):
53+
file_data = {'type': 'file', 'path': 'sample.txt', 'file_type': 'ASCII text'}
54+
file_data.update(checksum_data)
55+
with pytest.raises(ValueError, match='missing SHA1.*sample.txt'):
56+
write_spdx_for_checksum_test(file_data, as_tagvalue, monkeypatch)
57+
58+
59+
@pytest.mark.parametrize('as_tagvalue', [True, False], ids=['tagvalue', 'rdf'])
60+
def test_spdx_file_checksum_preserves_known_sha1(as_tagvalue, monkeypatch):
61+
checksum = hashlib.sha1(b'non-empty contents').hexdigest()
62+
result = write_spdx_for_checksum_test(
63+
{'type': 'file', 'path': 'sample.txt', 'sha1': checksum},
64+
as_tagvalue,
65+
monkeypatch,
66+
)
67+
assert checksum in result
68+
assert hashlib.sha1(b'').hexdigest() not in result
69+
70+
71+
@pytest.mark.parametrize('as_tagvalue', [True, False], ids=['tagvalue', 'rdf'])
72+
def test_spdx_file_checksum_preserves_empty_file_hash(as_tagvalue, monkeypatch):
73+
result = write_spdx_for_checksum_test(
74+
{'type': 'file', 'path': 'empty.txt', 'file_type': 'empty'},
75+
as_tagvalue,
76+
monkeypatch,
77+
)
78+
assert hashlib.sha1(b'').hexdigest() in result
79+
80+
81+
@pytest.mark.parametrize('as_tagvalue', [True, False], ids=['tagvalue', 'rdf'])
82+
def test_spdx_file_checksum_does_not_require_directory_hash(as_tagvalue, monkeypatch):
83+
result = write_spdx_for_checksum_test(
84+
{'type': 'directory', 'path': 'directory'},
85+
as_tagvalue,
86+
monkeypatch,
87+
)
88+
assert "No results for package 'sample'." in result
89+
90+
91+
@pytest.mark.parametrize('output_option', ['--spdx-tv', '--spdx-rdf'])
92+
def test_spdx_missing_sha1_cli_error(output_option, tmp_path, monkeypatch):
93+
from licensedcode import cache
94+
95+
monkeypatch.setattr(cache, 'get_licenses_db', lambda: {})
96+
source = tmp_path / 'sample.txt'
97+
source.write_text('non-empty contents', encoding='utf-8')
98+
output = tmp_path / 'output.spdx'
99+
result = run_scan_click(
100+
['--email', str(source), output_option, str(output)],
101+
expected_rc=1,
102+
retry=False,
103+
)
104+
assert 'missing SHA1' in result.output
105+
assert 'sample.txt' in result.output
106+
assert '--info' in result.output
107+
if output.exists():
108+
assert not output.read_text(encoding='utf-8')
109+
110+
111+
@pytest.mark.parametrize('output_option', ['--spdx-tv', '--spdx-rdf'])
112+
@pytest.mark.parametrize('content', [b'non-empty contents', b''])
113+
def test_spdx_file_checksum_cli_with_info(output_option, content, tmp_path, monkeypatch):
114+
from licensedcode import cache
115+
116+
monkeypatch.setattr(cache, 'get_licenses_db', lambda: {})
117+
source = tmp_path / 'sample.txt'
118+
source.write_bytes(content)
119+
output = tmp_path / 'output.spdx'
120+
run_scan_click(['--info', str(source), output_option, str(output)])
121+
assert hashlib.sha1(content).hexdigest() in output.read_text(encoding='utf-8')
122+
123+
29124
def strip_variable_text(rdf_text):
30125
"""
31126
Return rdf_text stripped from variable parts such as rdf nodeids
@@ -339,15 +434,21 @@ def test_spdx_rdf_with_empty_scan():
339434

340435

341436
@pytest.mark.scanslow
342-
def test_output_spdx_rdf_can_handle_non_ascii_paths():
437+
def test_output_spdx_rdf_can_handle_non_ascii_paths(monkeypatch):
438+
from licensedcode import cache
439+
440+
monkeypatch.setattr(cache, 'get_licenses_db', lambda: {})
343441
test_file = test_env.get_test_loc('spdx/unicode.json')
344442
result_file = test_env.get_temp_file(extension='spdx', file_name='test_spdx')
345443
run_scan_click(['--from-json', test_file, '--spdx-rdf', result_file])
346444
with io.open(result_file, encoding='utf-8') as res:
347445
results = res.read()
348446
assert 'han/据.svg' in results
349447

350-
def test_output_spdx_tv_can_handle_non_ascii_paths():
448+
def test_output_spdx_tv_can_handle_non_ascii_paths(monkeypatch):
449+
from licensedcode import cache
450+
451+
monkeypatch.setattr(cache, 'get_licenses_db', lambda: {})
351452
test_file = test_env.get_test_loc('spdx/unicode.json')
352453
result_file = test_env.get_temp_file(extension='spdx', file_name='test_spdx')
353454
run_scan_click(['--from-json', test_file, '--spdx-tv', result_file])

0 commit comments

Comments
 (0)