feat: try StartTLS if SMTP server doesn't support pure TLS (#1676)

* feat: try starttls if smtp server doesn't support pure tls

* chore: fix log id

* fix: errors.As is not working with own error type
This commit is contained in:
Elio Bischof 2021-04-28 09:53:33 +02:00 committed by GitHub
parent 72f0cbe813
commit fd3ac0dbd6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,11 +2,13 @@ package email
import (
"crypto/tls"
"net"
"net/smtp"
"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/notification/providers"
"net"
"net/smtp"
"github.com/pkg/errors"
)
type Email struct {
@ -93,24 +95,44 @@ func (smtpConfig SMTP) connectToSMTP(tlsRequired bool) (client *smtp.Client, err
func (smtpConfig SMTP) getSMPTClient() (*smtp.Client, error) {
client, err := smtp.Dial(smtpConfig.Host)
if err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwos", "Could not make smtp dial")
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwos", "could not make smtp dial")
}
return client, nil
}
func (smtpConfig SMTP) getSMPTClientWithTls(host string) (*smtp.Client, error) {
conn, err := tls.Dial("tcp", smtpConfig.Host, &tls.Config{})
if errors.As(err, &tls.RecordHeaderError{}) {
logging.Log("MAIN-xKIzT").OnError(err).Warn("could not connect using normal tls. trying starttls instead...")
return smtpConfig.getSMPTClientWithStartTls(host)
}
if err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-sl39s", "Could not make tls dial")
return nil, caos_errs.ThrowInternal(err, "EMAIL-sl39s", "could not make tls dial")
}
client, err := smtp.NewClient(conn, host)
if err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwi4", "Could not create smtp client")
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwi4", "could not create smtp client")
}
return client, err
}
func (smtpConfig SMTP) getSMPTClientWithStartTls(host string) (*smtp.Client, error) {
client, err := smtpConfig.getSMPTClient()
if err != nil {
return nil, err
}
if err := client.StartTLS(&tls.Config{
ServerName: host,
}); err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-guvsQ", "could not start tls")
}
return client, nil
}
func (smtpConfig SMTP) smtpAuth(client *smtp.Client, host string) error {
if !smtpConfig.HasAuth() {
return nil
@ -118,6 +140,6 @@ func (smtpConfig SMTP) smtpAuth(client *smtp.Client, host string) error {
// Auth
auth := smtp.PlainAuth("", smtpConfig.User, smtpConfig.Password, host)
err := client.Auth(auth)
logging.Log("EMAIL-s9kfs").WithField("smtp user", smtpConfig.User).OnError(err).Debug("Could not add smtp auth")
logging.Log("EMAIL-s9kfs").WithField("smtp user", smtpConfig.User).OnError(err).Debug("could not add smtp auth")
return err
}