From 7ae1b9e22e8a616c3f53eb22f362541274995279 Mon Sep 17 00:00:00 2001 From: unRekable Date: Sat, 5 Dec 2026 15:22:15 +0100 Subject: [PATCH] Tell the person when signing out of Google Messages may leave this computer listed on the phone --- crates/chatd/src/adapters/messages.rs | 20 +- crates/chatd/src/adapters/messages/fake.rs | 17 +- crates/chatd/src/server.rs | 15 +- crates/chatd/tests/messages.rs | 88 +++--- crates/protocol/src/lib.rs | 19 ++ .../tinyclient/src/gui/settings/accounts.rs | 20 +- crates/tinyclient/src/gui/shot_demo.rs | 1 + crates/tinyclient/src/gui/state.rs | 53 +++- docs/architecture.md | 4 +- .../messages-sign-out-notice/drive.linux.sh | 9 + .../messages-sign-out-notice/drive.macos.sh | 9 + .../messages-sign-out-notice/drive.py | 255 ++++++++++++++++++ .../drive.windows.ps1 | 17 ++ .../messages-sign-out-notice/scenario.json | 12 + 14 files changed, 494 insertions(+), 45 deletions(-) create mode 100644 e2e/scenarios/messages-sign-out-notice/drive.linux.sh create mode 100644 e2e/scenarios/messages-sign-out-notice/drive.macos.sh create mode 100644 e2e/scenarios/messages-sign-out-notice/drive.py create mode 100644 e2e/scenarios/messages-sign-out-notice/drive.windows.ps1 create mode 100644 e2e/scenarios/messages-sign-out-notice/scenario.json diff --git a/crates/chatd/src/adapters/messages.rs b/crates/chatd/src/adapters/messages.rs index 067abacf..e876c97f 100644 --- a/crates/chatd/src/adapters/messages.rs +++ b/crates/chatd/src/adapters/messages.rs @@ -286,10 +286,17 @@ impl Drive for LiveDrive { } } -/// Said when sign-out cannot reach the phone, so this computer may stay in its paired-device list. +/// Said when a sign-out could not ask the phone to drop this computer: it cannot reach the +/// phone, or the pairing has nothing to unpair with. pub const STILL_LISTED: &str = "This computer may still be listed under Device pairing on your phone. Remove it there."; +/// The answer to a sign-out that could not ask the phone to drop this computer. Why is for the +/// log: the person is signing out, and the one thing they can do about it is on the phone. +fn still_listed() -> Refusal { + Refusal::Refused(STILL_LISTED.to_owned()) +} + fn parse(session: &str) -> Result { let saved: Saved = serde_json::from_str(session) .map_err(|_| "the Messages session is unreadable".to_owned())?; @@ -937,7 +944,7 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<() fake::record(STILL_LISTED); } tracing::warn!("chatd: Messages: {STILL_LISTED}"); - let _ = reply.send(Err(Refusal::Refused(STILL_LISTED.to_owned()))); + let _ = reply.send(Err(still_listed())); } (None, command) => offline(&ctx, command), }, @@ -2757,11 +2764,14 @@ fn serve(account: &Arc, command: Command) { let _ = reply.send(url.ok_or(Refusal::Unsupported)); } Command::SignOut(reply) => { - if let Err(why) = account.drive.unpair() { + // Signed out here whatever the phone said. When it could not be asked to drop this + // computer, the answer says so for the person: the phone may still list it. + let unpaired = account.drive.unpair().map_err(|why| { tracing::warn!("chatd: Messages: {why}"); - } + still_listed() + }); account.drive.close(); - let _ = reply.send(Ok(())); + let _ = reply.send(unpaired); } Command::SetMute { conversation_id, diff --git a/crates/chatd/src/adapters/messages/fake.rs b/crates/chatd/src/adapters/messages/fake.rs index 0f3c83c0..76dd9857 100644 --- a/crates/chatd/src/adapters/messages/fake.rs +++ b/crates/chatd/src/adapters/messages/fake.rs @@ -10,12 +10,12 @@ //! `revoke`, `revoke-offline`, `auth`. //! `archive` files the chat as archived. `spam` files it as spam. `again` repeats the //! chat with a new title and no status, which must keep the folder it already had. -//! `silent` makes the phone stop answering sends, history, and files. `answer` clears that -//! and tells the adapter the phone is back. +//! `silent` makes the phone stop answering sends, history, files and an unpair. `answer` clears +//! that and tells the adapter the phone is back. //! `hold` pauses a file upload until `go`, so a cancel can land while it is still unsent. //! WHO is `grace` or `alan`. `status` reports that code on the last text this computer sent. -use super::{Drive, Event, Saved}; +use super::{Drive, Event, Saved, STILL_LISTED}; use crate::adapters::messages::bugle::{Chat, ContactEntry, Mark, MediaPart, Note, Participant, Piece, MESSAGE_PAGE, PHONE_QUIET, UNPAIRED}; use crate::adapters::script; use std::io::Write; @@ -71,10 +71,12 @@ pub struct Fake { last: Arc>>, /// A scripted upload waits while this is set (`hold` / `go` on `messages.ctl`). hold: Arc, + /// The saved session's pairing attempt, empty for a QR pairing. + pairing_id: String, } impl Fake { - pub fn open(_saved: &Saved) -> Fake { + pub fn open(saved: &Saved) -> Fake { let revoked = protocol::support_dir().join("messages.revoked"); if revoked.is_file() { let _ = std::fs::remove_file(&revoked); @@ -90,6 +92,7 @@ impl Fake { sent: AtomicU32::new(0), last: Arc::default(), hold: Arc::default(), + pairing_id: saved.pairing_id.clone(), }; } let (events, heard) = channel(); @@ -177,6 +180,7 @@ impl Fake { sent: AtomicU32::new(0), last: Arc::default(), hold: Arc::default(), + pairing_id: saved.pairing_id.clone(), }; let (events, closed, refuse, quiet, last, hold) = ( fake.events.clone(), @@ -1377,7 +1381,12 @@ impl Drive for Fake { record(&format!("delete-chat {conversation}")); Ok(()) } + /// The real drive's rule: a QR pairing has no attempt to revoke, so nothing is asked. fn unpair(&self) -> Result<(), String> { + if self.pairing_id.is_empty() { + return Err(STILL_LISTED.to_owned()); + } + self.unanswered()?; record("unpair"); Ok(()) } diff --git a/crates/chatd/src/server.rs b/crates/chatd/src/server.rs index ff692b2c..50376aba 100644 --- a/crates/chatd/src/server.rs +++ b/crates/chatd/src/server.rs @@ -836,6 +836,11 @@ impl Chat { } fn status(&self) -> Response { + self.status_saying("") + } + + /// The status, with `notice` as the one thing to tell the person about the request it answers. + fn status_saying(&self, notice: &str) -> Response { let (call, running) = self.hub.calls.describe(); let links = self.hub.links(); let keychain = self.hub.keychain(); @@ -907,6 +912,7 @@ impl Chat { keychain, started: self.hub.started, session: protocol::log_policy::session_id().to_owned(), + notice: notice.to_owned(), } } @@ -4151,11 +4157,16 @@ impl Chat { // Taken out of the map first, so nothing else is asked of it; kept until it has had // its time to end the session on the network, since dropping it stops its threads. let adapter = lock(&self.adapters).remove(&account); + // What the network would not do, in words for the person. The account is signed out + // either way, so it rides on the answer instead of failing the request. + let mut notice = String::new(); if let Some(adapter) = adapter { let (reply, done) = channel(); adapter.command(Command::SignOut(reply)); // Answered, or dropped unanswered by an adapter with nothing to end, or too slow. - let _ = done.recv_timeout(SIGN_OUT); + if let Ok(Err(Refusal::Refused(words))) = done.recv_timeout(SIGN_OUT) { + notice = words; + } } let stored = match session::read(account.network) { session::Stored::Found(session) => Some(session), @@ -4188,7 +4199,7 @@ impl Chat { self.forget(&account); self.hub.set_link(&account, Link::SignedOut, ""); self.hub.changed(Change::Status); - self.status() + self.status_saying(¬ice) } /// A device transfer moved this account to another device: it is forgotten here without diff --git a/crates/chatd/tests/messages.rs b/crates/chatd/tests/messages.rs index a09e5993..a90a27cd 100644 --- a/crates/chatd/tests/messages.rs +++ b/crates/chatd/tests/messages.rs @@ -20,6 +20,11 @@ const GRACE: &str = "phone-grace"; const ALAN: &str = "phone-alan"; const CLUB: &str = "phone-club"; const SESSION: &str = r#"{"account":"phone-ada","name":"Ada Quill"}"#; +/// The same account paired through its Google account, which names a pairing attempt to revoke. +/// `SESSION` alone is a QR pairing, which has none. +const GOOGLE_SESSION: &str = r#"{"account":"phone-ada","name":"Ada Quill","pairing_id":"attempt-1"}"#; +/// What a sign-out says when the phone was not asked to drop this computer. +const STILL_LISTED: &str = "This computer may still be listed under Device pairing on your phone. Remove it there."; fn key(id: &str) -> Key { Key { @@ -46,6 +51,11 @@ impl World { World::start(Some(SESSION)) } + /// Paired through the Google account, so a sign-out has a pairing attempt to revoke. + fn google() -> World { + World::start(Some(GOOGLE_SESSION)) + } + /// A scripted conversation of 100 messages, so a scroll can ask for the pages under the newest. fn many() -> World { World::open(Some(SESSION), true, false) @@ -304,6 +314,26 @@ impl World { } } + /// Signs the account out and answers with what the answer tells the person: empty when the + /// phone was asked to drop this computer, a sentence when it was not. + fn sign_out(&self) -> String { + match self.ask(Request::SignOut { + account: account(), + erase: false, + }) { + Response::Status { accounts, notice, .. } => { + assert!( + accounts + .iter() + .all(|status| status.key != account() || status.link != Link::Connected), + "{accounts:?}" + ); + notice + } + other => panic!("{other:?}"), + } + } + fn changed( &self, mut since: u64, @@ -1489,22 +1519,10 @@ fn three_texts_count_as_three_and_a_chat_read_on_the_phone_clears() { #[test] fn signing_out_asks_the_phone_to_drop_this_computer_once() { - let world = World::linked(); + let world = World::google(); world.connected(); - match world.ask(Request::SignOut { - account: account(), - erase: false, - }) { - Response::Status { accounts, .. } => { - assert!( - accounts - .iter() - .all(|status| status.key != account() || status.link != Link::Connected), - "{accounts:?}" - ); - } - other => panic!("{other:?}"), - } + // Asked and answered: there is nothing to tell the person. + assert_eq!(world.sign_out(), ""); world.heard("unpair"); assert_eq!( world.calls().iter().filter(|call| *call == "unpair").count(), @@ -1517,25 +1535,33 @@ fn signing_out_offline_says_the_phone_may_still_list_this_computer() { let world = World::offline_phone(); // The socket answers before the account's threads exist. Wait until the phone is unreachable. world.heard("offline"); - match world.ask(Request::SignOut { - account: account(), - erase: false, - }) { - Response::Status { accounts, .. } => { - assert!( - accounts - .iter() - .all(|status| status.key != account() || status.link != Link::Connected), - "{accounts:?}" - ); - } - other => panic!("{other:?}"), - } - world.heard( - "This computer may still be listed under Device pairing on your phone. Remove it there.", + assert_eq!(world.sign_out(), STILL_LISTED); + world.heard(STILL_LISTED); +} + +#[test] +fn signing_out_a_qr_pairing_says_the_phone_may_still_list_this_computer() { + // Paired by QR code: there is no pairing attempt to revoke, so the phone is never asked. + let world = World::linked(); + world.connected(); + assert_eq!(world.sign_out(), STILL_LISTED); + assert!( + !world.calls().iter().any(|call| call == "unpair"), + "the phone was asked: {:#?}", + world.calls() ); } +#[test] +fn signing_out_to_a_phone_that_does_not_answer_says_the_phone_may_still_list_this_computer() { + let world = World::google(); + world.connected(); + // The phone stops answering, as one that is off or out of reach does. + world.steer("silent"); + world.heard("silent"); + assert_eq!(world.sign_out(), STILL_LISTED); +} + #[test] fn a_video_is_a_video_and_a_voice_note_has_a_waveform() { chatd::adapters::messages::prove_message_media().expect("a video and a voice note"); diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 9db39429..fd464ab7 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -3303,6 +3303,8 @@ pub enum Request { /// Forgets the account's session and everything stored for it. Waits up to 5 s for the /// network to end the session first. A Tiny server's encrypted history stays on this device /// (sealed, its key in the keychain) for a later sign-in there, unless `erase` is set. + /// The account is signed out whatever the network said; when it could not be told, the + /// answer's `notice` says so. SignOut { account: AccountKey, #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -4962,6 +4964,11 @@ pub enum Response { /// Shared by the window, chatd, and mediad for this run. Empty on an older chatd. #[serde(default, skip_serializing_if = "String::is_empty")] session: String, + /// Something the person should know about the request this answers, in words. A sign-out + /// sets it when the network could not be told to end the session, so it may still list + /// this device. Empty on every other answer. + #[serde(default, skip_serializing_if = "String::is_empty")] + notice: String, }, Changes { /// Pass this to the next `Wait`. @@ -5802,6 +5809,18 @@ mod tests { assert_eq!(serde_json::to_value(pending).unwrap()["pending"], true); } + #[test] + fn a_status_notice_is_explicit_and_old_status_answers_still_decode() { + let mut value = serde_json::json!({"op": "status", "networks": [], "accounts": [], "media": "stopped", "call": null, "seq": 3}); + let quiet: super::Response = serde_json::from_value(value.clone()).unwrap(); + assert!(matches!(quiet, super::Response::Status { ref notice, .. } if notice.is_empty())); + assert!(serde_json::to_value(quiet).unwrap().get("notice").is_none()); + value["notice"] = serde_json::json!("Remove it there."); + let said: super::Response = serde_json::from_value(value).unwrap(); + assert!(matches!(said, super::Response::Status { ref notice, .. } if notice.as_str() == "Remove it there.")); + assert_eq!(serde_json::to_value(said).unwrap()["notice"], "Remove it there."); + } + use super::*; fn row(kind: ConversationKind, unread: u32, mentions: u32, muted: bool) -> Conversation { diff --git a/crates/tinyclient/src/gui/settings/accounts.rs b/crates/tinyclient/src/gui/settings/accounts.rs index c1dd0fc9..9aefd971 100644 --- a/crates/tinyclient/src/gui/settings/accounts.rs +++ b/crates/tinyclient/src/gui/settings/accounts.rs @@ -241,7 +241,7 @@ impl SettingsWindow { }; let shell = shell.read(cx); let accounts = shell.snapshot.as_ref().map(|s| s.accounts.clone()).unwrap_or_default(); - let (signing_in, failed) = (shell.signing_in, shell.sign_in_failed.clone()); + let (signing_in, failed, said) = (shell.signing_in, shell.sign_in_failed.clone(), shell.sign_out_said.clone()); let mut tiny_line = None; let mut pane = div().flex().flex_col().gap(px(20.)).child(self.devices_card(cx)); for network in NETWORK_ORDER { @@ -360,6 +360,18 @@ impl SettingsWindow { .children(failed.as_ref().filter(|(at, _)| *at == network).map(|(_, words)| { div().pt(px(6.)).px(px(super::controls::side())).type_small().text_color(theme::danger()).child(words.clone()) })) + // The account is gone, but the network could not be told: chatd's words stay + // here until dismissed (08 §6). + .children(said.iter().find(|(at, _)| *at == network).map(|(_, words)| { + div() + .pt(px(6.)) + .px(px(super::controls::side())) + .flex() + .items_start() + .gap(px(8.)) + .child(div().flex_1().min_w_0().type_small().text_color(theme::text()).child(words.clone())) + .child(button(("sign-out-said", network as usize), ButtonKind::Ghost, "Dismiss").on_click(cx.listener(move |this, _, _, cx| this.dismiss_sign_out_said(network, cx)))) + })) .children(tiny_line.take()), ); } @@ -1549,6 +1561,12 @@ impl SettingsWindow { cx.notify(); } + /// Puts away the line a sign-out left under `network`. + fn dismiss_sign_out_said(&mut self, network: Network, cx: &mut Context) { + let _ = self.shell.update(cx, |shell, cx| shell.dismiss_sign_out_said(network, cx)); + cx.notify(); + } + /// The sign-out question (§6), over the whole window. pub(super) fn sign_out_modal(&self, account: &AccountStatus, cx: &mut Context) -> gpui::AnyElement { let network = network_name(account.key.network); diff --git a/crates/tinyclient/src/gui/shot_demo.rs b/crates/tinyclient/src/gui/shot_demo.rs index 77aa8d50..5ba510d8 100644 --- a/crates/tinyclient/src/gui/shot_demo.rs +++ b/crates/tinyclient/src/gui/shot_demo.rs @@ -1123,6 +1123,7 @@ pub fn answer(request: &Request) -> std::io::Result { started: 1, // No session: a shot starts nothing that would share it. session: String::new(), + notice: String::new(), }, // Nothing ever changes: the wait runs out and is asked again, as a quiet chatd's does. // The loopback call changes by itself (its picture, its clock): say so a few times a second diff --git a/crates/tinyclient/src/gui/state.rs b/crates/tinyclient/src/gui/state.rs index c7436862..da0c2d7e 100644 --- a/crates/tinyclient/src/gui/state.rs +++ b/crates/tinyclient/src/gui/state.rs @@ -213,6 +213,9 @@ pub struct Shell { pub(super) signing_in: Option, /// What chatd said about the last sign-in that did not finish. pub(super) sign_in_failed: Option<(Network, String)>, + /// What chatd said when an account of a network was signed out: the network could not be + /// told to end the session (08 §6). One line a network, kept until dismissed. + pub(super) sign_out_said: Vec<(Network, String)>, pub(super) open: Option, /// The window is the one the user is working in. Only then is what is open read. pub(super) active: bool, @@ -321,6 +324,7 @@ impl Shell { refused: None, signing_in: None, sign_in_failed: None, + sign_out_said: Vec::new(), open: None, active: window.is_window_active(), spaces: Vec::new(), @@ -1287,12 +1291,33 @@ impl Shell { } self.sync_popout_composers(cx); } + let network = account.network; let request = Request::SignOut { account, erase }; - self.off_thread(cx, move || ask(&request), |this, _, cx| { + self.off_thread(cx, move || ask(&request), move |this, answer, cx| { + // Signed out either way; the status read below shows that. + if let Some(words) = sign_out_notice(&answer) { + this.sign_out_said.retain(|(at, _)| *at != network); + this.sign_out_said.push((network, words.to_owned())); + } this.load_status(cx); this.reload_all(cx); }); } + + /// Puts away what chatd said about a sign-out of `network`. + pub(super) fn dismiss_sign_out_said(&mut self, network: Network, cx: &mut Context) { + self.sign_out_said.retain(|(at, _)| *at != network); + cx.notify(); + } +} + +/// What a sign-out's answer has to tell the person: the notice chatd wrote, when it wrote one. +/// chatd alone knows whether the network could be told to end the session; the window shows it. +fn sign_out_notice(answer: &io::Result) -> Option<&str> { + match answer { + Ok(Response::Status { notice, .. }) if !notice.is_empty() => Some(notice), + _ => None, + } } /// The open conversation's row follows who is in it when that is all that changed: the header's @@ -1349,6 +1374,32 @@ mod tests { assert!(!following(&mut none, &channel, &two)); } + #[test] + fn only_a_sign_out_that_chatd_wrote_a_notice_for_has_something_to_say() { + let status = |notice: &str| -> io::Result { + Ok(Response::Status { + networks: Vec::new(), + accounts: Vec::new(), + media: protocol::Media::Stopped, + call: None, + ring: None, + seq: 1, + keychain: protocol::Keychain::default(), + started: 1, + session: String::new(), + notice: notice.to_owned(), + }) + }; + // The phone took the unpair: nothing to say. + assert_eq!(sign_out_notice(&status("")), None); + // It could not be asked: chatd's words, and nothing of the window's own. + assert_eq!(sign_out_notice(&status("Remove it there.")), Some("Remove it there.")); + let other = Ok(Response::Ok); + assert_eq!(sign_out_notice(&other), None); + let failed: io::Result = Err(io::Error::other("down")); + assert_eq!(sign_out_notice(&failed), None); + } + #[test] fn each_change_names_only_what_it_touched() { let account = key("").account(); diff --git a/docs/architecture.md b/docs/architecture.md index 846ea8fd..5af43c7b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -144,7 +144,9 @@ for the network, one account per server, and `TinyLocalServers` reads those orig `--at X,Y`. The helper's exit says how it ended: 1 the window was closed (`SignIn`), 3 the page could not load (`SignInUnreachable`), 4 the organization blocks it (`SignInBlocked`). `SignOut` sends `Command::SignOut(reply)` and waits up to 5 s for the adapter to end the session on the - network before it drops the adapter and forgets the account. A session part a network reissues + network before it drops the adapter and forgets the account. An adapter that could not end the + session answers `Refusal::Refused` with words for the person: the account is forgotten all the + same, and the words ride on the answer as `Status.notice`. A session part a network reissues while in use (Slack's rotated `d` cookie) is saved with `Context::save_session`. - **Tiny server sign-in** is the sheet's (`SignInBegin`, `SignInAnswer`), and it ends in the system browser, not in `tinyclient-login`: chatd reads the server's provider diff --git a/e2e/scenarios/messages-sign-out-notice/drive.linux.sh b/e2e/scenarios/messages-sign-out-notice/drive.linux.sh new file mode 100644 index 00000000..168c161d --- /dev/null +++ b/e2e/scenarios/messages-sign-out-notice/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# messages-sign-out-notice on Linux. The lab runs this with bash while ffmpeg films the display. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/messages-sign-out-notice/drive.macos.sh b/e2e/scenarios/messages-sign-out-notice/drive.macos.sh new file mode 100644 index 00000000..8d873661 --- /dev/null +++ b/e2e/scenarios/messages-sign-out-notice/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# messages-sign-out-notice on macOS. The lab runs this with bash while the display is filmed. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +if command -v python3 >/dev/null 2>&1; then + exec python3 "$HERE/drive.py" +fi +echo "python3 is not on PATH" >&2 +exit 1 diff --git a/e2e/scenarios/messages-sign-out-notice/drive.py b/e2e/scenarios/messages-sign-out-notice/drive.py new file mode 100644 index 00000000..311a1b5a --- /dev/null +++ b/e2e/scenarios/messages-sign-out-notice/drive.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Signing out of Google Messages says when the phone may still list this computer. + +Starts this build's chatd with the scripted Messages phone (TINYCLIENT_MESSAGES_FAKE), steers it +over its control file the way tests/messages.rs does, and speaks chatd's real socket. A QR +pairing has no pairing attempt to revoke, a phone that stopped answering never takes the +request, and with Messages unreachable nothing is sent: each of those sign-outs has to carry the +sentence that tells the person to remove this computer under Device pairing on the phone. A +sign-out the phone answers carries nothing. A build from before the fix drops what the adapter +answered, so none of its sign-outs carries the sentence and this driver fails there. + +Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR. +""" + +import json +import os +import socket +import struct +import subprocess +import sys +import time + +OUT = os.environ.get("E2E_OUT", "") +T0 = float(os.environ.get("E2E_T0") or time.time()) +APP = os.environ.get("E2E_APP_DIR", "") + +ME = "phone-ada" +ACCOUNT = {"network": "messages", "account": ME} +# Paired by QR code: no Google account, so no pairing attempt to revoke. +QR_SESSION = json.dumps({"account": ME, "name": "Ada Quill"}) +# Paired through the Google account: the saved session names the pairing attempt. +GOOGLE_SESSION = json.dumps({"account": ME, "name": "Ada Quill", "pairing_id": "attempt-1"}) +STILL_LISTED = "This computer may still be listed under Device pairing on your phone. Remove it there." + +FAILED = False +STEPS = "" + + +def now(): + return time.time() - T0 + + +def step(words, ok): + global FAILED + if not ok: + FAILED = True + line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false") + print(("[ok] " if ok else "[FAILED] ") + words, flush=True) + if STEPS: + with open(STEPS, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def app_bin(app_dir): + name = "chatd.exe" if sys.platform == "win32" else "chatd" + if sys.platform == "darwin" and app_dir.endswith(".app"): + return os.path.join(app_dir, "Contents", "MacOS", "chatd") + return os.path.join(app_dir, name) + + +def connect(sock_path): + """chatd's socket: a file on Unix, the matching named pipe on Windows.""" + if sys.platform == "win32": + return open("\\\\.\\pipe\\" + sock_path, "r+b", buffering=0) + stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + stream.settimeout(5) + stream.connect(sock_path) + return stream + + +def write_all(stream, data): + view = memoryview(data) + while view: + written = stream.write(view) + if not written: + raise RuntimeError("chatd's socket took nothing") + view = view[written:] + + +class Chat: + def __init__(self, sock_path): + self.stream = connect(sock_path) + + def ask(self, request): + body = json.dumps(request, separators=(",", ":")).encode() + write_all(self.stream, struct.pack("!I", len(body)) + body) + head = b"" + while len(head) < 4: + got = self.stream.read(4 - len(head)) + if not got: + raise RuntimeError("chatd closed its socket") + head += got + length = struct.unpack("!I", head)[0] + if length > 1024 * 1024: + raise RuntimeError("answer exceeds the protocol size limit") + chunks = b"" + while len(chunks) < length: + got = self.stream.read(length - len(chunks)) + if not got: + raise RuntimeError("chatd closed its socket mid-frame") + chunks += got + return json.loads(chunks) + + def close(self): + try: + self.stream.close() + except OSError: + pass + + +def main(): + global STEPS + if not OUT or not APP: + print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr) + return 1 + os.makedirs(OUT, exist_ok=True) + STEPS = os.path.join(OUT, "steps.jsonl") + open(STEPS, "w", encoding="utf-8").close() + binary = app_bin(APP) + if not os.path.isfile(binary): + step("chatd is in E2E_APP_DIR", False) + return 1 + + # One sign-out forgets the whole saved session, so every case starts its own chatd. + said = sign_out(binary, "qr-pairing", QR_SESSION) + step("a QR pairing is signed out and told the phone may still list this computer", said == STILL_LISTED) + said = sign_out(binary, "phone-quiet", GOOGLE_SESSION, quiet=True) + step("a phone that does not answer leaves the sign-out told the phone may still list this computer", said == STILL_LISTED) + said = sign_out(binary, "messages-offline", QR_SESSION, offline=True) + step("Messages unreachable leaves the sign-out told the phone may still list this computer", said == STILL_LISTED) + said = sign_out(binary, "phone-answered", GOOGLE_SESSION) + step("a phone that takes the unpair leaves nothing to tell", said == "") + return 1 if FAILED else 0 + + +def sign_out(binary, case, session, quiet=False, offline=False): + """One chatd on a fresh directory, one sign-out. Answers what the sign-out told the person, + or None when chatd never got that far.""" + data = os.path.join(OUT, case) + os.makedirs(data, exist_ok=True) + env = os.environ.copy() + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_MESSAGES_FAKE"] = "1" + env["TINYCLIENT_SESSION_MESSAGES"] = session + env.pop("TINYCLIENT_MESSAGES_OFFLINE", None) + env.pop("TINYCLIENT_MESSAGES_RELAY", None) + env.pop("TINYCLIENT_MESSAGES_QR_TTL_MS", None) + if offline: + env["TINYCLIENT_MESSAGES_OFFLINE"] = "1" + for other in ("DISCORD", "SLACK", "TELEGRAM", "TEAMS", "SIGNAL"): + env.pop("TINYCLIENT_SESSION_" + other, None) + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + with open(os.path.join(OUT, case + "-chatd.out.log"), "w", encoding="utf-8") as out, open( + os.path.join(OUT, case + "-chatd.err.log"), "w", encoding="utf-8" + ) as err: + kwargs["stdout"] = out + kwargs["stderr"] = err + proc = subprocess.Popen([binary], **kwargs) + chat = None + try: + deadline = time.time() + 15 + while chat is None: + if proc.poll() is not None: + step("chatd stays up for the driver", False) + return None + if time.time() > deadline: + step("chatd opens its socket", False) + return None + try: + chat = Chat(os.path.join(data, "chat.sock")) + except OSError: + time.sleep(0.1) + return drive(chat, data, quiet, offline) + finally: + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + + +def wait(what, chat, look, seconds=20): + deadline = time.time() + seconds + while time.time() < deadline: + found = look() + if found is not None: + step(what, True) + return found + time.sleep(0.2) + step(what, False) + return None + + +def steer(control, line): + with open(control, "a", encoding="utf-8") as handle: + handle.write(line + "\n") + + +def read(path): + """What chatd has written to the file so far, empty until there is one.""" + try: + with open(path, encoding="utf-8") as handle: + return handle.read() + except OSError: + return "" + + +def ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def connected(chat): + answer = ask(chat, {"op": "status"}) or {} + return True if any(account.get("key") == ACCOUNT and account.get("link") == "connected" for account in answer.get("accounts", [])) else None + + +def drive(chat, data, quiet, offline): + """Gets the account into the state the case needs, signs out, and answers what chatd said.""" + if wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) is None: + return None + calls = os.path.join(data, "messages.calls") + if offline: + # The socket answers before the account's adapter is in chatd's list, and the first + # attempt to reach the phone is logged from a thread that starts before that. The second + # comes a second later, after the adapter is in the list to be asked. + if wait("Messages is unreachable", chat, lambda: read(calls).count("offline") >= 2 or None) is None: + return None + elif wait("Messages is connected", chat, lambda: connected(chat)) is None: + return None + if quiet: + control = os.path.join(data, "messages.ctl") + if wait("the scripted phone listens", chat, lambda: os.path.isfile(control) or None) is None: + return None + steer(control, "silent") + if wait("the phone stops answering", chat, lambda: "silent" in read(calls) or None) is None: + return None + + answer = ask(chat, {"op": "sign_out", "account": ACCOUNT, "erase": False}) + if not isinstance(answer, dict) or answer.get("op") != "status": + step("chatd answers a sign-out with its status", False) + return None + accounts = answer.get("accounts", []) + step("the account is signed out", all(account.get("key") != ACCOUNT or account.get("link") != "connected" for account in accounts)) + return answer.get("notice", "") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/messages-sign-out-notice/drive.windows.ps1 b/e2e/scenarios/messages-sign-out-notice/drive.windows.ps1 new file mode 100644 index 00000000..97299ffd --- /dev/null +++ b/e2e/scenarios/messages-sign-out-notice/drive.windows.ps1 @@ -0,0 +1,17 @@ +# messages-sign-out-notice on Windows. The lab runs this in the console session it is already filming. +$ErrorActionPreference = 'Stop' +$drive = Join-Path $PSScriptRoot 'drive.py' +if (Get-Command py -ErrorAction SilentlyContinue) { + & py -3 $drive + exit $LASTEXITCODE +} +if (Get-Command python -ErrorAction SilentlyContinue) { + & python $drive + exit $LASTEXITCODE +} +if (Get-Command python3 -ErrorAction SilentlyContinue) { + & python3 $drive + exit $LASTEXITCODE +} +Write-Host 'python is not on PATH (tried py -3, python, python3)' +exit 1 diff --git a/e2e/scenarios/messages-sign-out-notice/scenario.json b/e2e/scenarios/messages-sign-out-notice/scenario.json new file mode 100644 index 00000000..7080d537 --- /dev/null +++ b/e2e/scenarios/messages-sign-out-notice/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "messages-sign-out-notice", + "title": "Signing out of Google Messages says when the phone may still list this computer", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The lab's phone demo build bypasses chatd and cannot run the scripted Messages wire. The notice is the answer chatd gives a sign-out over its socket.", + "ios": "The lab's phone demo build bypasses chatd and cannot run the scripted Messages wire. The notice is the answer chatd gives a sign-out over its socket." + }, + "needs": [], + "release": false, + "max_still_seconds": 90 +}