Skip to main content
coreydaley.dev

The bounce you never tested: forcing delivery failures in MessagePit

Every app that sends SMS or email has a delivery-callback handler. Twilio posts status changes to it. SendGrid posts events to it. And in most codebases I’ve looked at, that handler has only ever seen one value in development: delivered.

That’s not because the developers were careless. It’s because the failure branches are hard to reach. You can’t make a real handset unreachable on cue. You can’t make SendGrid block, drop, or defer a message on cue either, and bouncing real mail to test a handler costs you sender reputation. So the code that handles undelivered, bounce, and dropped gets written once, from the docs, and then runs for the first time in production at 2 a.m.

When I first wrote about MessagePit, it caught Twilio SMS on localhost and fired a single signed callback per message. SendGrid-style email events worked the same way: one delivered event, and only for messages that carried a notification_id. Same gap, just moved to my laptop.

Today I closed it. MessagePit is a test environment and nothing else, so it can afford to lie on purpose: a bounce on demand, an undelivered SMS on demand, signed with the same schemes production uses.

What Changed

Delivery callbacks now replay the whole progression instead of a single terminal event. For SMS that’s queued → sent → delivered, one signed POST per state change. For email it’s SendGrid’s event lifecycle, processed → delivered by default. Both can be pushed down a failure branch on demand, and both can be slowed down with a delay flag so the timing looks like production.

It’s on main and listed under Unreleased in the changelog. The latest release, v1.3.0, still sends the single callback. It’ll ship in the next release; if you want it today, build from source with make run (Go and Node required).

Forcing an Undelivered SMS

Twilio’s test credentials recognize a handful of magic numbers in the +1500555xxxx range, and MessagePit now honors them with the real API error codes. Send to +15005550001 and you get an HTTP 400 with error 21211, nothing is stored, and no callback fires. That covers your send-side error handling.

The delivery failures are MessagePit’s own, in the same range:

To numberProgressionErrorCodeMeaning
+15005550010queued → failed30008Unknown error
+15005550011queued → sent → undelivered30003Unreachable handset
+15005550012queued → sent → undelivered30005Unknown handset
+15005550013queued → sent → undelivered30006Landline or unreachable carrier
+15005550014queued → sentnoneCarrier never confirms

failed means the message never left; undelivered means it was handed to the carrier and rejected downstream. Those are different branches in your code, so they’re different numbers here. To be clear, 0010 through 0014 are a MessagePit convention. Real Twilio won’t do this with them. Matching is on digits only, so +1 (500) 555-0011 resolves the same as +15005550011.

Start MessagePit with a callback URL and an auth token:

MP_TWILIO_WEBHOOK_URL=http://localhost:3000/webhooks/twilio \
MP_TWILIO_AUTH_TOKEN=test_auth_token \
MP_TWILIO_CALLBACK_DELAY=750ms \
make run

A per-request StatusCallback overrides MP_TWILIO_WEBHOOK_URL, just as it does with Twilio. Now send to an unreachable handset:

curl -s -u ACtest:test_auth_token \
  http://localhost:8200/2010-04-01/Accounts/ACtest/Messages.json \
  --data-urlencode "From=+15555550100" \
  --data-urlencode "To=+15005550011" \
  --data-urlencode "Body=Your code is 123456"

The API response says "status": "queued", just as real Twilio’s does. Then your handler receives three signed posts, queued, sent, and finally undelivered with ErrorCode=30003 and an ErrorMessage. Each carries the core fields Twilio sends: MessageSid/SmsSid, MessageStatus/SmsStatus, To, From, AccountSid, and ApiVersion. The SMS docs have the full field table and the rejection numbers.

Forcing a Bounce

SendGrid’s side works by scenario. Pick one with an mp_scenario custom arg, or by addressing the recipient with a matching local part or plus-tag, like bounce@example.com or user+bounce@example.com. An explicit mp_scenario wins over the address. Set MP_EMAIL_WEBHOOK_URL to your handler, then:

curl -s http://localhost:8100/v3/mail/send \
  -H "Content-Type: application/json" \
  -d '{
    "personalizations": [{ "to": [{ "email": "user@example.com" }] }],
    "from": { "email": "app@example.com" },
    "subject": "Welcome",
    "content": [{ "type": "text/plain", "value": "Hello" }],
    "custom_args": { "notification_id": "42", "mp_scenario": "bounce" }
  }'

Your handler receives processed, then bounce with type, status, reason, and bounce_classification. There are eleven scenarios in all: delivered, open, click, deferred, bounce, blocked, dropped, spamreport, unsubscribe, group_unsubscribe, and group_resubscribe. The SendGrid docs list each event sequence. --email-webhook-event-delay (MP_EMAIL_WEBHOOK_EVENT_DELAY) spaces the events out.

Every key in custom_args is now flattened onto each event as a top-level field, the way SendGrid does it, so notification_id keeps working.

