Sub topic 7
Surviving security scanners and link prefetching
This chapter assumes you can read basic Python and SQL, know the difference between an HTTP GET and a POST request, and have a rough idea of how a confirmation token works from the previous chapter. The goal is to make sure that a program opening a link in an email cannot confirm or unsubscribe a person who never clicked it.
The problem: links get opened by machines
A double opt-in flow sends a link and treats the visit as proof that a human wanted to subscribe. That proof is only as good as the assumption that a human made the visit. Many systems open links in email before the recipient sees the message:
- Corporate security gateways fetch every URL in an incoming message to check for malware or phishing.
- Some mailbox providers and mail clients prefetch links or images to build previews or to protect the user.
- Link-rewriting products replace each URL with their own address, then visit the original target to classify it.
- Antivirus software on the recipient's device may follow links in a message it is scanning.
These tools are well-intentioned, and they usually send a plain GET request. They do not read the page, think about what it means, or press buttons. If your confirmation URL changes state on GET, the scanner confirms the subscription for the user. If your unsubscribe URL changes state on GET, the scanner unsubscribes the user.
Both outcomes cause real damage:
| Failure | What happens | Consequence |
|---|---|---|
| Scanner confirms a sign-up | An address becomes `confirmed` without the owner ever acting | Your consent record is false. The "proof" of double opt-in is worthless, and you may mail someone who did not ask. |
| Scanner unsubscribes a subscriber | A real subscriber silently disappears from the list | You lose an engaged reader and see unexplained unsubscribe spikes, often right after delivery to corporate domains. |
| Scanner hits a one-time link first | The token is marked used before the human arrives | The real person sees an "already used" or "expired" error. |
The last row is easy to miss. Making a token single-use does not protect you from scanners. It makes things worse, because the scanner consumes the token and the human is locked out.
The rule: GET reads, POST changes
HTTP defines GET as a safe method: a client may send it without intending to change anything on the server. Scanners rely on that promise. The fix is to honor it.
- The link in the email points to a page served on GET.
- That page verifies the token and shows a short message with a button, such as "Confirm my subscription".
- The button submits a form using POST. Only the POST handler changes the database.
A scanner that follows the link sees the page and stops, since it does not submit forms. A human clicks the button once and the state changes.
Implementing it
The code from the previous chapter already follows this pattern. The two handlers are shown again here so you can see which one is allowed to write.
from datetime import datetime, timezone
def show_confirmation_page(token: str):
"""Handle GET: only display a page with a Confirm button; change nothing."""
email = verify_token(token, "confirm")
if email is None:
return render("link_invalid_or_expired.html")
return render("confirm_button.html", token=token)
def confirm_subscription(db, token: str):
"""Handle POST: confirm the subscriber. Safe to call more than once."""
email = verify_token(token, "confirm")
if email is None:
return render("link_invalid_or_expired.html")
db.execute(
"UPDATE subscribers SET status = 'confirmed', confirmed_at = %s "
"WHERE email = %s AND status = 'pending'",
(datetime.now(timezone.utc), email),
)
return render("subscription_confirmed.html")Three details matter:
- The GET handler verifies the token but writes nothing. Verifying lets you show a useful error early. It must not log a consent event or update a timestamp.
- The POST handler verifies the token again. Never trust that the earlier GET happened or that the form was not edited. The token is the credential, so check it on every state-changing request.
- The
WHERE ... AND status = 'pending'clause makes the update idempotent. An operation is idempotent when running it twice has the same effect as running it once. A double click, a browser retry, or a reload of the result page does not overwriteconfirmed_atwith a later time. Without the clause, each retry would rewrite the timestamp and damage your audit trail.
The confirm_button.html template needs a form that posts back to the same URL or to a dedicated endpoint. In HTML terms, it needs method="post" and the token in the action URL or a hidden field. Keep the page free of JavaScript that submits the form automatically. An auto-submitting form defeats the purpose, because a scanner that renders JavaScript, which some do, would submit it.
Applying the same rule to unsubscribe
Unsubscribe links face the same risk, with a twist. Everyone agrees that unsubscribing should take as little effort as possible, and a confirmation page adds one more step. There are two sound ways to resolve this.
Option 1: a page with one button. The link opens a page that says "Unsubscribe [email protected] from this list?" with a single prominent button. This is one extra click, no login, and no questions. It is the safest pattern for links in the message body, and it is a natural place to offer a preference centre as an alternative.
Option 2: POST only for the machine path. The List-Unsubscribe header from a later chapter lets a mail client send a POST request directly when the user presses its built-in unsubscribe button. This is the one-click mechanism defined in RFC 8058. Because the request is a POST that the mail client sends on the user's explicit action, it is safe to act on immediately. Scanners do not send it.
Use both. The body link uses a confirmation page on GET and changes state on POST. The header uses POST only.
The cost of the extra click is small compared with the cost of silent unsubscribes. If you still prefer immediate GET unsubscribes, accept that scanner-triggered removals will occur. Treat the resulting list shrinkage as a known cost, not a mystery.
Defence in depth
The GET and POST split is the main defence. These measures add resilience.
- Keep tokens multi-use until expiry. A token that stays valid for its whole lifetime lets the human succeed after a scanner has visited. Rely on idempotent updates, not single-use tokens, to prevent harm.
- Bind tokens to a purpose. The
purposefield in the token means a confirmation token cannot unsubscribe anyone, and an unsubscribe token cannot confirm anyone. If a scanner or a leaked link exposes one token, the damage stays limited to that purpose. - Log the request method and user agent. Store them with each consent event. Some scanners identify themselves in the user agent, and an odd pattern, such as a confirmation recorded within one second of delivery, is a signal worth investigating.
- Do not bot-detect and silently ignore. User-agent filtering is unreliable. Scanners often use ordinary browser strings. Use it only as a diagnostic, never as the control that protects state.
- Consider a short delay check as a metric, not a gate. If many confirmations arrive within a second or two of sending, your flow is probably being triggered by software. Chapter 16 covers measuring this.
Common mistakes
- Putting the state change in the GET handler "just for convenience". This is the root cause of nearly every scanner incident.
- Using a redirect from GET to a POST-less state change. A GET that redirects to another GET that writes is still a GET write.
- Making the token single-use as a security measure. As explained above, this locks out real users after a scan.
- Testing only with a browser. A browser click always works. Test with a plain HTTP client that sends GET and never follows forms.
- Overwriting timestamps on repeat requests. This changes the evidence you may later need to show when consent was given.
Testing that scanners are harmless
You can simulate a scanner with a short test. It issues a GET to the confirmation URL and then checks that the subscriber is still pending.
def test_get_does_not_confirm(client, db):
token = make_token("[email protected]", "confirm")
response = client.get(f"/confirm/{token}")
assert response.status_code == 200
row = db.query_one(
"SELECT status FROM subscribers WHERE email = %s",
("[email protected]",),
)
assert row["status"] == "pending"
def test_post_confirms_once(client, db):
token = make_token("[email protected]", "confirm")
client.post(f"/confirm/{token}")
first = db.query_one(
"SELECT confirmed_at FROM subscribers WHERE email = %s",
("[email protected]",),
)
client.post(f"/confirm/{token}")
second = db.query_one(
"SELECT confirmed_at FROM subscribers WHERE email = %s",
("[email protected]",),
)
assert first["confirmed_at"] == second["confirmed_at"]The fixtures client and db are placeholders for your own test setup, and a subscriber row in the pending state must exist before each test. The first test fails if anyone adds a write to the GET handler. The second fails if the update loses its status = 'pending' guard.
Exercise
A subscriber on a corporate mail system reports that she never confirmed, yet your database shows her as confirmed 2 seconds after the email was delivered. Your confirmation handler changes the status on GET and the token is single-use. Name the most likely cause, and describe the change you would make so that this cannot recur.
Show answer
A security gateway at her employer most likely fetched the link with a GET request as part of scanning the message, which confirmed the subscription before she saw it. Change the flow so the GET request only verifies the token and shows a page with a Confirm button, and make a POST request from that button do the update. Keep the update idempotent with a status = 'pending' condition and stop invalidating the token on first use, so a real click still works after a scan. The record of her earlier "confirmation" should be treated as unreliable, so consider asking her to confirm again before mailing her.
Exercise
Why does making a confirmation token single-use fail to protect against scanners, and what protects you instead?
Show answer
The scanner uses the token first, so the real person later finds it already used and cannot confirm. Protection comes from separating GET from POST, because the scanner's GET changes nothing, and from making the POST update idempotent so repeated requests are harmless.