Migrate Matrix auth to appservice (MAS-durable)

Replace password login + password-UIA cross-signing with appservice
as_token auth and MSC4190 device creation, so the bot survives the
Matrix Authentication Service (MAS) migration that removes m.login.password
and UIA.

- internal/bot/client.go: NewClient uses AS_TOKEN, SetAppServiceUserID,
  whoami validation, cryptohelper MSC4190 device create; drop device.json
  (crypto store persists device id); cross-signing best-effort/soft-fail.
- main.go: Config.Password -> ASToken (reads AS_TOKEN).
- internal/util/auth.go: deleted (password login dead in a MAS world).
- Bump mautrix-go v0.28.0 -> v0.28.1.
- registration.yaml.example + README/.env.example: appservice setup docs.
This commit is contained in:
prosolis
2026-07-03 15:12:47 -07:00
parent c07d228be6
commit 48330be3d5
8 changed files with 177 additions and 229 deletions

View File

@@ -2,203 +2,146 @@ package bot
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"gogobee/internal/util"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/crypto/cryptohelper"
"maunium.net/go/mautrix/id"
)
// DeviceInfo holds persisted device credentials.
type DeviceInfo struct {
AccessToken string `json:"access_token"`
DeviceID string `json:"device_id"`
UserID string `json:"user_id"`
}
// Config holds the bot's startup configuration.
type Config struct {
Homeserver string
UserID string
Password string
UserID string // Bot's full Matrix user ID, e.g. @gogobee:example.com
ASToken string // Appservice as_token from registration.yaml
DataDir string
DisplayName string
}
// NewClient creates and configures a mautrix client with E2EE support.
// The cryptohelper handles:
// - Persistent crypto store in SQLite (device keys, sessions, cross-signing keys)
// - Automatic cross-signing bootstrap (self-signs the device on first run)
// - Automatic device trust via cross-signing (no manual verification needed)
// - Megolm session sharing and key exchange
// - Olm session management for device-to-device encryption
// NewClient creates and configures a mautrix client authenticated as an
// application service, with E2EE via the cryptohelper.
//
// This solves the TS version's device verification issues because:
// 1. Crypto state persists across restarts (not in-memory like fake-indexeddb)
// 2. Cross-signing makes other devices trust this bot automatically
// 3. The bot trusts all users' devices by default (appropriate for a bot)
// 4. No manual emoji/SAS verification needed
// Why appservice instead of password login:
//
// Under Matrix Authentication Service (MAS), the legacy password login
// (m.login.password) and User-Interactive Auth (UIA) flows are being removed —
// auth moves to OAuth2/OIDC. A bot built on password login + password-UIA
// cross-signing (the old code) breaks in a MAS world: short-lived tokens with
// no refresh, and UIA-gated key uploads that simply fail.
//
// The appservice model sidesteps MAS entirely. The as_token is a Synapse-level
// trust relationship declared in registration.yaml — Synapse validates it
// directly, not via MAS — so it never expires and needs no login flow. Device
// creation uses MSC4190 (PUT /devices), which replaces the UIA-gated device
// dance for appservice users. This is the MAS-durable path.
//
// The cryptohelper still handles everything E2EE:
// - Persistent crypto store in SQLite (device keys, sessions, cross-signing)
// - Megolm session sharing / key exchange, Olm device-to-device sessions
// - The bot trusts all users' devices by default (appropriate for a bot)
// - No interactive emoji/SAS verification needed
func NewClient(cfg Config) (*mautrix.Client, error) {
if err := os.MkdirAll(cfg.DataDir, 0o755); err != nil {
return nil, fmt.Errorf("create data dir: %w", err)
}
if cfg.ASToken == "" {
return nil, fmt.Errorf("AS_TOKEN is required (appservice registration as_token)")
}
if cfg.UserID == "" {
return nil, fmt.Errorf("BOT_USER_ID is required")
}
devicePath := filepath.Join(cfg.DataDir, "device.json")
ctx := context.Background()
userID := id.UserID(cfg.UserID)
// Try to load existing device credentials
device, err := loadDevice(devicePath)
// The as_token IS the access token. No login flow, no refresh — Synapse
// trusts it for any user in the registration's namespace.
client, err := mautrix.NewClient(cfg.Homeserver, userID, cfg.ASToken)
if err != nil {
slog.Info("no existing device found, will login fresh")
return nil, fmt.Errorf("create client: %w", err)
}
var client *mautrix.Client
// Assert our own user ID on every request (appservice identity assertion,
// ?user_id=). Required so Synapse knows which namespaced user we're acting
// as — including on /sync and the MSC4190 device creation below.
client.SetAppServiceUserID = true
if device != nil {
// Validate existing token
valid, _ := util.IsTokenValid(cfg.Homeserver, device.AccessToken)
if valid {
slog.Info("existing device credentials valid", "device_id", device.DeviceID)
userID := id.UserID(device.UserID)
client, err = mautrix.NewClient(cfg.Homeserver, userID, device.AccessToken)
if err != nil {
return nil, fmt.Errorf("create client with existing token: %w", err)
}
client.DeviceID = id.DeviceID(device.DeviceID)
} else {
slog.Warn("existing device credentials invalid, logging in again")
device = nil
}
// Validate the token + homeserver reachability up front with a clear error.
whoami, err := client.Whoami(ctx)
if err != nil {
return nil, fmt.Errorf("appservice token validation failed (whoami): %w", err)
}
if device == nil {
// Fresh login
loginResp, err := util.LoginWithPassword(cfg.Homeserver, cfg.UserID, cfg.Password, cfg.DisplayName)
if err != nil {
return nil, fmt.Errorf("login: %w", err)
}
userID := id.UserID(loginResp.UserID)
client, err = mautrix.NewClient(cfg.Homeserver, userID, loginResp.AccessToken)
if err != nil {
return nil, fmt.Errorf("create client: %w", err)
}
client.DeviceID = id.DeviceID(loginResp.DeviceID)
// Save device info
device = &DeviceInfo{
AccessToken: loginResp.AccessToken,
DeviceID: loginResp.DeviceID,
UserID: loginResp.UserID,
}
if err := saveDevice(devicePath, device); err != nil {
slog.Warn("failed to save device info", "err", err)
}
slog.Info("logged in successfully",
"user_id", loginResp.UserID,
"device_id", loginResp.DeviceID,
)
if whoami.UserID != userID {
return nil, fmt.Errorf("appservice identity mismatch: token resolves to %s but BOT_USER_ID is %s", whoami.UserID, userID)
}
slog.Info("appservice token valid", "user_id", whoami.UserID)
// Set up E2EE via cryptohelper — stores crypto state in its own SQLite DB,
// separate from the main app database. Unlike the TS version which used an
// in-memory fake-indexeddb store that was lost on restart (causing constant
// re-verification), mautrix-go's cryptohelper persists everything in SQLite:
// device keys, olm/megolm sessions, cross-signing keys, and device trust state.
//
// We pass just the raw file path — the cryptohelper wraps it in a file: URI
// with _txlock=immediate internally (see cryptohelper.go line 82).
// Set up E2EE. The cryptohelper persists all crypto state in its own SQLite
// DB (device keys, olm/megolm sessions, cross-signing keys, device trust),
// separate from the main app database. The device ID is persisted there too,
// so restarts reuse the same device — no device.json needed.
cryptoDBPath := filepath.Join(cfg.DataDir, "crypto.db")
ch, err := cryptohelper.NewCryptoHelper(client, []byte("gogobee_pickle_key"), cryptoDBPath)
if err != nil {
return nil, fmt.Errorf("init crypto helper: %w", err)
}
// LoginAs enables the cryptohelper to re-login if the token expires,
// and to bootstrap cross-signing on first run. Cross-signing means:
// - The bot's master key signs its own device key
// - Other users/devices that have verified the bot's master key
// will automatically trust this device
// - No interactive emoji/SAS verification needed
// MSC4190: create/refresh the bot's device via PUT /devices instead of the
// UIA-gated login dance. On first run the crypto store has no device ID, so
// a fresh one is generated and persisted; on restart the stored ID is
// reused (the PUT is idempotent). LoginAs carries only the display name —
// in MSC4190 mode the cryptohelper never calls /login.
ch.MSC4190 = true
ch.LoginAs = &mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{
Type: mautrix.IdentifierTypeUser,
User: cfg.UserID,
},
Password: cfg.Password,
InitialDeviceDisplayName: cfg.DisplayName,
}
if err := ch.Init(context.Background()); err != nil {
return nil, fmt.Errorf("crypto helper init: %w", err)
if err := ch.Init(ctx); err != nil {
return nil, fmt.Errorf("crypto helper init (MSC4190 device create): %w", err)
}
// Attach crypto helper to client
client.Crypto = ch
// Bootstrap cross-signing: generate keys, sign own device, sign master key.
// This makes the bot's device show as "verified" to other users.
// Best-effort cross-signing bootstrap. This makes the bot's device show as
// "verified" to users who have verified the bot's master key. It is NOT
// required for E2EE to function — the bot already trusts all devices and
// shares keys — so any failure is logged and ignored.
//
// Under MSC3202 (appservice device assertion) Synapse may accept the key
// upload without UIA, in which case the callback below is never invoked. If
// the homeserver still demands UIA, we have no password credential to
// satisfy it (that's the whole point of going MAS-native), so it fails soft.
mach := ch.Machine()
recoveryKey, _, err := mach.GenerateAndUploadCrossSigningKeys(context.Background(), func(ui *mautrix.RespUserInteractive) interface{} {
return map[string]interface{}{
"type": mautrix.AuthTypePassword,
"identifier": map[string]interface{}{
"type": mautrix.IdentifierTypeUser,
"user": cfg.UserID,
},
"password": cfg.Password,
"session": ui.Session,
}
recoveryKey, _, err := mach.GenerateAndUploadCrossSigningKeys(ctx, func(ui *mautrix.RespUserInteractive) interface{} {
slog.Warn("cross-signing: homeserver requested UIA, but appservice auth has no password credential to satisfy it — skipping verified-shield bootstrap")
return map[string]interface{}{"session": ui.Session}
}, "")
if err != nil {
slog.Warn("cross-signing: key upload failed (may already exist)", "err", err)
slog.Warn("cross-signing: key upload skipped (may already exist or UIA required)", "err", err)
} else {
slog.Info("cross-signing: keys uploaded", "recovery_key", recoveryKey)
}
if err := mach.SignOwnDevice(context.Background(), mach.OwnIdentity()); err != nil {
if err := mach.SignOwnDevice(ctx, mach.OwnIdentity()); err != nil {
slog.Warn("cross-signing: sign own device failed", "err", err)
} else {
slog.Info("cross-signing: own device signed")
}
if err := mach.SignOwnMasterKey(context.Background()); err != nil {
if err := mach.SignOwnMasterKey(ctx); err != nil {
slog.Warn("cross-signing: sign master key failed", "err", err)
} else {
slog.Info("cross-signing: master key signed")
}
slog.Info("E2EE initialized",
"user_id", client.UserID,
"device_id", client.DeviceID,
"crypto_store", "sqlite-persistent",
"auth", "appservice+msc4190",
)
return client, nil
}
func loadDevice(path string) (*DeviceInfo, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var info DeviceInfo
if err := json.Unmarshal(data, &info); err != nil {
return nil, err
}
return &info, nil
}
func saveDevice(path string, info *DeviceInfo) error {
data, err := json.MarshalIndent(info, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o600)
}

View File

@@ -1,86 +0,0 @@
package util
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// LoginResponse holds the Matrix login response fields we care about.
type LoginResponse struct {
AccessToken string `json:"access_token"`
DeviceID string `json:"device_id"`
UserID string `json:"user_id"`
}
// LoginWithPassword performs a Matrix password login.
func LoginWithPassword(homeserver, user, password, deviceDisplayName string) (*LoginResponse, error) {
url := homeserver + "/_matrix/client/v3/login"
body := map[string]any{
"type": "m.login.password",
"identifier": map[string]string{
"type": "m.id.user",
"user": user,
},
"password": password,
"initial_device_display_name": deviceDisplayName,
}
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal login body: %w", err)
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Post(url, "application/json", bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("login request: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return nil, fmt.Errorf("login failed (HTTP %d): %s", resp.StatusCode, string(respBody))
}
var result LoginResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("parse login response: %w", err)
}
return &result, nil
}
// IsTokenValid checks if an access token is still valid via /account/whoami.
func IsTokenValid(homeserver, accessToken string) (bool, string) {
url := homeserver + "/_matrix/client/v3/account/whoami"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, ""
}
req.Header.Set("Authorization", "Bearer "+accessToken)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return false, ""
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false, ""
}
var result struct {
UserID string `json:"user_id"`
}
body, _ := io.ReadAll(resp.Body)
if err := json.Unmarshal(body, &result); err != nil {
return false, ""
}
return true, result.UserID
}