Fix correctness bugs found by code review

- matrix: drop cryptohelper LoginAs so device.json creds aren't
  invalidated on every restart by Init's re-login
- matrix: thread ctx through PostThreadedReply; bot dispatcher derives
  per-command ctx from app lifecycle so SIGTERM cancels in-flight work
- matrix: isTokenValid verifies /whoami user_id matches configured one
- matrix: loadDevice distinguishes missing file from corrupt parse;
  refuse to silently overwrite a corrupt device.json
- matrix: Start checks Syncer type assertion and returns error
- arr: parseLookup skips empty-title items and extracts existing id
- bot: skip Add when Result.Exists; reply "already in library"
This commit is contained in:
prosolis
2026-05-24 20:50:51 -07:00
parent 8c295d183b
commit 035089c159
5 changed files with 137 additions and 52 deletions

View File

@@ -3,6 +3,7 @@ package matrix
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
@@ -50,13 +51,16 @@ func New(cfg config.MatrixConfig) (*Client, error) {
device, err := loadDevice(devicePath)
if err != nil {
slog.Info("no existing device found, will login fresh")
// File exists but is unparseable — refuse to overwrite. A silent fresh
// login would orphan the prior device's megolm sessions and break
// decryption in every encrypted room the bot is already in.
return nil, fmt.Errorf("load device file %s: %w (refusing to overwrite — fix or delete the file)", devicePath, err)
}
var mx *mautrix.Client
if device != nil {
if isTokenValid(cfg.Homeserver, device.AccessToken) {
if isTokenValid(cfg.Homeserver, device.AccessToken, cfg.UserID) {
slog.Info("existing device credentials valid", "device_id", device.DeviceID)
mx, err = mautrix.NewClient(cfg.Homeserver, id.UserID(device.UserID), device.AccessToken)
if err != nil {
@@ -92,12 +96,11 @@ func New(cfg config.MatrixConfig) (*Client, error) {
mx.UserID = resp.UserID
mx.DeviceID = resp.DeviceID
device = &deviceInfo{
if err := saveDevice(devicePath, &deviceInfo{
AccessToken: resp.AccessToken,
DeviceID: string(resp.DeviceID),
UserID: string(resp.UserID),
}
if err := saveDevice(devicePath, device); err != nil {
}); err != nil {
slog.Warn("failed to save device info", "err", err)
}
@@ -117,16 +120,11 @@ func New(cfg config.MatrixConfig) (*Client, error) {
"room", evt.RoomID, "event_id", evt.ID, "sender", evt.Sender, "err", err)
}
ch.LoginAs = &mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{
Type: mautrix.IdentifierTypeUser,
User: cfg.UserID,
},
Password: cfg.Password,
InitialDeviceDisplayName: cfg.DisplayName,
}
// Intentionally NOT setting ch.LoginAs: cryptohelper.Init will Login() every
// time LoginAs is non-nil (see mautrix cryptohelper.go), which would mint a
// new access_token on every startup and silently invalidate the device.json
// we just wrote. We already have valid credentials in mx by this point —
// Init will reuse them.
if err := ch.Init(context.Background()); err != nil {
return nil, fmt.Errorf("crypto helper init: %w", err)
}
@@ -189,8 +187,11 @@ func (c *Client) SetMessageHandler(fn MessageHandler) {
}
// Start begins the Matrix sync loop in the background.
func (c *Client) Start(ctx context.Context) {
syncer := c.mx.Syncer.(*mautrix.DefaultSyncer)
func (c *Client) Start(ctx context.Context) error {
syncer, ok := c.mx.Syncer.(*mautrix.DefaultSyncer)
if !ok {
return fmt.Errorf("matrix syncer is not *mautrix.DefaultSyncer (got %T)", c.mx.Syncer)
}
syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) {
if evt.Sender == c.userID {
@@ -243,6 +244,7 @@ func (c *Client) Start(ctx context.Context) {
}
}
}()
return nil
}
// Stop halts the sync loop and closes the crypto store.
@@ -259,10 +261,8 @@ func (c *Client) Stop() {
// PostThreadedReply sends a plain/HTML message into the thread rooted at rootEventID.
// IsFallingBack + m.in_reply_to gives non-thread-aware clients a sensible quoted reply.
func (c *Client) PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// The caller's ctx governs cancellation and deadline.
func (c *Client) PostThreadedReply(ctx context.Context, roomID id.RoomID, rootEventID id.EventID, plain, htmlBody string) error {
content := &event.MessageEventContent{
MsgType: event.MsgText,
Body: plain,
@@ -279,14 +279,24 @@ func (c *Client) PostThreadedReply(roomID id.RoomID, rootEventID id.EventID, pla
return err
}
// loadDevice returns (nil, nil) when no device file exists, the parsed device
// when it does, or (nil, err) when the file is present but unreadable/corrupt.
// Distinguishing the corrupt case lets the caller refuse to silently overwrite
// it with a brand-new device registration.
func loadDevice(path string) (*deviceInfo, error) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, err
}
var info deviceInfo
if err := json.Unmarshal(data, &info); err != nil {
return nil, err
return nil, fmt.Errorf("parse: %w", err)
}
if info.AccessToken == "" || info.DeviceID == "" || info.UserID == "" {
return nil, fmt.Errorf("missing required fields (access_token/device_id/user_id)")
}
return &info, nil
}
@@ -299,7 +309,11 @@ func saveDevice(path string, info *deviceInfo) error {
return os.WriteFile(path, data, 0o600)
}
func isTokenValid(homeserver, accessToken string) bool {
// isTokenValid hits /whoami and confirms both that the token is accepted AND
// that it identifies the user we expect. A bare status-code check would accept
// a token belonging to a different account if the operator swapped user_id
// without clearing data_dir.
func isTokenValid(homeserver, accessToken, expectedUserID string) bool {
req, err := http.NewRequest("GET", homeserver+"/_matrix/client/v3/account/whoami", nil)
if err != nil {
return false
@@ -312,5 +326,19 @@ func isTokenValid(homeserver, accessToken string) bool {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
if resp.StatusCode != http.StatusOK {
return false
}
var body struct {
UserID string `json:"user_id"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return false
}
if body.UserID != expectedUserID {
slog.Warn("saved token belongs to a different user, will re-login",
"saved", body.UserID, "configured", expectedUserID)
return false
}
return true
}