One behavior change deserves its own line. Events now fire for every captured message, including mail sent over SMTP, because that’s what SendGrid does. Handlers that assumed notification_id was always present need to guard for its absence.

The Bugs This Shakes Loose

Here’s what I expect people to find once their handlers see something other than delivered.

The handler that assumes a terminal state always arrives. +15005550014 stalls at sent. If your UI shows “sending…” until a callback says otherwise, it now shows it forever. That’s a real production state, and you need a timeout or a reconciliation job for it.

The callback that beats your own database write. MessagePit starts the progression before it returns the API response. With no delay, the queued callback can land before your app has saved the MessageSid it just got back. A lookup by SID returns nothing, the handler shrugs, and the status is lost. The delay flag makes the timing realistic, but run it at zero once to see whether your code survives.

The handler that treats deferred as failure. The deferred scenario replays processed → deferred → delivered. If your handler marks the message failed on deferred and ignores anything after a “terminal” state, it stays failed after delivered arrives.

The suppression list that’s too eager. bounce and blocked both produce a bounce event, distinguished by type: bounce with status 5.1.1, blocked with 5.7.1. Suppress the address on any bounce, and you’ll suppress a perfectly valid address because a receiving server didn’t like your reputation that day.

One more that MessagePit won’t trigger: it delivers each progression in order, once. Production providers don’t promise that, so a late sent can still clobber undelivered if you store whatever arrived last. Write that test yourself, and dedupe email events on sg_event_id, which is unique per event.

Verifying the Signatures

Both providers sign their callbacks, and MessagePit signs every callback in every progression.

Twilio uses HMAC-SHA1 with your auth token over the exact callback URL plus the sorted POST parameters, sent as X-Twilio-Signature. Your SDK’s request validator handles that. The common failure is the URL: if your app sits behind a proxy that rewrites the scheme or port, the URL it reconstructs no longer matches the one that was signed. MessagePit won’t catch that unless your local setup uses the same proxy, but it will catch a validator that was never wired up, because a broken one now fails three times per message instead of once.

SendGrid uses ECDSA P-256 over SHA-256. The signed payload is the X-Twilio-Email-Event-Webhook-Timestamp header concatenated with the raw request body, and the signature is in X-Twilio-Email-Event-Webhook-Signature. Without a configured key MessagePit generates one at startup and logs the public half, which changes on every restart. For a stable one, generate a throwaway test key and derive its public half:

# Private key (SEC1 DER, base64), for MessagePit
export MP_EMAIL_WEBHOOK_SIGNING_KEY="$(openssl ecparam -name prime256v1 -genkey -noout \
  | openssl ec -outform DER 2>/dev/null | base64 | tr -d '\n')"

# Matching public key (PKIX DER, base64), for your app
echo "$MP_EMAIL_WEBHOOK_SIGNING_KEY" | base64 -d \
  | openssl ec -inform DER -pubout -outform DER 2>/dev/null | base64 | tr -d '\n'

The second command has to read the key you already made. Pipe a fresh -genkey into it instead and you get the public half of a different key, and every signature check fails. The key pair setup section of the docs has the same commands.

Then verify against the raw bytes. In Go:

func verifySendGrid(pub *ecdsa.PublicKey, w http.ResponseWriter, r *http.Request) ([]byte, error) {
    body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
    if err != nil {
        return nil, err
    }
    ts := r.Header.Get("X-Twilio-Email-Event-Webhook-Timestamp")
    sig, err := base64.StdEncoding.DecodeString(
        r.Header.Get("X-Twilio-Email-Event-Webhook-Signature"))
    if err != nil {
        return nil, err
    }
    hash := sha256.Sum256(append([]byte(ts), body...))
    if !ecdsa.VerifyASN1(pub, hash[:], sig) {
        return nil, errors.New("invalid signature")
    }
    sec, err := strconv.ParseInt(ts, 10, 64)
    if err != nil || time.Since(time.Unix(sec, 0)).Abs() > 5*time.Minute {
        return nil, errors.New("stale timestamp")
    }
    return body, nil // decode this, not r.Body
}

The classic bug here is verifying a body that was parsed and re-serialized. If your framework hands you decoded JSON before your verifier runs, re-encoding it can change a space or the key order, and a signature that was valid on the wire fails in your code. Read the raw body, verify it, then decode. The timestamp check is there because SendGrid sends the timestamp precisely so you can reject replayed events.

Run the Branch Before Production Does

Twilio and SendGrid give you good tools for the happy path and very little for the rest. That’s reasonable from their side: they can’t bounce a real message just because you asked. But it means the most consequential branches of your notification code are the least exercised ones. The fix is to make those branches boring: run them locally, with real signatures, until they stop surprising you.

The project page has everything else.

Which failure branch in your notification code has never run, and what would break first if it did?

Related posts