Skip to content

Commit

Permalink
Enhance find_json garbage filtering (bsc#1231605) (#688)
Browse files Browse the repository at this point in the history
* Enhance find_json garbage filtering

* Enhance error handling in transactional_update module
  • Loading branch information
m-czernek authored Jan 23, 2025
1 parent 609a9fb commit a9505da
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion salt/modules/transactional_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -984,7 +984,7 @@ def call(function, *args, **kwargs):
return local.get("return", local)
else:
return local
except ValueError:
except (ValueError, AttributeError):
return {"result": False, "retcode": 1, "comment": ret_stdout}
finally:
# Check if reboot is needed
Expand Down
12 changes: 10 additions & 2 deletions salt/utils/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def find_json(raw):
# Search for possible starts end ends of the json fragments
for ind, _ in enumerate(lines):
line = lines[ind].lstrip()
line = line[0] if line else line
if line == "{" or line == "[":
starts.append((ind, line))
if line == "}" or line == "]":
Expand All @@ -61,10 +62,17 @@ def find_json(raw):
working = "\n".join(lines[start : end + 1])
try:
ret = json.loads(working)
return ret
except ValueError:
continue
if ret:
pass
# Try filtering non-JSON text right after the last closing curly brace
end_str = lines[end].lstrip()[0]
working = "\n".join(lines[start : end]) + end_str
try:
ret = json.loads(working)
return ret
except ValueError:
continue

# Fall back to old implementation for backward compatibility
# excpecting json after the text
Expand Down
5 changes: 5 additions & 0 deletions tests/unit/utils/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ def test_find_json(self):
ret = salt.utils.json.find_json(garbage_prepend_json)
self.assertDictEqual(ret, expected_ret)

# Pre-pend garbage right after closing bracket of the JSON
garbage_prepend_json = "{}{}".format(test_sample_json.rstrip(), LOREM_IPSUM)
ret = salt.utils.json.find_json(garbage_prepend_json)
self.assertDictEqual(ret, expected_ret)

# Test to see if a ValueError is raised if no JSON is passed in
self.assertRaises(ValueError, salt.utils.json.find_json, LOREM_IPSUM)

Expand Down

0 comments on commit a9505da

Please sign in to comment.