fix: correctly close SMTP message and await response #14495
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
We originally took heavy inspiration from Alertmanager's SMTP dispatch functionality due to the number of options we need to support.
In their dispatch code, they defer the call to
message.Close
but in fact this is necessary to complete the SMTP submission and await any errors; we do the same in our code.NOTE: We use
emersion/go-smtp
as our SMTP library while Alertmanager usesnet/smtp
, but the former extends the latter, so the code that follows is effectively the same.We cannot defer a call to
Close
because we depend on the error which is returned to determine if the message was successfully sent or not.This line checks if the response was successful (docs); if not, we need to fail this dispatch and mark it for retry.
I discovered this bug by incorrectly configuring
CODER_NOTIFICATIONS_EMAIL_FROM
as my@coder.com
address (which is backed by GSuite) and testing a dispatch via an outlook.com SMTP server. The server was rejecting the message with554 5.2.252 SendAsDenied; <redacted>@outlook.com not allowed to send as <redacted>@coder.com
, but the message was being marked successful, because we were not waiting for the actual outcome of the mail dispatch.This has quite worrying implications for Alertmanager, and I plan to raise a PR in that repo too to address this.