Skip to content

Commit 22b8d49

Browse files
committed
add sanitization to to_json output (#2287)
1 parent 1dfd092 commit 22b8d49

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

pygeoapi/util.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -261,8 +261,14 @@ def to_json(dict_: dict, pretty: bool = False) -> str:
261261
else:
262262
indent = None
263263

264-
return json.dumps(dict_, default=json_serial, indent=indent,
265-
separators=(',', ':'))
264+
LOGGER.debug('Dumping JSON')
265+
json_dump = json.dumps(dict_, default=json_serial, indent=indent,
266+
separators=(',', ':'))
267+
268+
LOGGER.debug('Removing < and >')
269+
json_dump = json_dump.replace('<', '&lt').replace('>', '&gt')
270+
271+
return json_dump
266272

267273

268274
def format_datetime(value: str, format_: str = DATETIME_FORMAT) -> str:

tests/other/test_util.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,17 @@ def test_get_typed_value():
7474
assert isinstance(value, bool)
7575

7676

77+
@pytest.mark.parametrize('data,minified,pretty_printed', [
78+
[{'foo': 'bar'}, '{"foo":"bar"}', '{\n "foo":"bar"\n}'],
79+
[{'foo<script>alert("hi")</script>': 'bar'},
80+
'{"foo&ltscript&gtalert(\\"hi\\")&lt/script&gt":"bar"}',
81+
'{\n "foo&ltscript&gtalert(\\"hi\\")&lt/script&gt":"bar"\n}']
82+
])
83+
def test_to_json(data, minified, pretty_printed):
84+
assert util.to_json(data) == minified
85+
assert util.to_json(data, pretty=True) == pretty_printed
86+
87+
7788
def test_yaml_load(config):
7889
assert isinstance(config, dict)
7990
with pytest.raises(FileNotFoundError):

0 commit comments

Comments
 (0)