|
| 1 | +// Copyright 2019 Prometheus Team |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +// Some tests require a running mail catcher. We use MailDev for this purpose, |
| 15 | +// it can work without or with authentication (LOGIN only). It exposes a REST |
| 16 | +// API which we use to retrieve and check the sent emails. |
| 17 | +// |
| 18 | +// Those tests are only executed when specific environment variables are set, |
| 19 | +// otherwise they are skipped. The tests must be run by the CI. |
| 20 | +// |
| 21 | +// To run the tests locally, you should start 2 MailDev containers: |
| 22 | +// |
| 23 | +// $ docker run --rm -p 1080:1080 -p 1025:1025 --entrypoint bin/maildev djfarrelly/maildev@sha256:624e0ec781e11c3531da83d9448f5861f258ee008c1b2da63b3248bfd680acfa -v |
| 24 | +// $ docker run --rm -p 1081:1080 -p 1026:1025 --entrypoint bin/maildev djfarrelly/maildev@sha256:624e0ec781e11c3531da83d9448f5861f258ee008c1b2da63b3248bfd680acfa --incoming-user user --incoming-pass pass -v |
| 25 | +// |
| 26 | +// $ EMAIL_NO_AUTH_CONFIG=testdata/noauth.yml EMAIL_AUTH_CONFIG=testdata/auth.yml make |
| 27 | +// |
| 28 | +// See also https://github.com/djfarrelly/MailDev for more details. |
| 29 | +package email |
| 30 | + |
| 31 | +import ( |
| 32 | + "context" |
| 33 | + "encoding/base64" |
| 34 | + "fmt" |
| 35 | + "io" |
| 36 | + "net" |
| 37 | + "net/http" |
| 38 | + "net/http/httptest" |
| 39 | + "strconv" |
| 40 | + "testing" |
| 41 | + "time" |
| 42 | + |
| 43 | + "github.com/emersion/go-sasl" |
| 44 | + "github.com/emersion/go-smtp" |
| 45 | + "github.com/prometheus/alertmanager/config" |
| 46 | + commoncfg "github.com/prometheus/common/config" |
| 47 | + "github.com/prometheus/common/promslog" |
| 48 | + "github.com/stretchr/testify/assert" |
| 49 | + "github.com/stretchr/testify/require" |
| 50 | +) |
| 51 | + |
| 52 | +const ( |
| 53 | + TestBearerUsername = "fxcp" |
| 54 | + TestBearerToken = "VkIvciKi9ijpiKNWrQmYCJrzgd9QYCMB" |
| 55 | +) |
| 56 | + |
| 57 | +func TestEmail_OAuth2(t *testing.T) { |
| 58 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) |
| 59 | + t.Cleanup(cancel) |
| 60 | + |
| 61 | + // Setup mock SMTP server which will reject at the DATA stage. |
| 62 | + srv, l, err := mockSMTPServer(t, &xOAuth2Backend{}) |
| 63 | + require.NoError(t, err) |
| 64 | + t.Cleanup(func() { |
| 65 | + // We expect that the server has already been closed in the test. |
| 66 | + require.ErrorIs(t, srv.Shutdown(ctx), smtp.ErrServerClosed) |
| 67 | + }) |
| 68 | + |
| 69 | + done := make(chan any, 1) |
| 70 | + go func() { |
| 71 | + // nolint:testifylint // require cannot be called outside the main goroutine: https://pkg.go.dev/testing#T.FailNow |
| 72 | + assert.NoError(t, srv.Serve(l)) |
| 73 | + close(done) |
| 74 | + }() |
| 75 | + |
| 76 | + oidcServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 77 | + w.Header().Add("Content-Type", "application/json") |
| 78 | + fmt.Fprintf(w, `{"access_token":"%s","token_type":"Bearer","expires_in":3600}`, TestBearerToken) |
| 79 | + })) |
| 80 | + |
| 81 | + // Wait for mock SMTP server to become ready. |
| 82 | + require.Eventuallyf(t, func() bool { |
| 83 | + c, err := smtp.Dial(srv.Addr) |
| 84 | + if err != nil { |
| 85 | + t.Logf("dial failed to %q: %s", srv.Addr, err) |
| 86 | + return false |
| 87 | + } |
| 88 | + |
| 89 | + // Ping. |
| 90 | + if err = c.Noop(); err != nil { |
| 91 | + t.Logf("ping failed to %q: %s", srv.Addr, err) |
| 92 | + return false |
| 93 | + } |
| 94 | + |
| 95 | + // Ensure we close the connection to not prevent server from shutting down cleanly. |
| 96 | + if err = c.Close(); err != nil { |
| 97 | + t.Logf("close failed to %q: %s", srv.Addr, err) |
| 98 | + return false |
| 99 | + } |
| 100 | + |
| 101 | + return true |
| 102 | + }, time.Second*10, time.Millisecond*100, "mock SMTP server failed to start") |
| 103 | + |
| 104 | + // Use mock SMTP server and prepare alert to be sent. |
| 105 | + require.IsType(t, &net.TCPAddr{}, l.Addr()) |
| 106 | + addr := l.Addr().(*net.TCPAddr) |
| 107 | + cfg := &config.EmailConfig{ |
| 108 | + Smarthost: config.HostPort{Host: addr.IP.String(), Port: strconv.Itoa(addr.Port)}, |
| 109 | + Hello: "localhost", |
| 110 | + Headers: make(map[string]string), |
| 111 | + From: "alertmanager@system", |
| 112 | + To: "sre@company", |
| 113 | + AuthUsername: TestBearerUsername, |
| 114 | + AuthXOAuth2: &commoncfg.OAuth2{ |
| 115 | + ClientID: "client_id", |
| 116 | + ClientSecret: "client_secret", |
| 117 | + TokenURL: oidcServer.URL, |
| 118 | + Scopes: []string{"email"}, |
| 119 | + }, |
| 120 | + } |
| 121 | + |
| 122 | + tmpl, firingAlert, err := prepare(cfg) |
| 123 | + require.NoError(t, err) |
| 124 | + |
| 125 | + e := New(cfg, tmpl, promslog.NewNopLogger()) |
| 126 | + |
| 127 | + // Send the alert to mock SMTP server. |
| 128 | + retry, err := e.Notify(context.Background(), firingAlert) |
| 129 | + require.ErrorContains(t, err, "501 5.5.4 Rejected!") |
| 130 | + require.True(t, retry) |
| 131 | + require.NoError(t, srv.Shutdown(ctx)) |
| 132 | + |
| 133 | + require.Eventuallyf(t, func() bool { |
| 134 | + <-done |
| 135 | + return true |
| 136 | + }, time.Second*10, time.Millisecond*100, "mock SMTP server goroutine failed to close in time") |
| 137 | +} |
| 138 | + |
| 139 | +// xOAuth2Backend will reject submission at the DATA stage. |
| 140 | +type xOAuth2Backend struct{} |
| 141 | + |
| 142 | +func (b *xOAuth2Backend) NewSession(c *smtp.Conn) (smtp.Session, error) { |
| 143 | + return &mockSMTPxOAuth2Session{ |
| 144 | + conn: c, |
| 145 | + backend: b, |
| 146 | + }, nil |
| 147 | +} |
| 148 | + |
| 149 | +type mockSMTPxOAuth2Session struct { |
| 150 | + conn *smtp.Conn |
| 151 | + backend smtp.Backend |
| 152 | +} |
| 153 | + |
| 154 | +func (s *mockSMTPxOAuth2Session) AuthMechanisms() []string { |
| 155 | + return []string{sasl.Plain, sasl.Login, "XOAUTH2"} |
| 156 | +} |
| 157 | + |
| 158 | +func (s *mockSMTPxOAuth2Session) Auth(string) (sasl.Server, error) { |
| 159 | + return &xOAuth2BackendAuth{}, nil |
| 160 | +} |
| 161 | + |
| 162 | +func (s *mockSMTPxOAuth2Session) Mail(string, *smtp.MailOptions) error { |
| 163 | + return nil |
| 164 | +} |
| 165 | + |
| 166 | +func (s *mockSMTPxOAuth2Session) Rcpt(string, *smtp.RcptOptions) error { |
| 167 | + return nil |
| 168 | +} |
| 169 | + |
| 170 | +func (s *mockSMTPxOAuth2Session) Data(io.Reader) error { |
| 171 | + return &smtp.SMTPError{Code: 501, EnhancedCode: smtp.EnhancedCode{5, 5, 4}, Message: "Rejected!"} |
| 172 | +} |
| 173 | + |
| 174 | +func (*mockSMTPxOAuth2Session) Reset() {} |
| 175 | + |
| 176 | +func (*mockSMTPxOAuth2Session) Logout() error { return nil } |
| 177 | + |
| 178 | +type xOAuth2BackendAuth struct{} |
| 179 | + |
| 180 | +func (*xOAuth2BackendAuth) Next(response []byte) ([]byte, bool, error) { |
| 181 | + // Generate empty challenge. |
| 182 | + if response == nil { |
| 183 | + return []byte{}, false, nil |
| 184 | + } |
| 185 | + |
| 186 | + token := make([]byte, base64.RawStdEncoding.DecodedLen(len(response))) |
| 187 | + |
| 188 | + _, err := base64.RawStdEncoding.Decode(token, response) |
| 189 | + if err != nil { |
| 190 | + return nil, true, err |
| 191 | + } |
| 192 | + |
| 193 | + expectedToken := fmt.Sprintf("user=%s\x01auth=Bearer %s\x01\x01", TestBearerUsername, TestBearerToken) |
| 194 | + if expectedToken == string(token) { |
| 195 | + return nil, true, nil |
| 196 | + } |
| 197 | + |
| 198 | + return nil, true, fmt.Errorf("unexpected token: %s, expected: %s", token, expectedToken) |
| 199 | +} |
0 commit comments