Skip to content

fix(mailer): set a connection deadline before the SMTP greeting is read - #2063

Open
0xABCD01 wants to merge 3 commits into
raystack:mainfrom
0xABCD01:fix/2039-smtp-greeting-deadline
Open

0xABCD01 wants to merge 3 commits into
raystack:mainfrom
0xABCD01:fix/2039-smtp-greeting-deadline

Conversation

@0xABCD01

Copy link
Copy Markdown

Summary

An email send hangs forever when the SMTP server accepts the connection but never sends its greeting. In gopkg.in/mail.v2, Dialer.Dial reads the greeting (inside smtpNewClient) before it sets the connection deadline from Dialer.Timeout, so that first read has no deadline. Every mail path goes through this dialer — login OTP, magic link, invitations, PAT alerts, org and user delete notices — and most run inside an HTTP request, so the request hangs with the send.

Changes

  • pkg/mailer/dialer.go: NewDialerImpl now installs (once, via sync.Once) a wrapper around the library's mail.NetDialTimeout hook that sets a deadline on each new connection as soon as it opens, so the greeting read is covered. After the greeting, the library re-arms the same deadline as before, so the rest of the session is unchanged.
  • pkg/mailer/dialer_test.go: new tests for a silent server and a cooperative server.

Technical Details

  • The deadline is derived from the timeout argument the library passes to the hook for each dial, so every dialer keeps its own Timeout, and a timeout of zero keeps the library's previous unbounded behaviour. If setting the deadline fails, the connection is closed and the error returned.
  • NetDialTimeout is a package-level hook, so the wrapper applies process-wide; pkg/mailer is the only place in the repo that creates a mail dialer (grep NewDialer / NewDialerImpl call sites).
  • The alternative from the issue — moving to an SMTP library whose send takes a context — is a much larger change; this stays within the seam the library already exposes.

Disclosure: @RyoKusnadi already implemented a fix for this in #2043 and closed it himself on 2026-11-08 ("happy to reopen if it's useful"), without any maintainer review or rejection. This PR covers the same ground, written independently from the current code — the main difference is that the deadline here comes from the per-dial timeout argument rather than a captured dialer timeout. Full credit to him for identifying the approach first. If he reopens #2043, I will close this PR in favour of his.

Test Plan

  • Manual testing completed (not done against a real mail server)

  • Build and type checking passes

  • TestDialerImpl_DialAndSend_SilentServer: a local listener accepts and stays silent; with a 300 ms dialer timeout the send must fail with a timeout error instead of blocking.

    • Before the fix: FAIL — DialAndSend still blocked after 10s: no deadline on the greeting read
    • After the fix: passes in ~0.3 s
  • TestDialerImpl_DialAndSend_CooperativeServer: a minimal fake SMTP server completes a full delivery; passes before and after (regression guard).

  • go test ./pkg/mailer/ — ok; also go test ./pkg/mailer/ -race -count=2 — ok. go vet ./pkg/mailer/... and gofmt -l pkg/mailer clean. The full repo suite was not run.

Fixes #2039

@vercel

vercel Bot commented Nov 25, 2026

Copy link
Copy Markdown

@0xABCD01 is attempting to deploy a commit to the Raystack Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Mail delivery now applies the configured timeout to network connections, including when SSL is enabled. If a mail server does not respond within the timeout, the delivery attempt can end with a timeout error rather than remaining stalled.
    • Mail delivery with no timeout configured, and delivery to a responsive mail server, continue to work as expected.

The mail dialer installs a one-time wrapper that sets a deadline on successful connections when the timeout is positive. Tests cover silent SMTP servers, including with SSL, and successful delivery to a cooperative server with zero and default timeouts.

Changes: SMTP greeting timeout

Layer / File(s) Summary
Install the connection deadline wrapper
pkg/mailer/dialer.go
A one-time wrapper sets a deadline after a successful dial when the timeout is positive. NewDialerImpl installs it before creating the mail dialer.
Verify SMTP greeting behavior
pkg/mailer/dialer_test.go
Tests check that delivery to silent servers times out, including with SSL. Tests also check successful delivery to a cooperative SMTP server with zero and default timeouts.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • raystack/frontier#2043: Addresses the same silent SMTP greeting issue by wrapping mail.NetDialTimeout to set a connection deadline.

Suggested reviewers: rohilsurana

Merge Risk: Minimal · up to d0dcf

