Debian Codegraph @

testing/e2e/xmpp/inbox_test.go

raw
1 package e2e_test
2
3 import (
4 "context"
5 "crypto/tls"
6 "encoding/xml"
7 "fmt"
8 "io"
9 "net"
10 "net/url"
11 "strconv"
12 "strings"
13 "time"
14
15 "mellium.im/sasl"
16 "mellium.im/xmlstream"
17 "mellium.im/xmpp/jid"
18 "mellium.im/xmpp/muc"
19 "mellium.im/xmpp/stanza"
20
21 mxmpp "mellium.im/xmpp"
22 xmux "mellium.im/xmpp/mux"
23
24 "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/xmpp"
25 )
26
27 type inbox struct {
28 bodies chan string
29 session *mxmpp.Session
30 conn net.Conn
31 cancel context.CancelFunc
32 }
33
34 const (
35 probeUser = "recipient"
36 probePassword = "recipientpass"
37 probeNick = "probe"
38 )
39
40 func (in *inbox) close() {
41 if in.cancel != nil {
42 in.cancel()
43 }
44
45 if in.session != nil {
46 _ = in.session.Close()
47 }
48
49 if in.conn != nil {
50 _ = in.conn.Close()
51 }
52 }
53
54 func startInbox(serviceURL *url.URL) (*inbox, error) {
55 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
56
57 cfg := probeConfig(serviceURL)
58
59 addr := net.JoinHostPort(cfg.Host, strconv.FormatUint(uint64(cfg.Port), 10))
60
61 var d net.Dialer
62
63 conn, err := d.DialContext(ctx, "tcp", addr)
64 if err != nil {
65 cancel()
66
67 return nil, fmt.Errorf("dialing probe: %w", err)
68 }
69
70 session, mucClient, err := probeSession(ctx, cfg, conn)
71 if err != nil {
72 cancel()
73
74 _ = conn.Close()
75
76 return nil, err
77 }
78
79 got := make(chan string, 8)
80 handler := xmux.New(
81 stanza.NSClient,
82 muc.HandleClient(mucClient),
83 xmux.MessageFunc(stanza.ChatMessage, xml.Name{Local: "body"}, captureBody(got)),
84 xmux.MessageFunc(stanza.GroupChatMessage, xml.Name{Local: "body"}, captureBody(got)),
85 )
86
87 go func() {
88 _ = session.Serve(handler)
89 }()
90
91 if err := session.Encode(ctx, struct {
92 XMLName xml.Name `xml:"presence"`
93 }{XMLName: xml.Name{Local: "presence"}}); err != nil {
94 cancel()
95
96 _ = session.Close()
97 _ = conn.Close()
98
99 return nil, fmt.Errorf("sending probe presence: %w", err)
100 }
101
102 if rooms := serviceURL.Query()["rooms"]; len(rooms) > 0 {
103 if err := joinProbeRoom(ctx, mucClient, session, rooms[0], serviceURL.Query().Get("roompassword")); err != nil {
104 cancel()
105
106 _ = session.Close()
107 _ = conn.Close()
108
109 return nil, err
110 }
111 }
112
113 return &inbox{bodies: got, session: session, conn: conn, cancel: cancel}, nil
114 }
115
116 func probeConfig(serviceURL *url.URL) *xmpp.Config {
117 cloned := *serviceURL
118 cloned.User = url.UserPassword(probeUser, probePassword)
119
120 query := cloned.Query()
121 if query.Get("to") == "" && query.Get("rooms") == "" {
122 query.Set("to", probeUser+"@"+cloned.Hostname())
123 cloned.RawQuery = query.Encode()
124 }
125
126 cfg := &xmpp.Config{}
127 if err := cfg.SetURL(&cloned); err != nil {
128 return &xmpp.Config{
129 Host: serviceURL.Hostname(),
130 User: probeUser,
131 Password: probePassword,
132 SkipTLSVerify: serviceURL.Query().Get("skiptlsverify") != "",
133 DisableTLS: serviceURL.Query().Get("disabletls") != "",
134 }
135 }
136
137 return cfg
138 }
139
140 func probeSession(
141 ctx context.Context,
142 cfg *xmpp.Config,
143 conn net.Conn,
144 ) (*mxmpp.Session, *muc.Client, error) {
145 origin, err := jid.New(probeUser, cfg.Host, xmpp.Resource)
146 if err != nil {
147 return nil, nil, fmt.Errorf("parsing probe JID: %w", err)
148 }
149
150 var stream io.ReadWriter = conn
151
152 features := []mxmpp.StreamFeature{}
153 tlsCfg := &tls.Config{
154 ServerName: cfg.Host,
155 MinVersion: tls.VersionTLS12,
156 InsecureSkipVerify: cfg.SkipTLSVerify,
157 }
158
159 if serviceUsesImplicitTLS(cfg) {
160 tlsConn := tls.Client(conn, tlsCfg)
161 if err := tlsConn.HandshakeContext(ctx); err != nil {
162 return nil, nil, fmt.Errorf("probe TLS handshake: %w", err)
163 }
164
165 stream = tlsConn
166 } else if !cfg.DisableTLS {
167 features = append(features, mxmpp.StartTLS(tlsCfg))
168 }
169
170 saslFeature := mxmpp.SASL("", cfg.Password, sasl.ScramSha256, sasl.ScramSha1, sasl.Plain)
171 if cfg.DisableTLS {
172 saslFeature.Necessary = 0
173 }
174
175 features = append(features, saslFeature, mxmpp.BindResource())
176
177 session, err := mxmpp.NewClientSession(ctx, origin, stream, features...)
178 if err != nil {
179 return nil, nil, fmt.Errorf("probe session: %w", err)
180 }
181
182 return session, &muc.Client{}, nil
183 }
184
185 func serviceUsesImplicitTLS(cfg *xmpp.Config) bool {
186 return cfg.GetURL().Scheme == xmpp.SchemeTLS
187 }
188
189 func joinProbeRoom(
190 ctx context.Context,
191 mucClient *muc.Client,
192 session *mxmpp.Session,
193 room, password string,
194 ) error {
195 roomJID, err := jid.Parse(room)
196 if err != nil {
197 return fmt.Errorf("parsing probe room: %w", err)
198 }
199
200 occupancy, err := roomJID.WithResource(probeNick)
201 if err != nil {
202 return fmt.Errorf("probe occupancy JID: %w", err)
203 }
204
205 opts := []muc.Option{muc.MaxHistory(0)}
206 if password != "" {
207 opts = append(opts, muc.Password(password))
208 }
209
210 if _, err := mucClient.Join(ctx, occupancy, session, opts...); err != nil {
211 return fmt.Errorf("probe joining MUC: %w", err)
212 }
213
214 return nil
215 }
216
217 func captureBody(got chan string) xmux.MessageHandlerFunc {
218 return func(_ stanza.Message, t xmlstream.TokenReadEncoder) error {
219 decoder := xml.NewTokenDecoder(t)
220
221 var text string
222
223 var textSb218 strings.Builder
224
225 for {
226 tok, err := decoder.Token()
227 if err != nil {
228 break
229 }
230
231 if cd, ok := tok.(xml.CharData); ok {
232 textSb218.WriteString(string(cd))
233 }
234 }
235
236 text += textSb218.String()
237
238 if text == "" {
239 return nil
240 }
241
242 select {
243 case got <- text:
244 default:
245 }
246
247 return nil
248 }
249 }