Debian Codegraph @

pkg/services/chat/matrix/matrix_client.go

raw
1 package matrix
2
3 import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net"
14 "net/http"
15 "net/url"
16 "strings"
17 "time"
18
19 "github.com/nicholas-fedor/shoutrrr/pkg/types"
20 "github.com/nicholas-fedor/shoutrrr/pkg/util"
21 )
22
23 // HTTPClient defines the interface for HTTP operations.
24 type HTTPClient interface {
25 Do(req *http.Request) (*http.Response, error)
26 }
27
28 // client manages interactions with the Matrix API.
29 type client struct {
30 apiURL url.URL
31 accessToken string
32 logger types.StdLogger
33 httpClient HTTPClient
34 }
35
36 // DefaultHTTPClient is the default implementation using http.DefaultClient with timeout.
37 type DefaultHTTPClient struct {
38 client *http.Client
39 }
40
41 const (
42 // schemeHTTPS is the URL scheme for HTTPS.
43 schemeHTTPS = "https"
44
45 // schemeHTTP is the URL scheme for HTTP.
46 schemeHTTP = "http"
47
48 // tokenHintLength is the length of the token hint shown in logs.
49 tokenHintLength = 3
50
51 // minSliceLength is the minimum length for slice operations.
52 minSliceLength = 1
53
54 // httpClientErrorStatus is the HTTP status code threshold for client errors.
55 httpClientErrorStatus = 400
56
57 // defaultHTTPTimeout is the timeout for HTTP requests.
58 defaultHTTPTimeout = 10 * time.Second
59
60 // transactionIDRandLen is the length of random bytes in transaction ID.
61 transactionIDRandLen = 8
62
63 // byteMask is the mask for extracting a single byte from an integer.
64 byteMask = 0xFF
65
66 // bitsPerByte is the number of bits in a byte.
67 bitsPerByte = 8
68
69 // authorizationHeader is the HTTP header name for Bearer token authentication.
70 authorizationHeader = "Authorization"
71
72 // bearerPrefix is the prefix for Bearer token authentication.
73 bearerPrefix = "Bearer "
74
75 // deviceIDLength is the length of the generated device ID.
76 // The Matrix spec recommends 10 characters for sufficient uniqueness.
77 deviceIDLength = 10
78
79 // deviceIDPrefix is the prefix for generated device IDs.
80 // This aids identification in Matrix admin interfaces.
81 deviceIDPrefix = "SH"
82
83 // deviceIDHashBytes is the number of hash bytes used for device ID generation.
84 // 8 bytes from SHA-256 provides enough characters for the suffix.
85 deviceIDHashBytes = 8
86
87 // opaqueIDCharset is the character set allowed by the Matrix Opaque Identifier Grammar.
88 // Reference: https://spec.matrix.org/v1.18/appendices/#opaque-identifiers
89 opaqueIDCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
90 opaqueIDCharsetLen = byte(len(opaqueIDCharset))
91 )
92
93 // Do performs the HTTP request.
94 func (c *DefaultHTTPClient) Do(req *http.Request) (*http.Response, error) {
95 resp, err := c.client.Do(req)
96 if err != nil {
97 return nil, fmt.Errorf("performing HTTP request: %w", err)
98 }
99
100 return resp, nil
101 }
102
103 // apiDo performs an HTTP request to the Matrix API.
104 func (c *client) apiDo(ctx context.Context, method, path string, request, response any) error {
105 err := c.doSingleRequest(ctx, method, path, request, response)
106 if err == nil {
107 return nil
108 }
109
110 // If it's a M_LIMIT_EXCEEDED rate limited error, propagate it immediately.
111 // This allows the caller to handle rate limiting as appropriate
112 if isRateLimitedError(err) {
113 c.logf("Rate limited, returning error to caller: %v\n", err)
114
115 return err
116 }
117
118 // For non-retryable errors, return immediately
119 return err
120 }
121
122 // apiGet performs a GET request to the Matrix API with the provided context.
123 func (c *client) apiGet(ctx context.Context, path string, response any) error {
124 reqCtx, cancel := context.WithTimeout(
125 ctx,
126 defaultHTTPTimeout,
127 )
128 defer cancel()
129
130 req, err := http.NewRequestWithContext(
131 reqCtx,
132 http.MethodGet,
133 c.buildURL(path),
134 http.NoBody,
135 )
136 if err != nil {
137 return fmt.Errorf("creating GET request: %w", err)
138 }
139
140 c.setAuthorizationHeader(req)
141
142 res, err := c.httpClient.Do(req)
143 if err != nil {
144 return fmt.Errorf("executing GET request: %w", err)
145 }
146
147 defer func() { _ = res.Body.Close() }()
148
149 body, err := io.ReadAll(res.Body)
150 if err != nil {
151 return fmt.Errorf("reading GET response body: %w", err)
152 }
153
154 if res.StatusCode >= httpClientErrorStatus {
155 resError := &apiResError{}
156 if err = json.Unmarshal(body, resError); err == nil {
157 return resError
158 }
159
160 return fmt.Errorf(
161 "%w: %v (unmarshal error: %w)",
162 ErrUnexpectedStatus,
163 res.Status, err,
164 )
165 }
166
167 if err = json.Unmarshal(body, response); err != nil {
168 return fmt.Errorf("unmarshaling GET response: %w", err)
169 }
170
171 return nil
172 }
173
174 // apiPost performs a POST request to the Matrix API with the provided context.
175 func (c *client) apiPost(ctx context.Context, path string, request, response any) error {
176 return c.apiDo(ctx, http.MethodPost, path, request, response)
177 }
178
179 // apiPut performs a PUT request to the Matrix API with the provided context.
180 func (c *client) apiPut(ctx context.Context, path string, request, response any) error {
181 return c.apiDo(ctx, http.MethodPut, path, request, response)
182 }
183
184 // buildURL returns a copy of the base API URL with the specified path set.
185 func (c *client) buildURL(path string) string {
186 u := c.apiURL
187 u.Path = path
188
189 return u.String()
190 }
191
192 // doSingleRequest performs a single HTTP request without retry logic.
193 func (c *client) doSingleRequest(ctx context.Context, method, path string, request, response any) error {
194 body, err := json.Marshal(request)
195 if err != nil {
196 return fmt.Errorf("marshaling %s request: %w", method, err)
197 }
198
199 reqCtx, cancel := context.WithTimeout(ctx, defaultHTTPTimeout)
200 defer cancel()
201
202 req, err := http.NewRequestWithContext(
203 reqCtx,
204 method,
205 c.buildURL(path),
206 bytes.NewReader(body),
207 )
208 if err != nil {
209 return fmt.Errorf("creating %s request: %w", method, err)
210 }
211
212 req.Header.Set("Content-Type", contentType)
213 c.setAuthorizationHeader(req)
214
215 res, err := c.httpClient.Do(req)
216 if err != nil {
217 return fmt.Errorf("executing %s request: %w", method, err)
218 }
219
220 defer func() { _ = res.Body.Close() }()
221
222 body, err = io.ReadAll(res.Body)
223 if err != nil {
224 return fmt.Errorf("reading %s response body: %w", method, err)
225 }
226
227 if res.StatusCode >= httpClientErrorStatus {
228 resError := &apiResError{}
229 if err = json.Unmarshal(body, resError); err == nil {
230 return resError
231 }
232
233 return fmt.Errorf(
234 "%w: %v (unmarshal error: %w)",
235 ErrUnexpectedStatus,
236 res.Status,
237 err,
238 )
239 }
240
241 if err = json.Unmarshal(body, response); err != nil {
242 return fmt.Errorf("unmarshaling %s response: %w", method, err)
243 }
244
245 return nil
246 }
247
248 // getJoinedRooms retrieves the list of rooms the client has joined.
249 func (c *client) getJoinedRooms(ctx context.Context) ([]string, error) {
250 response := apiResJoinedRooms{}
251
252 err := c.apiGet(ctx, apiJoinedRooms, &response)
253 if err != nil {
254 return []string{}, err
255 }
256
257 return response.Rooms, nil
258 }
259
260 // joinRoom joins a specified room and returns its ID.
261 func (c *client) joinRoom(ctx context.Context, room string) (string, error) {
262 resRoom := apiResRoom{}
263
264 err := c.apiPost(
265 ctx,
266 fmt.Sprintf(apiRoomJoin, room),
267 &struct{}{},
268 &resRoom,
269 )
270 if err != nil {
271 return "", err
272 }
273
274 return resRoom.RoomID, nil
275 }
276
277 // logf logs a formatted message using the client's logger.
278 func (c *client) logf(format string, v ...any) {
279 c.logger.Printf(format, v...)
280 }
281
282 // login authenticates the client using a username and password.
283 func (c *client) login(ctx context.Context, user, password string) error {
284 c.apiURL.RawQuery = ""
285
286 resLogin := apiResLoginFlows{}
287 if err := c.apiGet(ctx, apiLogin, &resLogin); err != nil {
288 return fmt.Errorf("failed to get login flows: %w", err)
289 }
290
291 flows := make([]string, 0, len(resLogin.Flows))
292 for _, flow := range resLogin.Flows {
293 flows = append(flows, string(flow.Type))
294
295 // Prefer password login when a user is configured
296 if flow.Type == flowLoginPassword && user != "" {
297 c.logf("Using login flow '%v'", flow.Type)
298
299 return c.loginPassword(ctx, user, password)
300 }
301
302 // Only use token login when no user is configured
303 if flow.Type == flowLoginToken && user == "" {
304 c.logf("Using login flow '%v'", flow.Type)
305
306 return c.loginToken(ctx, password)
307 }
308 }
309
310 return fmt.Errorf(
311 "%w: %v",
312 ErrUnsupportedLoginFlows,
313 strings.Join(flows, ", "),
314 )
315 }
316
317 // loginPassword performs a password-based login to the Matrix server.
318 func (c *client) loginPassword(ctx context.Context, user, password string) error {
319 response := apiResLogin{}
320
321 deviceID := generateDeviceID(user, c.apiURL.Host)
322 c.logf("Using device ID: %v\n", deviceID)
323
324 //nolint:exhaustruct // Intentional zero-value initialization for apiReqLogin
325 err := c.apiPost(
326 ctx,
327 apiLogin,
328 apiReqLogin{
329 Type: flowLoginPassword,
330 Password: password,
331 Identifier: newUserIdentifier(user),
332 DeviceID: deviceID,
333 },
334 &response,
335 )
336 if err != nil {
337 return fmt.Errorf("failed to log in: %w", err)
338 }
339
340 c.accessToken = response.AccessToken
341
342 tokenHint := ""
343 if len(response.AccessToken) > tokenHintLength {
344 tokenHint = response.AccessToken[:tokenHintLength]
345 }
346
347 c.logf("AccessToken: %v...\n", tokenHint)
348 c.logf("HomeServer: %v\n", response.HomeServer)
349 c.logf("User: %v\n", response.UserID)
350 c.logf("DeviceID: %v\n", response.DeviceID)
351
352 return nil
353 }
354
355 // loginToken performs a token-based login to the Matrix server.
356 func (c *client) loginToken(ctx context.Context, token string) error {
357 response := apiResLogin{}
358
359 // For token-based login, use an empty user string in the device ID hash.
360 // This ensures all token-based logins to the same host reuse the same device.
361 deviceID := generateDeviceID("", c.apiURL.Host)
362 c.logf("Using device ID: %v\n", deviceID)
363
364 //nolint:exhaustruct // Intentional zero-value initialization for apiReqLogin
365 err := c.apiPost(
366 ctx,
367 apiLogin,
368 apiReqLogin{
369 Type: flowLoginToken,
370 Token: token,
371 DeviceID: deviceID,
372 },
373 &response,
374 )
375 if err != nil {
376 return fmt.Errorf("failed to log in with token: %w", err)
377 }
378
379 c.accessToken = response.AccessToken
380
381 tokenHint := ""
382 if len(response.AccessToken) > tokenHintLength {
383 tokenHint = response.AccessToken[:tokenHintLength]
384 }
385
386 c.logf("AccessToken: %v...\n", tokenHint)
387 c.logf("HomeServer: %v\n", response.HomeServer)
388 c.logf("User: %v\n", response.UserID)
389 c.logf("DeviceID: %v\n", response.DeviceID)
390
391 return nil
392 }
393
394 // sendMessage sends a message to the specified rooms or all joined rooms if none are specified.
395 func (c *client) sendMessage(ctx context.Context, message string, rooms []string) []error {
396 if len(rooms) >= minSliceLength {
397 return c.sendToExplicitRooms(ctx, rooms, message)
398 }
399
400 return c.sendToJoinedRooms(ctx, message)
401 }
402
403 // sendMessageToRoom sends a message to a specific room using PUT method with transaction ID.
404 func (c *client) sendMessageToRoom(ctx context.Context, message, roomID string) error {
405 resEvent := apiResEvent{}
406 txnID := generateTransactionID()
407
408 path := fmt.Sprintf(apiSendMessage, roomID, txnID)
409
410 request := apiReqSend{
411 MsgType: msgTypeText,
412 Body: message,
413 }
414
415 return c.apiPut(ctx, path, request, &resEvent)
416 }
417
418 // sendToExplicitRooms sends a message to explicitly specified rooms and collects any errors.
419 func (c *client) sendToExplicitRooms(ctx context.Context, rooms []string, message string) []error {
420 var errs []error
421
422 for _, room := range rooms {
423 room = strings.TrimSpace(room)
424 if room == "" {
425 errs = append(errs, fmt.Errorf("%w", ErrEmptyRoom))
426
427 continue
428 }
429
430 c.logf("Sending message to '%v'...\n", room)
431
432 if !strings.HasPrefix(room, "!") {
433 roomID, err := c.joinRoom(ctx, room)
434 if err != nil {
435 errs = append(errs, fmt.Errorf("error joining room %v: %w", room, err))
436
437 continue
438 }
439
440 if room != roomID {
441 c.logf("Resolved room alias '%v' to ID '%v'", room, roomID)
442 }
443
444 room = roomID
445 }
446
447 if err := c.sendMessageToRoom(ctx, message, room); err != nil {
448 errs = append(
449 errs,
450 fmt.Errorf("failed to send message to room '%v': %w", room, err),
451 )
452 }
453 }
454
455 return errs
456 }
457
458 // sendToJoinedRooms sends a message to all joined rooms and collects any errors.
459 func (c *client) sendToJoinedRooms(ctx context.Context, message string) []error {
460 var errs []error
461
462 joinedRooms, err := c.getJoinedRooms(ctx)
463 if err != nil {
464 return append(errs, fmt.Errorf("failed to get joined rooms: %w", err))
465 }
466
467 for _, roomID := range joinedRooms {
468 c.logf("Sending message to '%v'...\n", roomID)
469
470 if err := c.sendMessageToRoom(ctx, message, roomID); err != nil {
471 errs = append(
472 errs,
473 fmt.Errorf("failed to send message to room '%v': %w", roomID, err),
474 )
475 }
476 }
477
478 return errs
479 }
480
481 // setAuthorizationHeader sets the Authorization header with Bearer token if access token is available.
482 func (c *client) setAuthorizationHeader(req *http.Request) {
483 if c.accessToken != "" {
484 req.Header.Set(authorizationHeader, bearerPrefix+c.accessToken)
485 }
486 }
487
488 // useToken sets the access token for the client.
489 func (c *client) useToken(token string) {
490 c.accessToken = token
491 }
492
493 // isRateLimitedError checks if the error is a rate limiting error.
494 func isRateLimitedError(err error) bool {
495 if err == nil {
496 return false
497 }
498
499 var apiErr *apiResError
500 if errors.As(err, &apiErr) {
501 return apiErr.IsRateLimited()
502 }
503
504 return false
505 }
506
507 // generateTransactionID generates a unique transaction ID using a timestamp
508 // and random bytes to ensure uniqueness across requests.
509 func generateTransactionID() string {
510 now := time.Now().UnixNano()
511 randBytes := make([]byte, transactionIDRandLen)
512
513 if _, err := rand.Read(randBytes); err != nil {
514 // Fallback: use timestamp-based bytes if crypto/rand fails
515 for i := range randBytes {
516 randBytes[i] = byte((now >> (bitsPerByte * i)) & byteMask)
517 }
518 }
519
520 return fmt.Sprintf("%d-%s", now, hex.EncodeToString(randBytes))
521 }
522
523 // generateDeviceID generates a deterministic device ID based on the user and
524 // host. This ensures the same logical client reuses the same device across
525 // restarts, preventing device accumulation on the Matrix server.
526 //
527 // The device ID follows the Matrix spec's Opaque Identifier Grammar:
528 // characters from [0-9], [A-Z], [a-z], "-", ".", "_", and "~".
529 // The format is "SH" + 8 characters derived from SHA-256(user:host),
530 // totaling 10 characters as recommended by the Matrix spec.
531 //
532 // The host is normalized to exclude default ports (443 for HTTPS, 80 for HTTP)
533 // to prevent device churn when ports are omitted or explicitly included.
534 func generateDeviceID(user, host string) string {
535 // Normalize host by removing default ports to prevent device churn.
536 // url.Host may include a port (e.g., "matrix.example.com:443"), but we want
537 // consistent device IDs regardless of whether the default port is explicit.
538 normalizedHost := normalizeHostForDeviceID(host)
539
540 // Create a deterministic hash from user and host.
541 // Using user + ":" + host ensures different users on the same host
542 // get different device IDs, and the same user on different hosts
543 // also gets different device IDs.
544 hash := sha256.Sum256([]byte(user + ":" + normalizedHost))
545
546 // Encode hash bytes to a device ID using the Opaque Identifier Grammar.
547 // We use base32-like encoding with the allowed character set.
548 // The hash provides sufficient entropy for uniqueness per user+host.
549 deviceID := deviceIDPrefix
550 for i := 0; i < deviceIDHashBytes && len(deviceID) < deviceIDLength; i++ {
551 // Map each byte to a character in the allowed set.
552 // Using modulo with a character set size ensures we stay within bounds.
553 deviceID += string(opaqueIDCharset[hash[i]%opaqueIDCharsetLen])
554 }
555
556 return deviceID
557 }
558
559 // normalizeHostForDeviceID normalizes a host string by removing default ports.
560 // This prevents device churn when the port is omitted or explicitly included
561 // in the URL (e.g., "matrix.example.com:443" vs "matrix.example.com").
562 func normalizeHostForDeviceID(host string) string {
563 // Check for explicit port using net.SplitHostPort.
564 // If no port is present, return the host as-is.
565 hostname, port, err := net.SplitHostPort(host)
566 if err != nil {
567 // No port present, return host as-is.
568 return host
569 }
570
571 // Remove default ports to normalize the host.
572 // Port 443 is the default for HTTPS, 80 for HTTP.
573 if port == "443" || port == "80" {
574 return hostname
575 }
576
577 // Non-default port, keep it for uniqueness.
578 return host
579 }
580
581 // newClient creates a new Matrix client with the specified host and TLS settings.
582 //
583 //nolint:exhaustruct // Intentional partial initialization
584 func newClient(host string, disableTLS bool, logger types.StdLogger) *client {
585 client := &client{
586 logger: logger,
587 apiURL: url.URL{
588 Host: host,
589 Scheme: schemeHTTPS,
590 },
591 httpClient: &DefaultHTTPClient{
592 client: &http.Client{
593 Timeout: defaultHTTPTimeout,
594 },
595 },
596 }
597
598 if client.logger == nil {
599 client.logger = util.DiscardLogger
600 }
601
602 if disableTLS {
603 client.apiURL.Scheme = schemeHTTP
604 }
605
606 client.logger.Printf("Using server: %v\n", client.apiURL.String())
607
608 return client
609 }