This change stops email sends from hanging indefinitely when an SMTP server accepts a connection but never sends its greeting. The wrapper is small and leaves behaviour unchanged when no timeout is set. It is covered by targeted tests, and no merge-blocking risk remains.

Pre-merge checks: Passed 2

Check name Status Explanation
Linked Issues check Passed Issue #2039 requires that a send through pkg/mailer must not block indefinitely when the SMTP server accepts a connection and sends no greeting. The issue proposes setting a deadline right after the c…
Out of Scope Changes check Passed The PR changes only pkg/mailer/dialer.go and pkg/mailer/dialer_test.go. The dialer.go change adds the net, sync, and time imports and the installGreetingDeadline wrapper, which directly implement the …
Full details: Linked Issues check

Explanation

Issue #2039 requires that a send through pkg/mailer must not block indefinitely when the SMTP server accepts a connection and sends no greeting. The issue proposes setting a deadline right after the connection opens by wrapping mail.NetDialTimeout. At head d0dcfb7, pkg/mailer/dialer.go implements this. installGreetingDeadline wraps mail.NetDialTimeout once through sync.Once. For each new non-nil connection with timeout > 0, the wrapper calls conn.SetDeadline(time.Now().Add(timeout)) before the library reads the greeting. A SetDeadline failure closes the connection and returns the error. A timeout of zero or less, or a nil connection, keeps the previous behaviour. NewDialerImpl calls installGreetingDeadline before mail.NewDialer. The code was read directly at head. The test file was not re-read in this review; the earlier review read the silent-server, SSL silent-server, and cooperative-server tests. The test runs were not executed here, so the pass results of those tests rest on code reading and the PR description. Non-coding items (manual testing, full repository suite) do not apply.

Full details: Out of Scope Changes check

Explanation

The PR changes only pkg/mailer/dialer.go and pkg/mailer/dialer_test.go. The dialer.go change adds the net, sync, and time imports and the installGreetingDeadline wrapper, which directly implement the issue's first proposed fix. NewDialerImpl's signature and other configuration are unchanged. The test file adds tests and a minimal fake SMTP server that verify the deadline behaviour, which supports the objective. The disclosure about #2043 in the PR description is narrative text and adds no code. The process-wide scope of the mail.NetDialTimeout hook is a design consideration. The PR description states that pkg/mailer is the only place that creates mail dialers, so the wrapper does not affect unrelated code paths. That statement was not independently re-verified in this review.

Finishing Touches

Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 18c8309 and d0dcfb7.

Files selected for processing: 2

  • pkg/mailer/dialer.go
  • pkg/mailer/dialer_test.go
Files with no reviewable changes: 2

  • pkg/mailer/dialer.go
  • pkg/mailer/dialer_test.go

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

@rohilsurana rohilsurana left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix. It does what issue #2039 asks, and I found no security problems. Only pkg/mailer/dialer.go and the new test file change. The wrapper passes the same network, address and timeout to the original dial. It adds no new network calls and does not touch credentials or TLS settings. The tests only listen on loopback.

I ran the same tests before and after the fix, scoped to pkg/mailer. For "before", I put the dialer.go from main back and kept the tests. I also added two tests of my own: a silent server with the default 10s timeout through the public API, and a silent server with SSL = true (the port 465 path).

Test main this PR
TestDialerImpl_DialAndSend_SilentServer FAIL, still blocked after 10s PASS, 0.30s
TestDialerImpl_DialAndSend_CooperativeServer PASS PASS
My silent server, default 10s timeout FAIL, still blocked after 25s PASS, i/o timeout after 10.0s
My silent server, SSL on, 500ms timeout FAIL, still blocked after 15s PASS, i/o timeout after 0.5s

go test -race on the new tests passes. golangci-lint run ./pkg/mailer/... reports 0 issues. gofmt is clean. The Go CI workflows have not run on this PR yet.

The inline comments are small. The main ask is a test for the SSL path, since port 465 is a common setup.

Comment thread pkg/mailer/dialer_test.go

addr := listener.Addr().(*net.TCPAddr)
impl := NewDialerImpl(addr.IP.String(), addr.Port, "", "", true, nil, mail.NoStartTLS)
impl.dialer.Timeout = 300 * time.Millisecond

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a second silent server test with impl.dialer.SSL = true? There the deadline also has to cover the TLS handshake. I checked it locally and it passes with your change and hangs on main, but nothing in the PR guards it. A case with Timeout = 0 against the cooperative server would also be nice, to show the zero timeout path still works.

