From 403e7f1f7d7380981ce8daf725f244014ddfe004 Mon Sep 17 00:00:00 2001 From: thingsconnected <45596685+thingsconnected@users.noreply.github.com> Date: Mon, 25 Dec 2023 05:49:17 +0100 Subject: [PATCH] lib/addoninfo.cpp: When loading a JSON addon, test 'script' key. (#5797) In case a user accidentally uses a wrong JSON file (e.g. naming.json, which is the config file for namingng.py), the code could give a confusing exception. This happens when the key 'script' is not defined as a string. This is solved by testing the key for existence and type. In case 'script' is not a key or refers to a type other than a string, a clear error is given, stating for example: 'Loading naming.json failed. script must be set to a string value.' The message is kept in line with other messages. Maybe it can be clarified further, e.g. 'Loading naming.json failed. A key "script" must be set with a string value referring to a Python script.' - in which case the errors relating to other keys may also be clarified. --- lib/addoninfo.cpp | 5 +++++ test/cli/test-other.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/lib/addoninfo.cpp b/lib/addoninfo.cpp index cfe720b81..c96543f75 100644 --- a/lib/addoninfo.cpp +++ b/lib/addoninfo.cpp @@ -87,6 +87,11 @@ static std::string parseAddonInfo(AddonInfo& addoninfo, const picojson::value &j return ""; } + if (!obj.count("script") || !obj["script"].is()) + { + return "Loading " + fileName + " failed. script must be set to a string value."; + } + return addoninfo.getAddonInfo(obj["script"].get(), exename); } diff --git a/test/cli/test-other.py b/test/cli/test-other.py index 819f1d6a6..a183161fc 100644 --- a/test/cli/test-other.py +++ b/test/cli/test-other.py @@ -278,6 +278,22 @@ extern const char* f() assert stderr == '{}:4:12: warning: strerror is MT-unsafe [threadsafety-unsafe-call]\n'.format(test_file) +def test_addon_invalidjson(tmpdir): + addon_file = os.path.join(tmpdir, 'invalid.json') + with open(addon_file, 'wt') as f: + f.write(""" +{ + "Script": "addons/something.py" +} + """) + + args = ['--addon={}'.format(addon_file), '--enable=all', 'nonexistent.cpp'] + + exitcode, stdout, stderr = cppcheck(args) + assert exitcode != 0 + assert stdout == 'Loading {} failed. script must be set to a string value.\n'.format(addon_file) + + def test_addon_naming(tmpdir): # the addon does nothing without a config addon_file = os.path.join(tmpdir, 'naming1.json')