Django Public Contact Form Hardening – Honeypot and Rate Limiting
Goal
Harden the unauthenticated POST /contact/ endpoint (new_contact) in the Django CRM application against automated spam bots and high-volume submission floods, without introducing third-party CAPTCHA friction for legitimate visitors.
Setup
Before hardening, every valid POST request to /contact/ executed two expensive operations directly inside the synchronous request-response cycle:
- Inserted a new row into the
Contacttable in PostgreSQL/SQLite. - Opened a synchronous TLS SMTP connection (
smtp.gmail.com:587) viasend_mail()to notifyEMAIL_USERS_TO_NOTIFY.
Leaving this public endpoint without bot filtering or rate limiting created four operational and security risks (detailed in Unprotected Public Form Risks - Synchronous SMTP DoS and Quota Exhaustion):
- SMTP quota exhaustion and account suspension: Gmail and Google Workspace enforce strict daily (500–2,000 emails/day) and burst sending limits; a short automated flood can exhaust the quota or trigger Google to lock the account.
- Synchronous worker starvation (DoS): Each
send_mail()call blocks a Gunicorn worker for 300ms to 2+ seconds waiting on network I/O, allowing concurrent bot submissions to stall the entire web application. Production starts Gunicorn without-w, so it runs the default single sync worker: one slow SMTP call blocks the whole site. - CRM database pollution: Automated form scrapers fill
ContactsListViewwith SEO spam and phishing links. - Team inbox fatigue: Flooding
EMAIL_USERS_TO_NOTIFYconditions staff to ignore notification emails.
Deployment context that matters for the controls below: the app runs behind a shared nginx-proxy container (VIRTUAL_HOST / acme-companion) on the webproxy network, publishes no port of its own, and has no CACHES setting, so Django uses its default per-process LocMemCache.
Steps and findings
We implemented a two-layer defense-in-depth architecture backed by an automated test suite:
1. Layer 1: Hidden Honeypot Field (website)
To catch automated HTML form scrapers that populate every <input> tag in the DOM, we added an optional website field to ContactForm:
website = forms.CharField(
required=False,
widget=forms.TextInput(attrs={
"autocomplete": "off",
"tabindex": "-1",
"aria-hidden": "true",
}),
)
In contacts_new.html, the field is wrapped in a visually hidden container:
<div class="hidden" aria-hidden="true">
{{ form.website }}
</div>
In new_contact, any submission with a non-empty website value is silently rejected before touching the database or SMTP server:
# Checked on the raw POST data before validation, so a bot that also sends
# invalid data gets the same fake success instead of an error page.
if request.POST.get("website"):
return redirect("crm_contacts_thanks_path")
- Why name the field
website? Bots look for realistic field names (website,url,company) and fill them with spam URLs, whereas obvious names likehoneypotorbot_trapare skipped by smarter bots. - Why
autocomplete="off",tabindex="-1", andaria-hidden="true"? Thehiddenwrapper (display: none) already keeps the field out of the Tab order and the accessibility tree. The attributes are insurance if the stylesheet fails to load, so keyboard and screen-reader users can't reach the trap.autocomplete="off"is only a hint, which Chrome often ignores. - Why redirect to
/contact/thanks/instead of returning400 Bad Request? Returning an error signals to adaptive bots that their payload failed, prompting them to retry with optional fields left blank. Redirecting to the thank-you page convinces the bot its submission succeeded while zero rows are written and zero emails are sent.
2. Layer 2: Per-IP Rate Limiting via django.core.cache
Because a honeypot does not stop a human attacker or a targeted script tailored to the form, we added per-IP rate limiting (5 submissions per 3,600-second window) using Django's cache framework:
CONTACT_RATE_LIMIT = 5
CONTACT_RATE_LIMIT_TIMEOUT = 3600 # 1 hour in seconds
def _get_client_ip(request):
# nginx-proxy sets X-Real-IP to the address it received the connection from,
# overwriting any value the client sent. X-Forwarded-For is not used: nginx-proxy
# appends to the client's header, so its first entry can be forged.
return request.META.get("HTTP_X_REAL_IP", "").strip() or request.META.get(
"REMOTE_ADDR", "unknown"
)
- Reverse-proxy IP extraction: Behind nginx-proxy,
REMOTE_ADDRis the proxy's internal IP, so keying on it would put every visitor on one shared counter. The view readsX-Real-IP, which nginx-proxy always sets to the address it received the connection from.X-Forwarded-Foris not used: with nginx-proxy's defaultTRUST_DOWNSTREAM_PROXY=trueit appends to whatever the client sent, so its first entry can be forged. - Atomic fixed window:
cache.add(key, 0, timeout=3600)creates the counter only on the first submission andcache.incr(key)increments it, so later submissions don't extend the hour and concurrent requests can't overshoot. - Execution order: Rate-limit checking and counter increment (
contact_rate_limit:<ip>) run at the very start ofPOSThandling—before form validation, the honeypot check, database writes, orsend_mail(). A bot triggering the honeypot still consumes its IP quota and receives HTTP429 Too Many Requests("Trop de tentatives d'envoi. Veuillez réessayer plus tard.") on the 6th attempt. - Trade-off of that order: submissions that fail form validation (a mistyped email address) also count, so a legitimate visitor who makes several mistakes can be throttled before their message goes through.
Controls verified
We added three unit tests in NewContactViewTests (apps/crm/tests.py), mocking send_mail with unittest.mock.patch so the test suite never initiates real network SMTP connections:
-
test_valid_contact_submission_creates_contact: normal submission creates 1Contactrecord, callssend_mail()once, and redirects to/contact/thanks/. -
test_honeypot_blocks_spam_silently: submission withwebsitepopulated redirects to/contact/thanks/whileContact.objects.count()remains0andsend_mail()is not called. -
test_rate_limit_blocks_excessive_submissions: 5 submissions from the same IP succeed, and the 6th returns HTTP429 Too Many Requests, renders"Trop de tentatives", and creates no 6th record. -
test_forged_x_forwarded_for_does_not_reset_rate_limit: 6 submissions with the sameX-Real-IPand a different forged firstX-Forwarded-Forentry each time; the 6th still returns429. -
test_rate_limit_is_per_client_ip: after one IP uses its 5 submissions, anotherX-Real-IPcan still submit. -
test_honeypot_with_invalid_data_still_redirects_silently: honeypot filled and invalid email; redirects to/contact/thanks/with no record and no email. -
test_smtp_error_is_logged_not_shown_to_visitor:send_mailraisesSMTPAuthenticationError; the contact is still saved, the error is logged atERROR, and no message shown to the visitor contains the SMTP error.
All 7 tests pass (python manage.py test apps.crm).
References
- OWASP Automated Threats to Web Applications: OAT-017 Spamming - Classification of automated form spam and mitigation patterns.
- Django Documentation: Django's cache framework - Low-level
cache.get()andcache.set()API used for per-IP request counters. - RFC 6585 Section 4: 429 Too Many Requests - Standard HTTP status code for rate-limited client requests.
- MDN Web Docs: X-Forwarded-For - De-facto standard header for identifying the originating client IP address through a reverse proxy, and why its leftmost entry can't be trusted.
- nginx-proxy documentation -
TRUST_DOWNSTREAM_PROXYdefaults totrue, soX-Forwarded-Foris appended to rather than replaced; the default template setsX-Real-IP $remote_addr(last checked 2026-10-24). - Debugging Django Email with Gmail in a Dockerized App - Production Gmail SMTP setup (
smtp.gmail.com:587) used by the Django container.
Review cards
Flashcard Why can an unprotected public form that calls `send_mail()` synchronously cause an application-wide Denial of Service?
Opening a TLS connection to an external SMTP server takes 300ms to 2+ seconds per request. Concurrent bot submissions block all synchronous Gunicorn workers on network I/O, starving legitimate traffic across the entire site.
Flashcard Why should a triggered form honeypot redirect to the thank-you page (`302`) instead of returning `400 Bad Request`?
Returning an error tells adaptive bots that their submission failed, prompting them to retry with optional fields left blank. Redirecting to the thank-you page convinces the bot its spam succeeded while the server silently drops the database write and email.
Quiz When combining a form honeypot with per-IP rate limiting, in what order should the view evaluate them and why?
- Honeypot first, then rate limit, so bots don't write keys to the cache.
- Rate limit first, then honeypot, so bots hitting the honeypot still consume their IP quota and get throttled with HTTP 429.
- After
form.save(), so only valid records are counted.
Checking the rate limit before the honeypot ensures a bot flooding the form with honeypot payloads still exhausts its IP allowance after 5 attempts instead of hitting the view indefinitely.