File size: 1,901 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package app

import (
	"context"
	"crypto/tls"
	"net"
	_ "net/url"
	"strings"

	"github.com/target/goalert/alert"
	"github.com/target/goalert/auth/authtoken"
	"github.com/target/goalert/integrationkey"
	"github.com/target/goalert/smtpsrv"
)

func (app *App) initSMTPServer(ctx context.Context) error {
	if app.cfg.SMTPListenAddr == "" && app.cfg.SMTPListenAddrTLS == "" {
		return nil
	}

	cfg := smtpsrv.Config{
		Domain:            app.cfg.EmailIntegrationDomain,
		AllowedDomains:    parseAllowedDomains(app.cfg.SMTPAdditionalDomains, app.cfg.EmailIntegrationDomain),
		TLSConfig:         app.cfg.TLSConfigSMTP,
		MaxRecipients:     app.cfg.SMTPMaxRecipients,
		BackgroundContext: app.LogBackgroundContext,
		Logger:            app.cfg.Logger,
		AuthorizeFunc: func(ctx context.Context, id string) (context.Context, error) {
			tok, _, err := authtoken.Parse(id, nil)
			if err != nil {
				return nil, err
			}

			ctx, err = app.IntegrationKeyStore.Authorize(ctx, *tok, integrationkey.TypeEmail)
			if err != nil {
				return nil, err
			}

			return ctx, nil
		},
		CreateAlertFunc: func(ctx context.Context, a *alert.Alert) error {
			_, _, err := app.AlertStore.CreateOrUpdate(ctx, a)
			return err
		},
	}

	app.smtpsrv = smtpsrv.NewServer(cfg)
	var err error
	if app.cfg.SMTPListenAddr != "" {
		app.smtpsrvL, err = net.Listen("tcp", app.cfg.SMTPListenAddr)
		if err != nil {
			return err
		}
	}

	if app.cfg.SMTPListenAddrTLS != "" {
		l, err := tls.Listen("tcp", app.cfg.SMTPListenAddrTLS, cfg.TLSConfig)
		if err != nil {
			return err
		}
		app.smtpsrvL = newMultiListener(app.smtpsrvL, l)
	}

	return nil
}

func parseAllowedDomains(additionalDomains string, primaryDomain string) []string {
	if !strings.Contains(additionalDomains, primaryDomain) {
		additionalDomains = strings.Join([]string{additionalDomains, primaryDomain}, ",")
	}
	return strings.Split(additionalDomains, ",")
}