Comment thread pkg/mailer/dialer.go Outdated
dial := mail.NetDialTimeout
mail.NetDialTimeout = func(network, addr string, timeout time.Duration) (net.Conn, error) {
conn, err := dial(network, addr, timeout)
if err != nil || timeout <= 0 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small guard idea: if err != nil || conn == nil || timeout <= 0. net.DialTimeout never returns a nil conn with a nil error, but a future hook might, and then SetDeadline would panic.

Comment thread pkg/mailer/dialer.go
if err != nil || timeout <= 0 {
return conn, err
}
if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the greeting read times out, mail.v2 returns from Dial without closing the conn (smtp.go:91-94). So each timed out send now leaves one socket open until the garbage collector closes it. That is still far better than hanging forever. It may be worth a follow up, either upstream or by returning a wrapped conn here.

Comment thread pkg/mailer/dialer.go

func NewDialerImpl(SMTPHost string, SMTPPort int, SMTPUser string, SMTPPass string,
SMTPInsecure bool, headers map[string]string, tlsPolicy mail.StartTLSPolicy) *DialerImpl {
installGreetingDeadline()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The constructor changes a package level hook in the library. sync.Once stops a double install, but the write is not synced with a Dial that may be running in another goroutine. That is fine today, since the only caller is cmd/serve.go at startup. Installing it in a package init() would remove the question for good. Not a blocker.

Add the conn == nil check rohilsurana suggested before SetDeadline, plus tests for the SSL silent-server path and the Timeout = 0 path against a cooperative server.
@0xABCD01

0xABCD01 commented Dec 2, 2026

Copy link
Copy Markdown
Author

Pushed the three changes in 18c8309:

  • TestDialerImpl_DialAndSend_SilentServerSSL: silent server with SSL = true and a 500ms timeout, so the deadline has to cover the TLS handshake. Passes in 0.50s with the fix. As a negative control I ran it against main's dialer: it stays blocked and fails the 10s guard, same as the plain silent-server test.
  • TestDialerImpl_DialAndSend_CooperativeServerZeroTimeout: cooperative server with Timeout = 0, the send completes.
  • The dial hook guard is now if err != nil || conn == nil || timeout <= 0.

Results: go test ./pkg/mailer/... passes 4/4, go test -race on the DialAndSend tests passes, gofmt clean.

On the two non-blockers, agreed on both. The socket left open when the greeting read times out sits inside mail.v2's Dial, so a follow-up upstream or a wrapped conn here both work. Moving the hook install to init() also removes the sync question; the only caller today installs it at startup. Happy to pick either up as a follow-up if you want it in this PR.

Comment thread pkg/mailer/dialer.go Outdated

var greetingDeadlineOnce sync.Once

// installGreetingDeadline wraps the mail library's dial hook so that a

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can get rid of this comment. It explains how we got to this fix, which belongs in the PR description. The function name already says what it does.

Comment thread pkg/mailer/dialer_test.go Outdated
return msg
}

// A server that accepts the connection but never sends its greeting must

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can get rid of this comment. The test name can say what it checks, and the library detail belongs in the PR description.

Comment thread pkg/mailer/dialer_test.go Outdated
}
}

// Same silent server, but with SSL on: the deadline set at dial time also

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, we can drop this comment and let the test name say it.

Comment thread pkg/mailer/dialer_test.go Outdated
}
}

// A timeout of zero keeps the library's unbounded behaviour: no deadline

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, we can drop this comment and let the test name say it.

Comment thread pkg/mailer/dialer_test.go Outdated
}
}

// A server that answers normally must still complete the send: the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, we can drop this comment and let the test name say it.

Comment thread pkg/mailer/dialer_test.go Outdated
}
}

// serveFakeSMTP speaks just enough SMTP for one successful delivery.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can drop this one as well. The helper name already says what it does.

@0xABCD01

0xABCD01 commented Dec 3, 2026

Copy link
Copy Markdown
Author

Done in d0dcfb7 — removed the six comments (dialer.go installGreetingDeadline header, plus the five test/helper comments in dialer_test.go). Comment-only change, no code touched. gofmt clean, go test ./pkg/mailer/... passes.

For reference, the silent-server SSL test, the Timeout=0 case, and the nil-conn guard from your earlier review are already in the PR since the previous revision (18c8309), so nothing from that round was missed. The socket-leak follow-up and the init() note I left as follow-ups, not part of this change.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An SMTP server that never sends its greeting makes an email send hang

2 participants