--- a/pkg/connector/login.go +++ b/pkg/connector/login.go @@ -389,7 +389,7 @@ func (wl *WALogin) onLoginComplete(ctx context.Context) (*bridgev2.LoginStep, er } newLoginID := waid.MakeUserLoginID(wl.LoginSuccess.ID) - ul, err := wl.User.NewLogin(ctx, &database.UserLogin{ + ul, err := xessengerNewLogin(ctx, wl.User, &database.UserLogin{ ID: newLoginID, RemoteName: "+" + wl.LoginSuccess.ID.User, RemoteProfile: status.RemoteProfile{ @@ -404,15 +404,21 @@ func (wl *WALogin) onLoginComplete(ctx context.Context) (*bridgev2.LoginStep, er HistorySyncPortalsNeedCreating: true, }, }, &bridgev2.NewLoginParams{ - DeleteOnConflict: true, + DeleteOnConflict: false, }) if err != nil { + if resp, ok := err.(bridgev2.RespError); ok && resp.ErrCode == "M_ACCOUNT_IN_USE" { + xessengerUnlinkDevice(wl.Log.WithContext(ctx), wl.Client) + } return nil, fmt.Errorf("failed to create user login: %w", err) } ul.Client.(*WhatsAppClient).isNewLogin = true ul.Client.Connect(ul.Log.WithContext(wl.Main.Bridge.BackgroundCtx)) + if ul.UserMXID != wl.User.MXID { + return nil, xessengerAccountInUse(ul.ID) + } return &bridgev2.LoginStep{ Type: bridgev2.LoginStepTypeComplete, StepID: LoginStepIDComplete, --- /dev/null +++ b/pkg/connector/xessenger_login.go @@ -0,0 +1,99 @@ +package connector + +import ( + "context" + "fmt" + "net/http" + "sync" + "time" + + "github.com/rs/zerolog" + "go.mau.fi/whatsmeow" + "maunium.net/go/mautrix/bridgev2" + "maunium.net/go/mautrix/bridgev2/database" + "maunium.net/go/mautrix/bridgev2/networkid" + "maunium.net/go/mautrix/bridgev2/status" +) + +// One WhatsApp account has one connection, which several Xessenger workspaces may link to +// (docs/team-workspaces.md, T8). Upstream moves a conflicting login to the newer Matrix user; here +// another user's login of a connected account leaves the existing login alone and gets +// M_ACCOUNT_IN_USE with that login's ID, so the server links the workspace to it instead. When the +// existing login has lost its session it takes the new one first, as in its holder's own re-login, +// or only that holder could ever bring the connection back. + +// xessengerAccountInUse answers with the existing login, never naming its Matrix user. +func xessengerAccountInUse(held networkid.UserLoginID) bridgev2.RespError { + return bridgev2.RespError{ + ErrCode: "M_ACCOUNT_IN_USE", + Err: "This account is already connected in Xessenger. Link this workspace to that connection.", + StatusCode: http.StatusConflict, + ExtraData: map[string]any{"com.xessenger.login_id": string(held)}, + } +} + +// xessengerSessionLost reports whether a login has lost its session, by what its client last +// reported, which is what the account list shows. A temporary ban reports BAD_CREDENTIALS with a +// live session. A login with no state yet (after a restart) isn't known to have lost anything. +func xessengerSessionLost(login *bridgev2.UserLogin) bool { + state := login.BridgeState.GetPrevUnsent() + return (state.StateEvent == status.StateBadCredentials || state.StateEvent == status.StateLoggedOut) && + state.Error != WATemporaryBan +} + +// xessengerUnlinkDevice removes the companion device a pairing just added, so the phone doesn't keep +// an unused linked device. Logging out needs the paired device signed in, which the 515 restart +// ended. If that fails, the device only leaves this bridge's store, and the person may have to +// remove it from the phone's linked devices. +// The cleanup outlives the login request, which the server may stop waiting for. +func xessengerUnlinkDevice(ctx context.Context, cli *whatsmeow.Client) { + ctx = context.WithoutCancel(ctx) + logoutCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + log := zerolog.Ctx(ctx) + if err := cli.Connect(); err != nil { + log.Warn().Err(err).Msg("Failed to reconnect the extra WhatsApp device to unlink it") + } else if !cli.WaitForConnection(15 * time.Second) { + log.Warn().Msg("Timed out signing in the extra WhatsApp device to unlink it") + } else if err = cli.Logout(logoutCtx); err != nil { + log.Warn().Err(err).Msg("Failed to unlink the extra WhatsApp device") + } else { + return + } + cli.Disconnect() + if err := cli.Store.Delete(ctx); err != nil { + log.Warn().Err(err).Msg("Failed to delete the extra WhatsApp device from the store") + } +} + +// One process owns this bridge database. Deciding who gets an account and saving the result are one +// step, so simultaneous sign-ins cannot both take over a login. +var xessengerAdmission sync.Mutex + +// xessengerNewLogin saves a paired login, unless another Matrix user holds the account. A held login +// that has lost its session takes this pairing's device and is returned, still the holder's; the +// caller starts it and answers M_ACCOUNT_IN_USE. Any other held login gets that answer here, and the +// caller unlinks the device. +func xessengerNewLogin(ctx context.Context, user *bridgev2.User, data *database.UserLogin, params *bridgev2.NewLoginParams) (*bridgev2.UserLogin, error) { + params.DeleteOnConflict = false + xessengerAdmission.Lock() + defer xessengerAdmission.Unlock() + held, err := user.Bridge.GetExistingUserLoginByID(ctx, data.ID) + if err != nil { + return nil, fmt.Errorf("failed to check existing login: %w", err) + } + if held == nil || held.UserMXID == user.MXID { + return user.NewLogin(ctx, data, params) + } + if !xessengerSessionLost(held) { + return nil, xessengerAccountInUse(held.ID) + } + // NewLogin in this bridgev2 version leaves the old client running. + held.Client.Disconnect() + login, err := held.User.NewLogin(ctx, data, params) + if err == nil { + // No longer lost for the next sign-in, before the caller has started the client. + login.BridgeState.Send(status.BridgeState{StateEvent: status.StateConnecting}) + } + return login, err +} --- /dev/null +++ b/pkg/connector/xessenger_login_test.go @@ -0,0 +1,230 @@ +package connector + +import ( + "context" + "database/sql" + "encoding/json" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + _ "github.com/mattn/go-sqlite3" + "github.com/rs/zerolog" + "go.mau.fi/mautrix-whatsapp/pkg/waid" + "go.mau.fi/util/dbutil" + "maunium.net/go/mautrix/bridgev2" + "maunium.net/go/mautrix/bridgev2/bridgeconfig" + "maunium.net/go/mautrix/bridgev2/database" + "maunium.net/go/mautrix/bridgev2/status" +) + +type ownerTestMatrix struct{ bridgev2.MatrixConnector } + +func (*ownerTestMatrix) Init(*bridgev2.Bridge) {} +func (*ownerTestMatrix) BotIntent() bridgev2.MatrixAPI { return nil } + +func (*ownerTestMatrix) SendBridgeStatus(context.Context, *status.BridgeState) error { + return nil +} + +type ownerTestClient struct { + bridgev2.NetworkAPI + disconnects int +} + +func (c *ownerTestClient) Disconnect() { c.disconnects++ } + +type ownerTestNetwork struct{ WhatsAppConnector } + +func (*ownerTestNetwork) Init(*bridgev2.Bridge) {} +func (*ownerTestNetwork) LoadUserLogin(_ context.Context, ul *bridgev2.UserLogin) error { + ul.Client = &ownerTestClient{} + return nil +} + +func ownerTestBridge(t *testing.T) *bridgev2.Bridge { + t.Helper() + raw, err := sql.Open("sqlite3", "file:"+filepath.Join(t.TempDir(), "bridge.db")+"?_foreign_keys=on") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { raw.Close() }) + db, err := dbutil.NewWithDB(raw, "sqlite3") + if err != nil { + t.Fatal(err) + } + br := bridgev2.NewBridge("", db, zerolog.Nop(), &bridgeconfig.BridgeConfig{SplitPortals: true}, &ownerTestMatrix{}, &ownerTestNetwork{}, func(*bridgev2.Bridge) bridgev2.CommandProcessor { return nil }) + br.BackgroundCtx = context.Background() + if err = br.DB.Upgrade(context.Background()); err != nil { + t.Fatal(err) + } + return br +} + +// reportState is a login's client reporting a state. Waits until the state has been delivered. +func reportState(t *testing.T, login *bridgev2.UserLogin, state status.BridgeState) { + t.Helper() + login.BridgeState.Send(state) + for range 2000 { + if prev := login.BridgeState.GetPrev(); prev.StateEvent == state.StateEvent && prev.Error == state.Error { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("state %s was not delivered", state.StateEvent) +} + +// accountInUseBody is what the provisioning API writes for err. The holder's Matrix user never +// appears in it. +func accountInUseBody(t *testing.T, err error) map[string]any { + t.Helper() + resp, ok := err.(bridgev2.RespError) + if !ok { + t.Fatalf("error = %v, want a RespError", err) + } + rec := httptest.NewRecorder() + resp.Write(rec) + if rec.Code != 409 { + t.Fatalf("status = %d, want 409", rec.Code) + } + if strings.Contains(rec.Body.String(), "@a:fixture") { + t.Fatalf("answer names the holder: %s", rec.Body.String()) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + return body +} + +func TestXessengerSecondWorkspaceLinksToWhatsAppConnection(t *testing.T) { + ctx := context.Background() + br := ownerTestBridge(t) + a, _ := br.GetUserByMXID(ctx, "@a:fixture") + b, _ := br.GetUserByMXID(ctx, "@b:fixture") + data := func() *database.UserLogin { + return &database.UserLogin{ID: "821012345678", Metadata: &waid.UserLoginMetadata{}} + } + first, err := xessengerNewLogin(ctx, a, data(), &bridgev2.NewLoginParams{DeleteOnConflict: true}) + if err != nil { + t.Fatal(err) + } + + // Another workspace that paired the same account is answered with the existing login. The login + // has reported no state yet, as after a bridge restart: it is not treated as lost. + _, err = xessengerNewLogin(ctx, b, data(), &bridgev2.NewLoginParams{DeleteOnConflict: true}) + body := accountInUseBody(t, err) + if body["errcode"] != "M_ACCOUNT_IN_USE" || body["com.xessenger.login_id"] != string(first.ID) { + t.Fatalf("body = %v", body) + } + persisted, err := br.DB.UserLogin.GetByID(ctx, first.ID) + if err != nil || persisted == nil || persisted.UserMXID != a.MXID { + t.Fatal("original owner lost the connection", err) + } + + // The holder's own re-login reuses its login. + again, err := xessengerNewLogin(ctx, a, data(), &bridgev2.NewLoginParams{}) + if err != nil || again != first { + t.Fatal("same owner cannot reconnect", err) + } + + first.Delete(ctx, status.BridgeState{}, bridgev2.DeleteOpts{BlockingCleanup: true}) + moved, err := xessengerNewLogin(ctx, b, data(), &bridgev2.NewLoginParams{}) + if err != nil { + t.Fatal("explicit disconnect did not release connection", err) + } + moved.BridgeState.Destroy() +} + +func TestXessengerLostSessionGoesToExistingConnection(t *testing.T) { + ctx := context.Background() + br := ownerTestBridge(t) + a, _ := br.GetUserByMXID(ctx, "@a:fixture") + b, _ := br.GetUserByMXID(ctx, "@b:fixture") + c, _ := br.GetUserByMXID(ctx, "@c:fixture") + const id = "821012345678" + signIn := func(user *bridgev2.User, device uint16) (*bridgev2.UserLogin, error) { + return xessengerNewLogin(ctx, user, &database.UserLogin{ID: id, Metadata: &waid.UserLoginMetadata{WADeviceID: device}}, &bridgev2.NewLoginParams{}) + } + first, err := signIn(a, 1) + if err != nil { + t.Fatal(err) + } + defer first.Delete(ctx, status.BridgeState{}, bridgev2.DeleteOpts{BlockingCleanup: true}) + device := func() uint16 { return first.Metadata.(*waid.UserLoginMetadata).WADeviceID } + + // A working or banned connection is left alone: the caller unlinks the new device. + for _, state := range []status.BridgeState{ + {StateEvent: status.StateConnected}, + {StateEvent: status.StateTransientDisconnect}, + {StateEvent: status.StateUnknownError}, + {StateEvent: status.StateBadCredentials, Error: WATemporaryBan}, + } { + reportState(t, first, state) + _, err = signIn(b, 9) + if body := accountInUseBody(t, err); body["com.xessenger.login_id"] != id { + t.Fatalf("%s: body = %v", state.StateEvent, body) + } + if device() != 1 { + t.Fatalf("%s: the connection took a new device", state.StateEvent) + } + } + + // Logged out from the phone: the new device goes to the holder's login, and this answer is no + // 409, so the caller doesn't unlink it. The old client stops. + old := first.Client.(*ownerTestClient) + reportState(t, first, status.BridgeState{StateEvent: status.StateBadCredentials, Error: WALoggedOut}) + login, err := signIn(b, 2) + if err != nil || login != first { + t.Fatal("the dead login did not take the new device", err) + } + if login.UserMXID != a.MXID || len(b.GetUserLogins()) != 0 { + t.Fatal("the login changed hands") + } + if device() != 2 || old.disconnects != 1 || first.Client == bridgev2.NetworkAPI(old) { + t.Fatalf("device = %d, disconnects = %d", device(), old.disconnects) + } + if saved, err := br.DB.UserLogin.GetByID(ctx, id); err != nil || saved.UserMXID != a.MXID || saved.Metadata.(*waid.UserLoginMetadata).WADeviceID != 2 { + t.Fatal("the saved login is not the holder's with the new device", err) + } + + // It is no longer dead, so the next sign-in only links. + _, err = signIn(c, 3) + if body := accountInUseBody(t, err); body["com.xessenger.login_id"] != id { + t.Fatalf("body = %v", body) + } + if device() != 2 { + t.Fatal("a second sign-in replaced the device") + } + + // Logged out counts too. The holder's own re-login still goes through. + reportState(t, first, status.BridgeState{StateEvent: status.StateLoggedOut}) + if login, err = signIn(c, 4); err != nil || login != first || device() != 4 { + t.Fatal("logged-out login did not take the device", err) + } + if login, err = signIn(a, 5); err != nil || login != first || device() != 5 { + t.Fatal("holder re-login failed", err) + } + + // Of two pairings at the same moment, one takes the session and the other only links. + reportState(t, first, status.BridgeState{StateEvent: status.StateBadCredentials, Error: WALoggedOut}) + results := make(chan error, 2) + for _, user := range []*bridgev2.User{b, c} { + go func() { + _, err := signIn(user, 6) + results <- err + }() + } + refused := 0 + for range 2 { + if err := <-results; err != nil { + accountInUseBody(t, err) + refused++ + } + } + if refused != 1 || device() != 6 { + t.Fatalf("refused = %d, device = %d", refused, device()) + } +}