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 <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa 2024-10-18 15:33:50 -07:00 committed by James Valleroy
parent 4bde5309c5
commit f456a58118
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
2 changed files with 16 additions and 1 deletions

View File

@ -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."""

View File

@ -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}?', '')