|
| 1 | +# typed: strict |
| 2 | +# frozen_string_literal: true |
| 3 | + |
| 4 | +# Receives Postal's delivery webhooks and suppresses addresses that hard-bounce. Same route and rule as Planning Alerts. |
| 5 | +# https://docs.postalserver.io/developer/webhooks |
| 6 | +# |
| 7 | +# Not a browser, so there is no session or request forgery check. |
| 8 | +class PostalController < ActionController::API |
| 9 | + extend T::Sig |
| 10 | + |
| 11 | + HARD_FAILURE_EVENTS = T.let(%w[MessageDeliveryFailed MessageBounced].freeze, T::Array[String]) |
| 12 | + |
| 13 | + sig { void } |
| 14 | + def event |
| 15 | + failure = signature_failure_status(request.raw_post) |
| 16 | + return head failure if failure |
| 17 | + |
| 18 | + body = parse_body(request.raw_post) |
| 19 | + # A signed body we can't read won't improve on a retry, so don't ask Postal to send it again |
| 20 | + return head :ok if body.nil? |
| 21 | + |
| 22 | + event_name = body["event"] |
| 23 | + payload = body["payload"] |
| 24 | + # Delayed, held and every other event are accepted and ignored. Postal keeps retrying soft failures itself. |
| 25 | + return head :ok unless HARD_FAILURE_EVENTS.include?(event_name) && payload.is_a?(Hash) |
| 26 | + |
| 27 | + suppress_if_hard_bounce(T.cast(event_name, String), payload, event_time(body["timestamp"], payload["timestamp"])) |
| 28 | + head :ok |
| 29 | + end |
| 30 | + |
| 31 | + private |
| 32 | + |
| 33 | + sig { params(raw_post: String).returns(T.nilable(T::Hash[String, T.untyped])) } |
| 34 | + def parse_body(raw_post) |
| 35 | + parsed = JSON.parse(raw_post) |
| 36 | + parsed if parsed.is_a?(Hash) |
| 37 | + rescue JSON::ParserError |
| 38 | + nil |
| 39 | + end |
| 40 | + |
| 41 | + # When Postal says the event happened, which a retry of the event repeats. Status events carry it in the payload and |
| 42 | + # bounce reports in the webhook itself. Nil if it didn't say. |
| 43 | + sig { params(webhook_time: T.untyped, payload_time: T.untyped).returns(T.nilable(ActiveSupport::TimeWithZone)) } |
| 44 | + def event_time(webhook_time, payload_time) |
| 45 | + timestamp = [payload_time, webhook_time].find { |value| value.is_a?(Numeric) } |
| 46 | + Time.zone.at(timestamp) if timestamp |
| 47 | + end |
| 48 | + |
| 49 | + # A bounce report wraps the message that bounced in original_message. |
| 50 | + sig do |
| 51 | + params(event: String, payload: T::Hash[String, T.untyped], happened_at: T.nilable(ActiveSupport::TimeWithZone)).void |
| 52 | + end |
| 53 | + def suppress_if_hard_bounce(event, payload, happened_at) |
| 54 | + message = payload[event == "MessageBounced" ? "original_message" : "message"] |
| 55 | + recipient = message["to"] if message.is_a?(Hash) |
| 56 | + return log(event, "ignored: untagged") if EmailSuppression.normalise(recipient).blank? || message["tag"] != PostalWebhook::ALERT_TAG |
| 57 | + return log(event, "ignored: not about the address") if event == "MessageDeliveryFailed" && !address_failed?(payload) |
| 58 | + |
| 59 | + # Postal retries an event it didn't get a 200 for, possibly after staff have lifted the address. That says nothing |
| 60 | + # about the address now, so only a failure after the latest lift suppresses it again. |
| 61 | + return log(event, "ignored: before the address was last lifted") if lifted_since?(recipient, happened_at) |
| 62 | + |
| 63 | + EmailSuppression.suppress!(recipient, reason: :hard_bounce, postal_event: event, reply: payload["output"], |
| 64 | + at: happened_at || Time.zone.now) |
| 65 | + log(event, "suppressed") |
| 66 | + end |
| 67 | + |
| 68 | + sig { params(address: String, happened_at: T.nilable(ActiveSupport::TimeWithZone)).returns(T::Boolean) } |
| 69 | + def lifted_since?(address, happened_at) |
| 70 | + lifted_at = EmailSuppression.last_lifted_at(address) |
| 71 | + !happened_at.nil? && !lifted_at.nil? && happened_at <= lifted_at |
| 72 | + end |
| 73 | + |
| 74 | + sig { params(payload: T::Hash[String, T.untyped]).returns(T::Boolean) } |
| 75 | + def address_failed?(payload) |
| 76 | + PostalWebhook::BounceRule.address_failed?(details: payload["details"], output: payload["output"]) |
| 77 | + end |
| 78 | + |
| 79 | + # Event type and outcome only, never an address. |
| 80 | + sig { params(event: String, outcome: String).void } |
| 81 | + def log(event, outcome) |
| 82 | + Rails.logger.info("Postal #{event}: #{outcome}") |
| 83 | + end |
| 84 | + |
| 85 | + # X-Postal-Signature-256 holds a base64 RSA-SHA256 signature of the raw body, made with Postal's installation-wide |
| 86 | + # key. We check it against every key Postal currently publishes, so a rotation needs no change here. |
| 87 | + # |
| 88 | + # Returns nil when properly signed, otherwise the status to respond with. A bad signature gets 403 and the event is |
| 89 | + # gone for good. Being unable to reach the keys is different: we can't tell whether the request is genuine, so 503 |
| 90 | + # asks Postal to retry (about 36 minutes of backoffs) instead of dropping a real event. |
| 91 | + sig { params(raw_post: String).returns(T.nilable(Symbol)) } |
| 92 | + def signature_failure_status(raw_post) |
| 93 | + signature = request.headers["X-Postal-Signature-256"] |
| 94 | + # Checked before the keys are fetched, so an unsigned request costs no outbound request. |
| 95 | + return :forbidden if signature.blank? |
| 96 | + |
| 97 | + keys = PostalWebhook::SigningKeys.call |
| 98 | + return :service_unavailable if keys.nil? |
| 99 | + |
| 100 | + decoded = Base64.decode64(signature) |
| 101 | + digest = OpenSSL::Digest.new("SHA256") |
| 102 | + keys.any? { |key| key.verify(digest, decoded, raw_post) } ? nil : :forbidden |
| 103 | + end |
| 104 | +end |
0 commit comments