From f456a58118a793c8084caa60b032bee4391010d3 Mon Sep 17 00:00:00 2001 From: Sunil Mohan Adapa Date: Fri, 18 Oct 2024 15:33:50 -0700 Subject: [PATCH] utils: Improve safe formatter by handling more cases Fixes: #2462. - When there are field retrievals and subscript based retrievals in the format string, exceptions are raised. Handle these safely. - This eliminates are error such as "Notification missing required key during translation: 'str' object has no attribute 'php");print($CONFIG'". when the notification message contains "{include_once("/var/www/html/config/config.php");print($CONFIG["dbpassword"] ?? ""); }" Tests: - Updated unit tests pass. Signed-off-by: Sunil Mohan Adapa Reviewed-by: James Valleroy --- plinth/tests/test_utils.py | 8 ++++++++ plinth/utils.py | 9 ++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/plinth/tests/test_utils.py b/plinth/tests/test_utils.py index 0ad26c3b7..ac87f1624 100644 --- a/plinth/tests/test_utils.py +++ b/plinth/tests/test_utils.py @@ -149,6 +149,14 @@ class TestYAMLFileUtil: 'key1': 'value1' }), '20 10 value1'), (('{2} {1} {key1}', [10, 20], {}), '?2? 20 ?key1?'), + (('{a[2]}', [], { + 'a': [1, 2, 3] + }), '3'), + (('{a[b]}', [], { + 'a': [] + }), '?a[b]?'), + (('{a["b"]}', [], {}), '?a["b"]?'), + (('{a.b}', [], {}), '?a.b?'), )) def test_safe_string_formatter(input_, output): """Test the safe string formatter.""" diff --git a/plinth/utils.py b/plinth/utils.py index 239da8b37..565dbc09f 100644 --- a/plinth/utils.py +++ b/plinth/utils.py @@ -180,8 +180,15 @@ class SafeFormatter(string.Formatter): """A string.format() handler to deal with missing arguments.""" def get_value(self, key, args, kwargs): - """Retrieve a given field value.""" + """Retrieve a given field's value: 0 or foo.""" try: return super().get_value(key, args, kwargs) except (IndexError, KeyError): return f'?{key}?' + + def get_field(self, field_name, args, kwargs): + """Retrieve a given field's value: 0[foo] or foo.bar.""" + try: + return super().get_field(field_name, args, kwargs) + except (AttributeError, TypeError): + return (f'?{field_name}?', '')