Django Public Contact Form Hardening – Honeypot and Rate Limiting

Django AppSec

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:

  1. Inserted a new row into the Contact table in PostgreSQL/SQLite.
  2. Opened a synchronous TLS SMTP connection (smtp.gmail.com:587) via send_mail() to notify EMAIL_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 ContactsListView with SEO spam and phishing links.
  • Team inbox fatigue: Flooding EMAIL_USERS_TO_NOTIFY conditions 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 like honeypot or bot_trap are skipped by smarter bots.
  • Why autocomplete="off", tabindex="-1", and aria-hidden="true"? The hidden wrapper (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 returning 400 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_ADDR is the proxy's internal IP, so keying on it would put every visitor on one shared counter. The view reads X-Real-IP, which nginx-proxy always sets to the address it received the connection from. X-Forwarded-For is not used: with nginx-proxy's default TRUST_DOWNSTREAM_PROXY=true it 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 and cache.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 of POST handling—before form validation, the honeypot check, database writes, or send_mail(). A bot triggering the honeypot still consumes its IP quota and receives HTTP 429 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 1 Contact record, calls send_mail() once, and redirects to /contact/thanks/.
  • test_honeypot_blocks_spam_silently: submission with website populated redirects to /contact/thanks/ while Contact.objects.count() remains 0 and send_mail() is not called.
  • test_rate_limit_blocks_excessive_submissions: 5 submissions from the same IP succeed, and the 6th returns HTTP 429 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 same X-Real-IP and a different forged first X-Forwarded-For entry each time; the 6th still returns 429.
  • test_rate_limit_is_per_client_ip: after one IP uses its 5 submissions, another X-Real-IP can 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_mail raises SMTPAuthenticationError; the contact is still saved, the error is logged at ERROR, and no message shown to the visitor contains the SMTP error.

All 7 tests pass (python manage.py test apps.crm).

References

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.