Skip to content

Sanitize sensitive variables in RequestPanel #2105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Prev Previous commit
Next Next commit
Refactor sanitize_and_sort_request_vars
- Use helper functions to refactor ugly-looking code
  • Loading branch information
dr-rompecabezas committed Mar 13, 2025
commit 0100833bc4bf2501ac0d2ecc64024e904c90d853
48 changes: 34 additions & 14 deletions debug_toolbar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,27 +228,47 @@ def sanitize_and_sort_request_vars(
return {"raw": variable}

try:
try:
keys = sorted(variable)
except TypeError:
keys = list(variable)

# Get sorted keys if possible, otherwise just list them
keys = _get_sorted_keys(variable)

# Process the variable based on its type
if isinstance(variable, QueryDict):
result = []
for k in keys:
values = variable.getlist(k)
# Return single value if there's only one, otherwise keep as list
value = values[0] if len(values) == 1 else values
result.append((k, safe_filter.cleanse_setting(k, value)))
result = _process_query_dict(variable, keys)
else:
result = [
(k, safe_filter.cleanse_setting(k, variable.get(k))) for k in keys
]
result = _process_dict(variable, keys)

return {"list": result}
except TypeError:
# If any processing fails, return raw variable
return {"raw": variable}


def _get_sorted_keys(variable):
"""Helper function to get sorted keys if possible."""
try:
return sorted(variable)
except TypeError:
return list(variable)


def _process_query_dict(query_dict, keys):
"""Process a QueryDict into a list of (key, sanitized_value) tuples."""
result = []
for k in keys:
values = query_dict.getlist(k)
# Return single value if there's only one, otherwise keep as list
value = values[0] if len(values) == 1 else values
result.append((k, safe_filter.cleanse_setting(k, value)))
return result


def _process_dict(dictionary, keys):
"""Process a dictionary into a list of (key, sanitized_value) tuples."""
return [
(k, safe_filter.cleanse_setting(k, dictionary.get(k))) for k in keys
]


def get_stack(context=1) -> list[stubs.InspectStack]:
"""
Get a list of records for a frame and all higher (calling) frames.
Expand Down