Skip to content

Instantly share code, notes, and snippets.

@mcsee
Last active December 15, 2025 16:04
Show Gist options
  • Select an option

  • Save mcsee/fbd378352df69bdab3043ad2687300e7 to your computer and use it in GitHub Desktop.

Select an option

Save mcsee/fbd378352df69bdab3043ad2687300e7 to your computer and use it in GitHub Desktop.
This gist belongs to Clean Code Cookbook http://cleancodecookbook.com By Maximiliano Contieri http://maximilianocontieri.com
import unicodedata
def normalize_email(email):
# Convert to NFKC normalized form
normalized = unicodedata.normalize('NFKC', email)
# Ensure only ASCII characters
try:
normalized.encode('ascii')
except UnicodeEncodeError:
raise ValueError(
"Email contains non-ASCII characters."
)
return normalized.lower()
def reset_password(email_from_ui):
# DEFENSE 1: Normalize and validate input
try:
normalized_email = normalize_email(email_from_ui)
except ValueError:
# Reject non-ASCII emails immediately
return False
cursor.execute(
"SELECT * FROM users WHERE email = %s",
(normalized_email,)
)
user = cursor.fetchone()
if user:
# DEFENSE 2: NEVER trust UI data
# Always use the canonical email from the database
database_email = user['email']
send_reset_email(database_email)
# NOT: send_reset_email(email_from_ui)
# NOT: send_reset_email(normalized_email)
return True
return False
# Now the attack fails:
# Attacker sends: victim@gmàil.com
# Normalized to: rejected (non-ASCII)
# Even if it passed, email sent to: user['email']
# (the actual stored value, not attacker's input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment