Skip to content

Commit 8643e2a

Browse files
authored
Merge pull request #1609 from openaustralia/feature/1608-pause-alerts-to-bounced-addresses
Pause alert emails to addresses that hard-bounce in Postal
2 parents a4813e1 + e07489d commit 8643e2a

26 files changed

Lines changed: 1160 additions & 3 deletions

‎GLOSSARY.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,24 @@ The email sent to a Watcher covering the Broken scrapers they watch, and the
128128
ones that have recovered.
129129
_Avoid_: notification, digest, warning
130130

131+
**Hard bounce**:
132+
A permanent delivery failure that Postal reports for an Alert and that says the
133+
email address itself is bad. Postal's reports of a refusal that blames
134+
morph.io's sending server (a reply starting 5.7.x), of retries running out, or
135+
of a message it no longer held are not hard bounces. Soft bounces are not
136+
tracked, because Postal's own retries are the threshold.
137+
_Avoid_: bounce, failure
138+
139+
**Email suppression**:
140+
The record that Alerts are no longer sent to an email address because it hard
141+
bounced. It belongs to the address, not to a User, so a User who changes their
142+
GitHub primary email is no longer affected and their Watches are untouched.
143+
Staff lift a suppression by hand, and a later hard bounce suppresses the address
144+
again. Not Postal's own per-mail-server "Suppression list", which the
145+
infrastructure repository's glossary defines and morph.io neither reads nor
146+
writes.
147+
_Avoid_: bounce list, blocklist, unsubscribe
148+
131149
### Traffic
132150

133151
**Domain**:

‎app/controllers/owners_controller.rb‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ def show
1616
# Only do this once
1717
session[:new_supporter] = false if @new_supporter
1818

19+
# Only the person themself sees this, because it says something about their email address
20+
suppression = T.must(current_user).email_suppression if @owner == current_user
21+
@email_suppression = T.let(suppression, T.nilable(EmailSuppression))
22+
1923
scrapers = Scraper.accessible_by(current_ability).where(owner: @owner)
2024
@scrapers = T.let(scrapers, T.nilable(ActiveRecord::Relation))
2125

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# typed: strict
2+
# frozen_string_literal: true
3+
4+
require "csv"
5+
6+
# One-off clean-up that suppresses addresses Postal has already hard-failed, so the damage stops before the webhook is
7+
# switched on. Applies the same rule as the webhook (PostalWebhook::BounceRule), and additionally skips rows with no
8+
# reply from the receiving server, because a failure with no reply (for example Postal's own outbound spam check) says
9+
# nothing about the address.
10+
#
11+
# The input is a CSV export from the Postal server's history with a header row. Columns (names are case-insensitive):
12+
# address (or rcpt_to) the recipient
13+
# output (or reply) the receiving server's reply, exactly as Postal stored it
14+
# date (or timestamp) optional, when the most recent hard fail happened
15+
#
16+
# The export must hold hard failures only: this doesn't check the event, so a row for mail that was delivered, or that
17+
# soft-failed, would suppress a working address.
18+
#
19+
# The file is real personal data: keep it out of the repository (tmp/ is ignored), issues, chat and AI conversations.
20+
# Safe to run twice. Returns counts only so the output can be shared without exposing an address.
21+
#
22+
# Adapted from They Vote for You's EmailSuppressionImport (openaustralia/theyvoteforyou, same licence).
23+
class EmailSuppressionImport
24+
extend T::Sig
25+
26+
# Raised, with column names only, when the file doesn't have the columns we need. Better than counting every row as
27+
# missing data, which would look like a successful run that did nothing.
28+
class MissingColumns < StandardError; end
29+
30+
ADDRESS_COLUMNS = T.let(%w[address rcpt_to].freeze, T::Array[String])
31+
REPLY_COLUMNS = T.let(%w[output reply].freeze, T::Array[String])
32+
DATE_COLUMNS = T.let(%w[date timestamp].freeze, T::Array[String])
33+
34+
OUTCOMES = T.let(%i[suppressed already_suppressed skipped_failed_before_a_lift skipped_refusal_blaming_our_server
35+
skipped_no_reply skipped_no_address].freeze, T::Array[Symbol])
36+
37+
sig { params(path: String).returns(T::Hash[Symbol, Integer]) }
38+
def self.call(path)
39+
new.call(path)
40+
end
41+
42+
sig { params(path: String).returns(T::Hash[Symbol, Integer]) }
43+
def call(path)
44+
check_columns!(path)
45+
counts = OUTCOMES.index_with { 0 }
46+
CSV.foreach(path, encoding: "bom|utf-8", headers: true, header_converters: ->(header) { normalise_header(header) }) do |row|
47+
outcome = outcome_for(row)
48+
counts[outcome] = T.must(counts[outcome]) + 1
49+
end
50+
counts
51+
end
52+
53+
private
54+
55+
sig { params(header: T.untyped).returns(String) }
56+
def normalise_header(header)
57+
header.to_s.strip.downcase
58+
end
59+
60+
sig { params(path: String).void }
61+
def check_columns!(path)
62+
headers = (CSV.parse_line(File.open(path, encoding: "bom|utf-8", &:gets).to_s) || []).map { |header| normalise_header(header) }
63+
return if (headers & ADDRESS_COLUMNS).any? && (headers & REPLY_COLUMNS).any?
64+
65+
raise MissingColumns, "The file needs a header row with a column named #{ADDRESS_COLUMNS.join(' or ')} " \
66+
"and a column named #{REPLY_COLUMNS.join(' or ')}"
67+
end
68+
69+
sig { params(row: CSV::Row).returns(Symbol) }
70+
def outcome_for(row)
71+
address = row["address"] || row["rcpt_to"]
72+
reply = row["output"] || row["reply"]
73+
return :skipped_no_address if EmailSuppression.normalise(address).blank?
74+
return :skipped_no_reply if reply.blank?
75+
return :skipped_refusal_blaming_our_server if PostalWebhook::BounceRule.blames_sender?(reply)
76+
return :already_suppressed if EmailSuppression.suppressed?(address)
77+
78+
failed_at = failed_at(row)
79+
return :skipped_failed_before_a_lift if recovered_since?(address, failed_at)
80+
81+
EmailSuppression.suppress!(address, reason: :imported_from_postal, reply: reply, at: failed_at || Time.zone.now)
82+
:suppressed
83+
end
84+
85+
# When the most recent hard fail happened, so a person's notice says since when their emails have been returning.
86+
# Nil if the file has no usable date.
87+
sig { params(row: CSV::Row).returns(T.nilable(ActiveSupport::TimeWithZone)) }
88+
def failed_at(row)
89+
Time.zone.parse(row.values_at(*DATE_COLUMNS).find(&:present?).to_s)
90+
rescue ArgumentError
91+
nil
92+
end
93+
94+
# An address someone has since proved works again (a lift) must not be suppressed again by an old export. Without a
95+
# date we can't tell whether the failure was before or after, so we leave it alone.
96+
sig { params(address: String, failed_at: T.nilable(ActiveSupport::TimeWithZone)).returns(T::Boolean) }
97+
def recovered_since?(address, failed_at)
98+
lifted_at = EmailSuppression.last_lifted_at(address)
99+
!lifted_at.nil? && (failed_at.nil? || failed_at <= lifted_at)
100+
end
101+
end

