Skip to content

Commit 16f7cd7

Browse files
authored
Fix #15279 (donate-cpu-server: modernize code and provide REST API) (cppcheck-opensource#9084)
1 parent 3eae36d commit 16f7cd7

8 files changed

Lines changed: 2093 additions & 5 deletions

File tree

‎.github/workflows/scriptcheck.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ jobs:
9797
python -m pip install requests
9898
python -m pip install psutil
9999
python -m pip install setuptools
100+
python -m pip install -r tools/donate-cpu-server-requirements.txt
101+
python -m pip install httpx
100102
101103
- name: run Shellcheck
102104
if: matrix.python-latest
@@ -191,6 +193,12 @@ jobs:
191193
env:
192194
PYTHONPATH: ./tools
193195

196+
- name: test donate_cpu_server_rest
197+
run: |
198+
python -m pytest -Werror --strict-markers -vv test/tools/donate_cpu_server_rest_test.py
199+
env:
200+
PYTHONPATH: ./tools
201+
194202
- name: Show all ignored files
195203
if: false # TODO: currently lists all the contents of ignored folders - we only need what actually matched
196204
run: |
Lines changed: 297 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,297 @@
1+
from importlib import import_module
2+
import time
3+
import warnings
4+
5+
import pytest
6+
7+
# the tests need the requirements of the server (donate-cpu-server-requirements.txt) and httpx
8+
pytest.importorskip('fastapi')
9+
pytest.importorskip('jinja2')
10+
pytest.importorskip('uvicorn')
11+
pytest.importorskip('httpx')
12+
13+
with warnings.catch_warnings():
14+
# newer Starlette versions warn that 'httpx2' should be used instead of 'httpx'
15+
warnings.filterwarnings('ignore', message='.*httpx2')
16+
from fastapi.testclient import TestClient # pylint: disable=wrong-import-position
17+
18+
server = import_module('donate-cpu-server-rest')
19+
20+
PKG_A = 'ftp://ftp.de.debian.org/debian/pool/main/a/aaa/aaa_1.0.orig.tar.gz'
21+
PKG_B = 'ftp://ftp.de.debian.org/debian/pool/main/b/bbb/bbb_1.0.orig.tar.gz'
22+
PKG_C = 'ftp://ftp.de.debian.org/debian/pool/main/c/ccc/ccc_1.0.orig.tar.xz'
23+
24+
RESULT_CRASH = '''{url}
25+
cppcheck-options: --library=posix
26+
platform: Linux-7
27+
python: 3.14.4
28+
client-version: 1.3.67
29+
compiler: g++ 15
30+
cppcheck: head {old}
31+
head-info: abc
32+
count: Crash! 5
33+
elapsed-time: -1.0 3.0
34+
head results:
35+
Program received signal SIGSEGV, Segmentation fault.
36+
0x000055 in Foo::bar (this=0x0) at lib/foo.cpp:12
37+
12 return x->y;
38+
#0 0x000055 in Foo::bar (this=0x0) at lib/foo.cpp:12
39+
#1 0x000066 in main (argc=1) at cli/main.cpp:3
40+
41+
aaa/x.c:1:1: error: <script>alert(1)</script> [syntaxError]
42+
diff:
43+
'''.format(url=PKG_A, old=server.OLD_VERSION)
44+
45+
# crash with an assertion failure message before the ' received signal ' line (donate-cpu 1.4.2)
46+
ASSERTION = "build/symboldatabase.cpp:6760: bool Variable::arrayDimensions(const Settings&, bool&): Assertion `x == 1' failed."
47+
RESULT_CRASH_ASSERTION = '''{url}
48+
cppcheck: head {old}
49+
count: Crash! 5
50+
elapsed-time: -6.0 3.0
51+
head results:
52+
Checking bbb/x.cpp ...
53+
54+
{assertion}
55+
Program received signal SIGABRT, Aborted.
56+
0x00007fdd4b3b569c in ?? () from /lib/x86_64-linux-gnu/libc.so.6
57+
#0 0x00007fdd4b3b569c in ?? () from /lib/x86_64-linux-gnu/libc.so.6
58+
#1 0x00007fdd4b349420 in abort () from /lib/x86_64-linux-gnu/libc.so.6
59+
#2 0x0000562c2c38806f in Variable::arrayDimensions (this=0x562c53552490) at build/symboldatabase.cpp:6760
60+
61+
diff:
62+
'''.format(url=PKG_B, old=server.OLD_VERSION, assertion=ASSERTION)
63+
64+
INFO = '''{url}
65+
cppcheck: head {old}
66+
info messages:
67+
aaa/x.c:1:1: information: --check-library: There is no matching configuration for function foo() [checkLibraryFunction]
68+
aaa/x.c:2:1: information: --check-library: There is no matching configuration for function foo() [checkLibraryFunction]
69+
aaa/x.c:3:1: information: --check-library: Function bar() should have <noreturn> configuration [checkLibraryNoReturn]
70+
aaa/x.c:4:1: information: --check-library: There is no matching configuration for unsigned int [checkLibraryCheckType]
71+
'''.format(url=PKG_A, old=server.OLD_VERSION)
72+
73+
# result file as written by donate-cpu-server.py
74+
RESULT_FILE_C = '''2026-11-01 10:00
75+
{url}
76+
cppcheck: head {old}
77+
count: 3 2
78+
elapsed-time: 10.0 2.0
79+
head results:
80+
ccc/a.c:1:2: error: Array 'a[2]' accessed at index 2, which is out of bounds. [arrayIndexOutOfBounds]
81+
ccc/b.c:4:1: error: There is an unknown macro here somewhere. Configuration is required. If FOO is a macro then please configure it. [unknownMacro]
82+
83+
diff:
84+
head ccc/a.c:1:2: error: Array 'a[2]' accessed at index 2, which is out of bounds. [arrayIndexOutOfBounds]
85+
{old} ccc/c.c:1:2: style: blah [knownConditionTrueFalse]
86+
'''.format(url=PKG_C, old=server.OLD_VERSION)
87+
88+
89+
@pytest.fixture(name='work_path')
90+
def fixture_work_path(tmp_path):
91+
(tmp_path / 'donated-results').mkdir()
92+
(tmp_path / 'packages.txt').write_text('\n'.join([PKG_A, PKG_B, PKG_C]) + '\n')
93+
(tmp_path / 'donated-results' / 'ccc').write_text(RESULT_FILE_C)
94+
return tmp_path
95+
96+
97+
@pytest.fixture(name='client')
98+
def fixture_client(work_path):
99+
app = server.create_app(str(work_path), rescan_interval=0.2)
100+
with TestClient(app) as client:
101+
for _ in range(100):
102+
if client.get('/api/v1/status').json()['index_ready']:
103+
break
104+
time.sleep(0.05)
105+
yield client
106+
107+
108+
def test_parse_result():
109+
entry = server.parse_result(RESULT_FILE_C)
110+
assert entry['date'] == '2026-11-01 10:00'
111+
assert entry['url'] == PKG_C
112+
assert entry['versions'] == ['head', server.OLD_VERSION]
113+
assert entry['count'] == ['3', '2']
114+
assert entry['elapsed'] == [10.0, 2.0]
115+
assert entry['head_ids'] == {'arrayIndexOutOfBounds': 1, 'unknownMacro': 1}
116+
assert entry['diff'] == {'arrayIndexOutOfBounds': [0, 1], 'knownConditionTrueFalse': [1, 0]}
117+
assert entry['names'] == {'unknownMacro': {'FOO': 1}}
118+
assert entry['crash'] is None
119+
120+
121+
def test_parse_crash():
122+
entry = server.parse_result('2026-11-27 10:00\n' + RESULT_CRASH)
123+
assert entry['crash'] == {
124+
'assertions': [],
125+
'crash_line': '0x000055 in Foo::bar (this=0x0) at lib/foo.cpp:12',
126+
'code_line': '12\t return x->y;',
127+
'stack_trace': ['#0 Foo::bar(...) at lib/foo.cpp:12', '#1 main(...) at cli/main.cpp:3'],
128+
}
129+
assert entry['head_ids'] == {'syntaxError': 1}
130+
131+
132+
def test_parse_crash_assertion():
133+
entry = server.parse_result('2026-11-27 10:00\n' + RESULT_CRASH_ASSERTION)
134+
assert entry['crash'] == {
135+
'assertions': [ASSERTION],
136+
'crash_line': '0x00007fdd4b3b569c in ?? () from /lib/x86_64-linux-gnu/libc.so.6',
137+
'code_line': '',
138+
'stack_trace': ['#0 ?? (...) from /lib/x86_64-linux-gnu/libc.so.6',
139+
'#1 abort (...) from /lib/x86_64-linux-gnu/libc.so.6',
140+
'#2 Variable::arrayDimensions(...) at build/symboldatabase.cpp:6760'],
141+
}
142+
# the "Checking" line is not an assertion failure
143+
entry = server.parse_result('2026-11-27 10:00\n' + RESULT_CRASH_ASSERTION.replace(ASSERTION + '\n', ''))
144+
assert entry['crash']['assertions'] == []
145+
146+
147+
def test_crash_report_assertion(client):
148+
assert client.post('/api/v1/results', content=RESULT_CRASH).status_code == 201
149+
assert client.post('/api/v1/results', content=RESULT_CRASH_ASSERTION).status_code == 201
150+
crash = client.get('/api/v1/reports/crash').json()
151+
assert [g['assertions'] for g in crash['stack_traces']] == [[], [ASSERTION]]
152+
assert [(p['package'], p['head_assert']) for p in crash['packages']] == [('aaa', False), ('bbb', True)]
153+
page = client.get('/crash.html').text
154+
assert page.count('>Assert failed<') == 1
155+
assert '>Crash/Assertion failure<' not in page
156+
157+
158+
def test_crash_report_old_crash_assertion(client):
159+
# old version crashed too => it might be the same assertion failure
160+
result = RESULT_CRASH_ASSERTION.replace('count: Crash! 5', 'count: Crash! Crash!')
161+
assert client.post('/api/v1/results', content=result).status_code == 201
162+
page = client.get('/crash.html').text
163+
assert page.count('>Assert failed<') == 1
164+
assert page.count('>Crash/Assertion failure<') == 1
165+
assert "Variable::arrayDimensions(const Settings&amp;, bool&amp;): Assertion `x == 1&#39; failed." in page
166+
167+
168+
def test_parse_info():
169+
entry = server.parse_info('2026-11-27 10:00\n' + INFO)
170+
assert entry['info_ids'] == {'checkLibraryFunction': 2, 'checkLibraryNoReturn': 1, 'checkLibraryCheckType': 1}
171+
assert entry['names'] == {
172+
'checkLibraryFunction': {'foo()': 2},
173+
'checkLibraryNoReturn': {'bar()': 1},
174+
'checkLibraryCheckType': {'unsigned int': 1},
175+
}
176+
177+
178+
def test_existing_results_are_indexed(client):
179+
assert client.get('/api/v1/status').json()['results'] == 1
180+
data = client.get('/api/v1/reports/time').json()
181+
assert [p['package'] for p in data['packages']] == ['ccc']
182+
assert data['packages'][0]['factor'] == 5.0
183+
184+
185+
def test_packages(client):
186+
assert client.get('/api/v1/versions').json() == {'versions': ['head', server.OLD_VERSION]}
187+
assert client.get('/api/v1/packages').json() == {'count': 3}
188+
assert client.post('/api/v1/packages/next').json() == {'index': 0, 'url': PKG_A}
189+
assert client.get('/api/v1/packages/2').json() == {'index': 2, 'url': PKG_C}
190+
assert client.get('/api/v1/packages/9').status_code == 404
191+
assert client.post('/api/v1/nodata', json={'url': PKG_B}).status_code == 200
192+
# PKG_B is not handed out any more
193+
assert [client.post('/api/v1/packages/next').json()['index'] for _ in range(3)] == [2, 0, 2]
194+
195+
196+
def test_upload(client):
197+
r = client.post('/api/v1/results', content=RESULT_CRASH + '\nDONE')
198+
assert r.status_code == 201 and r.json()['package'] == 'aaa'
199+
assert client.post('/api/v1/info', content=INFO).status_code == 201
200+
201+
crash = client.get('/api/v1/reports/crash').json()
202+
assert [p['package'] for p in crash['packages']] == ['aaa']
203+
assert crash['stack_traces'][0]['packages'] == ['aaa']
204+
assert client.get('/api/v1/reports/crash?packages_only=true').text == PKG_A + '\n'
205+
206+
names = client.get('/api/v1/reports/names/checkLibraryFunction').json()
207+
assert names['names'] == [{'name': 'foo()', 'count': 2}]
208+
209+
210+
def test_upload_errors(client, work_path):
211+
wrong_version = RESULT_CRASH.replace('head ' + server.OLD_VERSION, 'head 1.0')
212+
assert client.post('/api/v1/results', content=wrong_version).status_code == 422
213+
assert client.post('/api/v1/results', content='ftp://evil/x/../../y.tar.gz\nfoo').status_code == 400
214+
unknown = RESULT_CRASH.replace('/aaa/aaa_1.0', '/zzz/zzz_1.0')
215+
assert client.post('/api/v1/results', content=unknown).status_code == 404
216+
217+
# too large data removes the existing result
218+
big = PKG_C + '\ncppcheck: head ' + server.OLD_VERSION + '\n' + 'x' * server.MAX_RESULT_SIZE
219+
assert client.post('/api/v1/results', content=big).status_code == 413
220+
assert not (work_path / 'donated-results' / 'ccc').exists()
221+
222+
223+
def test_files_written_by_old_server_are_picked_up(client, work_path):
224+
(work_path / 'donated-results' / 'aaa').write_text('2026-11-27 10:00\n' + RESULT_CRASH)
225+
for _ in range(100):
226+
if client.get('/api/v1/status').json()['results'] == 2:
227+
break
228+
time.sleep(0.05)
229+
assert client.get('/api/v1/status').json()['results'] == 2
230+
231+
232+
def test_html_pages(client):
233+
client.post('/api/v1/results', content=RESULT_CRASH)
234+
client.post('/api/v1/info', content=INFO)
235+
pages = ['/', '/crash.html', '/timeout.html', '/stale.html', '/diff.html', '/diff-knownConditionTrueFalse',
236+
'/head.html', '/headinfo.html', '/head-syntaxError', '/headtoday-syntaxError', '/headinfo-checkLibraryFunction',
237+
'/latest.html', '/time_lt.html', '/time_gt.html', '/time_slow.html', '/clients.html',
238+
'/check_library_function_report.html', '/check_library_check_type_report.html', '/unknown_macro.html',
239+
'/value_flow_bailout_incomplete_var.html']
240+
for page in pages:
241+
r = client.get(page)
242+
assert r.status_code == 200, page
243+
assert r.headers['content-type'].startswith('text/html'), page
244+
assert '<script>' not in r.text, page
245+
246+
assert '&lt;script&gt;' in client.get('/head-syntaxError').text
247+
assert client.get('/head-syntaxError?pkgs=1').text == PKG_A + '\n'
248+
assert 'unknownMacro' in client.get('/head.html').text
249+
250+
251+
def test_html_name_pages(client):
252+
client.post('/api/v1/info', content=INFO)
253+
assert 'Function bar() should have' in client.get('/check_library-bar%28%29').text
254+
# '+' is a space, as in the links of donate-cpu-server.py
255+
assert 'configuration for unsigned int' in client.get('/check_library-unsigned+int').text
256+
assert 'please configure it' in client.get('/unknown_macro-FOO').text
257+
258+
259+
def test_html_name_pages_packages_link(client):
260+
# the "packages.txt" link must give the same name as the page
261+
info = INFO + 'aaa/x.c:5:1: information: --check-library: There is no matching configuration for function operator+() [checkLibraryFunction]\n'
262+
assert client.post('/api/v1/info', content=info).status_code == 201
263+
for path in ['/check_library-operator%2B%28%29', '/check_library-unsigned+int']:
264+
page = client.get(path).text
265+
assert 'href="{}?pkgs=1"'.format(path) in page, path
266+
assert client.get(path + '?pkgs=1').text == PKG_A + '\n', path
267+
268+
269+
def test_safe_path(tmp_path):
270+
directory = str(tmp_path)
271+
assert server.safe_path(directory, 'pkg') == str(tmp_path / 'pkg')
272+
assert server.safe_path(directory + '/', 'pkg') == str(tmp_path / 'pkg')
273+
for name in ('', '.', '..', '../pkg', 'a/b', '/etc/passwd', 'a/../../pkg'):
274+
with pytest.raises(ValueError):
275+
server.safe_path(directory, name)
276+
277+
278+
def test_upload_invalid_package_name(work_path):
279+
# even if such an url is in packages.txt, nothing is written outside the result path
280+
url = 'ftp://ftp.de.debian.org/debian/pool/main/x/../x.orig.tar.gz'
281+
with open(str(work_path / 'packages.txt'), 'at') as f:
282+
f.write(url + '\n')
283+
app = server.create_app(str(work_path), rescan_interval=0.2)
284+
with TestClient(app) as client:
285+
data = RESULT_CRASH.replace(PKG_A, url)
286+
assert client.post('/api/v1/results', content=data).status_code == 400
287+
assert client.post('/api/v1/info', content=data).status_code == 400
288+
assert sorted(p.name for p in work_path.iterdir()) == ['donated-results', 'packages.txt', 'report-index']
289+
290+
291+
def test_raw_files(client):
292+
client.post('/api/v1/info', content=INFO)
293+
r = client.get('/ccc')
294+
assert r.status_code == 200 and r.text == RESULT_FILE_C
295+
assert client.get('/info_output/aaa').status_code == 200
296+
assert client.get('/nonexistent').status_code == 404
297+
assert client.get('/..%2F..%2Fetc%2Fpasswd').status_code == 404
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
fastapi
2+
uvicorn
3+
jinja2

0 commit comments

Comments
 (0)