Skip to content

Commit

Permalink
feat(utils): ✨ add cookie value sanitizer (hacktoolkit#423)
Browse files Browse the repository at this point in the history
## Description
- Adds `sanitize_cookie_value` utility function.

---------

Co-authored-by: Jonathan Tsai <[email protected]>
  • Loading branch information
goztrk and jontsai authored Apr 4, 2024
1 parent c7573de commit 9c99e29
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions utils/text/sanitizers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Python Standard Library Imports
import html
import re

# isort: off


def sanitize_cookie_value(value: str) -> str:
"""Sanitize Cookie Value
Sanitizes a cookie value by escaping HTML special characters and
removing non-alphanumeric characters, except for some safe ones like
hyphens and underscores.
Args:
- value (str): The cookie value to be sanitized.
Returns:
- str: The sanitized cookie value.
References:
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
- https://stackoverflow.com/a/1969339
"""
# Escape HTML special characters to prevent XSS
sanitized_value = html.escape(value)

# Further restrict to a safe set of characters
sanitized_value = re.sub(
r'[^a-zA-Z0-9-_!#$%&\'()*+-./:<=>?@[\]^_`{|}~]', '', sanitized_value
)
return sanitized_value

0 comments on commit 9c99e29

Please sign in to comment.