‎app/lib/postal_webhook.rb‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# typed: strict
2+
# frozen_string_literal: true
3+
4+
# Handling of Postal's delivery webhooks: PostalController receives them, SigningKeys checks the signature and BounceRule
5+
# decides which failures say the address is bad.
6+
module PostalWebhook
7+
# The only mail we tag, set in AlertMailer. Discourse mail from the same mail server is untagged.
8+
ALERT_TAG = "alert"
9+
end
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# typed: strict
2+
# frozen_string_literal: true
3+
4+
module PostalWebhook
5+
# Decides whether a permanent delivery failure says anything about the recipient's address. Shared by the webhook and
6+
# the one-off import of past failures, so the two can't drift apart. Same rule as Planning Alerts.
7+
module BounceRule
8+
extend T::Sig
9+
10+
# The receiving server's reply starts with a 5.7.x enhanced status code when it has refused us for a policy or
11+
# reputation reason, such as a block on our sending IP address. https://www.rfc-editor.org/rfc/rfc3463
12+
SENDER_SIDE_REFUSAL = T.let(/\A\s*\d{3}[ -]5\.7\.\d+/, Regexp)
13+
14+
# Postal reports a hard fail with no reply when it runs out of retries after temporary failures.
15+
RETRIES_EXHAUSTED = T.let(/\AMaximum number of delivery attempts/, Regexp)
16+
17+
# Postal also hard fails when it can't send a held message because it has already deleted the stored copy.
18+
RAW_MESSAGE_REMOVED = T.let(/\ARaw message has been removed/, Regexp)
19+
20+
sig { params(reply: T.nilable(String)).returns(T::Boolean) }
21+
def self.blames_sender?(reply)
22+
SENDER_SIDE_REFUSAL.match?(reply.to_s)
23+
end
24+
25+
# Whether a MessageDeliveryFailed event says the address itself is bad. Only a reply from the receiving server can
26+
# say that, so a failure with none (for example Postal's own outbound spam check) never does.
27+
sig { params(details: T.nilable(String), output: T.nilable(String)).returns(T::Boolean) }
28+
def self.address_failed?(details:, output:)
29+
return false if output.blank?
30+
return false if RETRIES_EXHAUSTED.match?(details.to_s) || RAW_MESSAGE_REMOVED.match?(details.to_s)
31+
32+
!blames_sender?(output)
33+
end
34+
end
35+
end
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# typed: strict
2+
# frozen_string_literal: true
3+
4+
module PostalWebhook
5+
# The public keys Postal publishes for the key it signs webhooks with. Postal signs with one installation-wide key and
6+
# publishes the matching public key as a JWK Set at a well-known address, so we check against whatever it publishes
7+
# now rather than holding a copy. A key rotation on the Postal server then needs no change here.
8+
# https://docs.postalserver.io/developer/webhooks and https://www.rfc-editor.org/rfc/rfc7517
9+
#
10+
# Adapted from Planning Alerts' PostalSigningKeysService (openaustralia/planningalerts, same licence), using Net::HTTP
11+
# and building the RSA key by hand so morph needs no new gem.
12+
class SigningKeys
13+
extend T::Sig
14+
15+
class FetchError < StandardError; end
16+
17+
# Postal gives up on a webhook after 5 seconds and this runs inside that request, so a slower fetch is no use.
18+
HTTP_TIMEOUT = 2
19+
20+
# Bump the version to expire every cached copy.
21+
CACHE_KEY = "postal_webhook/signing_keys/v1"
22+
23+
# Long enough that a burst of webhooks isn't a fetch each, short enough that a key rotation heals within a
24+
# quarter of an hour.
25+
# Events signed with a new key in that window get 403 and are lost, as in Planning Alerts. Failures are cached
26+
# too, deliberately: that is what stops an outage becoming one outbound request per inbound webhook on an endpoint
27+
# anyone can post to.
28+
CACHE_TTL = T.let(15.minutes, ActiveSupport::Duration)
29+
30+
# While one request refreshes an expired entry, others keep getting the stale copy instead of fetching.
31+
RACE_CONDITION_TTL = T.let(5.seconds, ActiveSupport::Duration)
32+
33+
# Returns the RSA public keys, or nil if they can't be determined.
34+
sig { returns(T.nilable(T::Array[OpenSSL::PKey::RSA])) }
35+
def self.call
36+
pems = Rails.cache.fetch(CACHE_KEY, expires_in: CACHE_TTL, race_condition_ttl: RACE_CONDITION_TTL) { fetch_pems }
37+
pems&.map { |pem| OpenSSL::PKey::RSA.new(pem) }
38+
end
39+
40+
# PEM strings rather than key objects, because the production cache is memcached and what we store has to survive
41+
# Marshal. Network failures and a malformed body degrade to nil ("can't check this signature") rather than a 500,
42+
# and are reported to Sentry, at most once per CACHE_TTL because the result is cached.
43+
sig { returns(T.nilable(T::Array[String])) }
44+
def self.fetch_pems
45+
uri = URI.parse(Rails.configuration.x.postal_jwks_url)
46+
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
47+
open_timeout: HTTP_TIMEOUT, read_timeout: HTTP_TIMEOUT) do |http|
48+
http.get(uri.request_uri)
49+
end
50+
return report_failure("HTTP status #{response.code}") unless response.code == "200"
51+
52+
parsed = JSON.parse(response.body.to_s)
53+
keys = parsed["keys"] if parsed.is_a?(Hash)
54+
return report_failure("body has no keys list") unless keys.is_a?(Array)
55+
56+
keys.filter_map { |jwk| signing_pem(jwk) }.presence || report_failure("no usable RSA signing key")
57+
rescue Timeout::Error, SocketError, SystemCallError, EOFError, Net::ProtocolError, Net::HTTPBadResponse,
58+
Net::HTTPHeaderSyntaxError, JSON::ParserError, TypeError, ArgumentError, OpenSSL::OpenSSLError => e
59+
report_failure("#{e.class}: #{e.message}")
60+
end
61+
62+
# The message is fixed and the reason goes in extra, so one outage groups as one Sentry issue.
63+
sig { params(reason: String).returns(NilClass) }
64+
def self.report_failure(reason)
65+
Sentry.capture_exception(
66+
FetchError.new("Could not fetch Postal's webhook signing keys, so bounce processing is paused"),
67+
extra: { jwks_url: Rails.configuration.x.postal_jwks_url, reason: reason }
68+
)
69+
nil
70+
end
71+
72+
# Only RSA keys marked for signatures, or with no usage stated ("use" is optional in RFC 7517). Never encryption keys.
73+
sig { params(jwk: T.untyped).returns(T.nilable(String)) }
74+
def self.signing_pem(jwk)
75+
return unless jwk.is_a?(Hash) && jwk["kty"] == "RSA" && [nil, "sig"].include?(jwk["use"])
76+
return unless jwk["n"].is_a?(String) && jwk["e"].is_a?(String)
77+
78+
modulus = OpenSSL::BN.new(Base64.urlsafe_decode64(jwk["n"]), 2)
79+
exponent = OpenSSL::BN.new(Base64.urlsafe_decode64(jwk["e"]), 2)
80+
sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer(modulus), OpenSSL::ASN1::Integer(exponent)])
81+
OpenSSL::PKey::RSA.new(sequence.to_der).to_pem
82+
end
83+
private_class_method :fetch_pems, :report_failure, :signing_pem
84+
end
85+
end

‎app/mailers/alert_mailer.rb‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ def alert_email(user, broken_scrapers, successful_scrapers)
2323
attachments.inline["logo_75x75.png"] = File.read(path)
2424
return if user.email.nil?
2525

26-
mail(to: "#{user.name} <#{user.email}>", subject: @subject)
26+
# Postal passes the tag back in its delivery webhooks, and PostalController only acts on this one
27+
mail(to: "#{user.name} <#{user.email}>", subject: @subject, "X-Postal-Tag" => PostalWebhook::ALERT_TAG)
2728
user.update(alerted_at: Time.current)
2829
end
2930
end

0 commit comments

Comments
 (0)