diff --git a/crates/chatd/src/adapters/signal.rs b/crates/chatd/src/adapters/signal.rs index 02671b66..e512b152 100644 --- a/crates/chatd/src/adapters/signal.rs +++ b/crates/chatd/src/adapters/signal.rs @@ -32,8 +32,9 @@ //! # What the user did, and only that //! //! Read receipts go out when the shell says a message was read and the user's own Signal settings -//! send them; typing likewise. Both stay off until the phone has said what those settings are. -//! Nothing else is sent unasked: no reaction, edit, delete or profile change. +//! send them; typing likewise. Both stay off until the phone has said what those settings are, +//! and what it said is kept from one start to the next until it says otherwise. Nothing else is +//! sent unasked: no reaction, edit, delete or profile change. mod fake; mod files; @@ -92,6 +93,9 @@ const REACTIONS_KEPT: usize = 4_096; /// Largest reaction record file read on startup. `REACTIONS_KEPT` rows sit well below this; /// anything larger is skipped so an oversized or corrupt file is not parsed under the lock. const REACTIONS_FILE_LIMIT: u64 = 2 * 1024 * 1024; +/// Largest kept-settings file read at a start. The three switches sit far below this in JSON; +/// anything larger is not the file this adapter wrote, and is skipped. +const SETTINGS_FILE_LIMIT: u64 = 4 * 1024; /// Ballots remembered on one poll. Older ones drop off the list; the choice counts stay. const BALLOTS_KEPT: usize = 1_024; /// Signal's poll limits, from its desktop schema: a question and each choice are at most this @@ -772,9 +776,13 @@ struct Live { group_calls: HashMap, /// Pending incoming Signal group-call ring (`conversation_id`, `group_id`, `era_id`, `caller_aci`, `ring_id`). group_ring: Option, - /// The user's own Signal settings. Off until the phone says. + /// The user's own Signal settings, as the phone last shared them: off until it says, and + /// what it said is kept at `settings_path` for the next start. read_receipts: bool, typing: bool, + /// `{support}/signal/{aci}.settings`: what the phone last said of those settings. Empty when + /// nothing is kept on disk. + settings_path: PathBuf, /// File sends, by the time Signal gave them, so the phone's copy does not replace the file. echoed: VecDeque, /// Disappearing-messages timer per conversation id. @@ -946,6 +954,38 @@ struct ActiveGroupCall { } impl Live { + /// A new memory on what the adapter keeps for this account. The settings are the phone's + /// last word, so they hold from the first moment until the phone says otherwise. A start + /// with nothing kept, or a kept file that does not read, is off. + fn kept(aci: &str) -> Live { + let settings_path = settings_path(aci); + let said = read_settings(&settings_path).unwrap_or_default(); + Live { + reactions_path: reactions_path(aci), + pins_path: pins_path(aci), + stickers_path: stickers_path(aci), + attachments_path: transfer::attachments_path(aci), + settings_path, + read_receipts: said.read_receipts, + typing: said.typing, + link_previews: said.link_previews.unwrap_or(false), + ..Live::default() + } + } + + /// Takes what the phone said of the account's settings and keeps it for the next start. + /// The phone saying nothing of link previews leaves what is held, here and in the file. + fn note_settings(&mut self, said: &KeptSettings) { + self.read_receipts = said.read_receipts; + self.typing = said.typing; + if let Some(previews) = said.link_previews { + self.link_previews = previews; + } + // What is kept is what holds now, so a start from the file is as this moment is. + let held = KeptSettings { read_receipts: self.read_receipts, typing: self.typing, link_previews: Some(self.link_previews) }; + write_settings(&self.settings_path, &held); + } + fn name(&self, id: &str) -> String { if let Some(nick) = self.nicknames.get(id).filter(|s| !s.is_empty()) { return nick.clone(); @@ -1392,6 +1432,59 @@ fn write_reactions(path: &Path, order: &VecDeque<(String, String)>, book: &HashM } } +/// What the phone last said of the account's own settings, as `Event::Settings` carries them. +/// The file is this, in JSON, owned by this adapter and not by the message store. What it does +/// not say is off: unknown never sends a receipt. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +struct KeptSettings { + #[serde(default)] + read_receipts: bool, + #[serde(default)] + typing: bool, + /// None when the phone said nothing of it. + #[serde(default, skip_serializing_if = "Option::is_none")] + link_previews: Option, +} + +fn settings_path(aci: &str) -> PathBuf { + protocol::support_dir().join("signal").join(format!("{aci}.settings")) +} + +/// `None` when nothing is kept or what is there does not read. +fn read_settings(path: &Path) -> Option { + if path.as_os_str().is_empty() { + return None; + } + let Ok(meta) = std::fs::metadata(path) else { + return None; + }; + if meta.len() > SETTINGS_FILE_LIMIT { + return None; + } + let Ok(bytes) = std::fs::read(path) else { + return None; + }; + serde_json::from_slice::(&bytes).ok() +} + +fn write_settings(path: &Path, said: &KeptSettings) { + if path.as_os_str().is_empty() { + return; + } + if let Some(parent) = path.parent() { + if std::fs::create_dir_all(parent).is_err() { + return; + } + } + let Ok(bytes) = serde_json::to_vec(said) else { + return; + }; + let tmp = path.with_extension("settings.tmp"); + if std::fs::write(&tmp, &bytes).and_then(|()| std::fs::rename(&tmp, path)).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + /// The lab's signal-wave13 driver: proves mobile companion linking (#735) and linked-device /// message history transfer (#724) end-to-end against a scratch SQLite store. pub fn prove_signal_wave13() -> Result<(), String> { @@ -1527,15 +1620,10 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<() if !supported() { return Err(unsupported_reason()); } - // What is learned (names, settings, unread) outlives one connection. Reactions outlive the - // process: the file is what a later reaction replaces, once this memory is gone. - let live = Arc::new(Mutex::new(Live { - reactions_path: reactions_path(&saved.aci), - pins_path: pins_path(&saved.aci), - stickers_path: stickers_path(&saved.aci), - attachments_path: transfer::attachments_path(&saved.aci), - ..Live::default() - })); + // What is learned (names, unread) outlives one connection. The kept files outlive the + // process: a later reaction replaces against the reaction record once this memory is gone, + // and the settings are the phone's last word until it says otherwise. + let live = Arc::new(Mutex::new(Live::kept(&saved.aci))); let current: Arc>>> = Arc::default(); let (socket_ctx, held, socket_saved, socket_live) = (ctx.clone(), current.clone(), saved.clone(), live.clone()); std::thread::Builder::new() @@ -2358,19 +2446,11 @@ fn apply(account: &Account, event: Event) { } } Event::Settings { read_receipts, typing, link_previews } => { - let updated_lp = { - let mut live = account.live(); - live.read_receipts = read_receipts; - live.typing = typing; - if let Some(lp) = link_previews { - live.link_previews = lp; - Some(lp) - } else { - None - } - }; - if let Some(lp) = updated_lp { - ctx.capabilities(capabilities(lp)); + // Kept as it is taken, so the next start has the phone's word before it answers again. + let said = KeptSettings { read_receipts, typing, link_previews }; + account.live().note_settings(&said); + if let Some(previews) = said.link_previews { + ctx.capabilities(capabilities(previews)); } } Event::TimerChanged { peer, seconds, version } => { @@ -7564,6 +7644,47 @@ mod tests { assert!(read_reactions(&path).is_empty()); } + #[test] + fn kept_settings_round_trip_and_nothing_unknown_reads_as_on() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("acct.settings"); + // Nothing kept, a file that is not the settings, one too large: none of them reads, so + // a start from them is off. + assert_eq!(read_settings(&path), None); + assert_eq!(read_settings(std::path::Path::new("")), None); + std::fs::write(&path, br#"{"read_receipts":"yes"}"#).unwrap(); + assert_eq!(read_settings(&path), None); + std::fs::write(&path, vec![b' '; (SETTINGS_FILE_LIMIT as usize) + 1]).unwrap(); + assert_eq!(read_settings(&path), None); + + // The phone's word is kept as it was said, and nothing else is in the file. + let said = KeptSettings { read_receipts: true, typing: false, link_previews: Some(false) }; + write_settings(&path, &said); + assert_eq!(std::fs::read_to_string(&path).unwrap(), r#"{"read_receipts":true,"typing":false,"link_previews":false}"#); + assert_eq!(read_settings(&path), Some(said)); + assert!(!path.with_extension("settings.tmp").exists(), "the temporary file was renamed away"); + + // A file that does not say every switch, or says one this build does not know, still + // reads; what it does not say is off. + std::fs::write(&path, br#"{"typing":true,"later":1}"#).unwrap(); + assert_eq!(read_settings(&path), Some(KeptSettings { read_receipts: false, typing: true, link_previews: None })); + + // Taking the phone's word keeps it. The phone saying nothing of link previews leaves + // what is held, here and in the file, so the next start holds it too. + let mut live = Live { settings_path: path.clone(), ..Live::default() }; + live.note_settings(&KeptSettings { read_receipts: true, typing: true, link_previews: Some(true) }); + assert!(live.read_receipts && live.typing && live.link_previews); + let off = KeptSettings { read_receipts: false, typing: true, link_previews: None }; + live.note_settings(&off); + assert!(!live.read_receipts && live.typing && live.link_previews); + assert_eq!(read_settings(&path), Some(KeptSettings { read_receipts: false, typing: true, link_previews: Some(true) })); + + // A memory with no file to keep to still takes the word, and writes nothing. + let mut nowhere = Live::default(); + nowhere.note_settings(&said); + assert!(nowhere.read_receipts && !nowhere.typing && !nowhere.link_previews); + } + #[test] fn a_username_shape_is_proven() { prove_signal_username().unwrap(); diff --git a/crates/chatd/src/adapters/signal/fake.rs b/crates/chatd/src/adapters/signal/fake.rs index 2723f502..5e2d66ae 100644 --- a/crates/chatd/src/adapters/signal/fake.rs +++ b/crates/chatd/src/adapters/signal/fake.rs @@ -43,6 +43,11 @@ //! WHO is `grace` or `alan`. Every request it is sent is appended to `signal.calls`, one line //! each, so a test can see what the network would have heard. //! +//! The phone answers a device that connects with its contacts, its groups and its settings. A +//! test keeps it from answering the settings with an empty `signal.phone-away` in the scratch +//! directory, as a phone that is off: they then come only from the lines above, and chatd has to +//! go by what it kept of the phone's last word (`adapters/signal.rs`). +//! //! The account: Ada Quill (us); Grace Ombra and Alan Ferro, both contacts; the group "Bridge //! club" with all three of us in it. @@ -94,6 +99,13 @@ fn record(line: &str) { } } +/// True when a test keeps the phone from answering at this connect (`signal.phone-away` in the +/// scratch directory). Only the settings wait for it: the contacts and the groups are read from +/// the device's own memory and from the storage service. +fn phone_away() -> bool { + protocol::support_dir().join("signal.phone-away").exists() +} + #[derive(Clone)] struct FakeGroup { info: GroupInfo, @@ -230,13 +242,16 @@ pub struct Fake { impl Fake { pub fn open(_saved: &Saved) -> Fake { let (events, heard) = channel(); - // What the phone says once a device connects: its contacts, its groups, its settings. + // What the phone says once a device connects: its contacts, its groups, its settings, + // unless the test has the phone away. let grace = Contact { id: GRACE.into(), name: "Grace Ombra".into(), phone: "+15550100002".into() }; let alan = Contact { id: ALAN.into(), name: "Alan Ferro".into(), phone: String::new() }; let _ = events.send(Event::Contacts(vec![grace, alan])); let club_state = FakeGroup::initial(); let _ = events.send(Event::Groups(vec![club_state.info.clone()])); - let _ = events.send(Event::Settings { read_receipts: true, typing: true, link_previews: Some(true) }); + if !phone_away() { + let _ = events.send(Event::Settings { read_receipts: true, typing: true, link_previews: Some(true) }); + } let manifest_path = protocol::support_dir().join("signal.storage.json"); if let Ok(raw) = std::fs::read_to_string(&manifest_path) { if let Ok(snapshot) = serde_json::from_str::(&raw) { diff --git a/crates/chatd/src/adapters/signal/real.rs b/crates/chatd/src/adapters/signal/real.rs index ee7375dc..15d435d7 100644 --- a/crates/chatd/src/adapters/signal/real.rs +++ b/crates/chatd/src/adapters/signal/real.rs @@ -1013,15 +1013,27 @@ impl Session { let _ = self.events.send(event); } - /// Once per link: ask the phone for the contacts and the settings it shares with devices. + /// At every connect: ask the phone for the settings it shares with devices. What was kept of + /// its last answer (`adapters/signal.rs`) holds until this one arrives, and a link whose + /// first answer never came is not left without. The contacts are asked for once per link: + /// the phone answers with the whole list. async fn first_run(&mut self) { self.emit_sticker_packs().await; if self.vault.flag("asked") { self.tell(Event::Contacts(self.contacts().await)); + self.ask_settings().await; self.sync_storage().await; return; } let _ = self.manager.request_contacts().await; + self.ask_settings().await; + self.vault.set_flag("asked"); + self.sync_storage().await; + } + + /// Asks the phone for the account's settings: read receipts, typing, link previews. Its + /// answer is a configuration sync, which becomes `Event::Settings`. + async fn ask_settings(&mut self) { let configuration = SyncMessage { request: Some(sync_message::Request { r#type: Some(sync_message::request::Type::Configuration.into()) }), ..SyncMessage::with_padding(&mut rand::rng()) @@ -1029,8 +1041,6 @@ impl Session { if let Ok(me) = Uuid::parse_str(&self.me) { let _ = self.manager.send_message(Aci::from(me), configuration, now_ms()).await; } - self.vault.set_flag("asked"); - self.sync_storage().await; } /// Derives the account's read-only Storage Service key from the stored master key or account entropy pool. diff --git a/crates/chatd/tests/signal.rs b/crates/chatd/tests/signal.rs index 00d0e765..a44263db 100644 --- a/crates/chatd/tests/signal.rs +++ b/crates/chatd/tests/signal.rs @@ -681,6 +681,59 @@ fn typing_and_receipts_have_a_local_switch_that_stops_the_frames_here() { world.heard(&format!("typing {ALAN} started")); } +#[test] +fn the_settings_the_phone_shared_are_kept_over_a_restart() { + let mut world = World::linked(); + world.connected(); + for (at, text) in [(1, "one"), (2, "two")] { + world.steer(&format!("incoming grace {} {text}", T0 + at * 1_000)); + } + // The settings were said before either message, so they are taken before the second is stored. + world.arrived(GRACE, &id(T0 + 2_000, GRACE)); + // The phone is away at the next start and says nothing of the settings. What it said before + // is all there is, and it said on. + std::fs::write(world.dir.join("signal.phone-away"), b"").unwrap(); + world.restart(); + world.connected(); + assert_eq!(world.ask(Request::MarkRead { conversation: key(GRACE), message_id: id(T0 + 1_000, GRACE) }), Response::Ok); + world.heard(&format!("read receipts=true {}", id(T0 + 1_000, GRACE))); + world.ask(Request::Typing { conversation: key(GRACE), activity: protocol::Compose::Typing }); + world.heard(&format!("typing {GRACE} started")); + world.send(GRACE, "7381", "Tuesday, then", None); + // Read back, as the shell does: the answer to the send does not carry the note. + let ours = world.until("our message", || world.messages(GRACE).into_iter().find(|message| message.client_id.as_deref() == Some("7381") && message.id != "7381")); + assert_eq!(ours.receipt_note, ""); + // The phone is back with another word. It wins, and it is what is kept from now on. + world.steer("receipts off"); + let kept = || std::fs::read_to_string(world.dir.join("signal").join(format!("{ME}.settings"))).unwrap_or_default(); + world.until("the phone's last word kept", || kept().contains(r#""read_receipts":false"#).then_some(())); + assert_eq!(world.ask(Request::MarkRead { conversation: key(GRACE), message_id: id(T0 + 2_000, GRACE) }), Response::Ok); + world.heard(&format!("read receipts=false {}", id(T0 + 2_000, GRACE))); +} + +#[test] +fn a_phone_that_turned_the_receipts_off_is_still_off_after_a_restart() { + let mut world = World::linked(); + world.connected(); + for (at, text) in [(1, "one"), (2, "two")] { + world.steer(&format!("incoming grace {} {text}", T0 + at * 1_000)); + } + world.arrived(GRACE, &id(T0 + 2_000, GRACE)); + world.steer("receipts off"); + let kept = || std::fs::read_to_string(world.dir.join("signal").join(format!("{ME}.settings"))).unwrap_or_default(); + world.until("the phone's word kept", || kept().contains(r#""read_receipts":false"#).then_some(())); + // The phone is away at the next start. What it last said was off, and off it stays: the + // failure to avoid is a receipt the account did not agree to. + std::fs::write(world.dir.join("signal.phone-away"), b"").unwrap(); + world.restart(); + world.connected(); + assert_eq!(world.ask(Request::MarkRead { conversation: key(GRACE), message_id: id(T0 + 2_000, GRACE) }), Response::Ok); + world.heard(&format!("read receipts=false {}", id(T0 + 2_000, GRACE))); + world.send(GRACE, "7382", "Quiet", None); + let ours = world.until("our message", || world.messages(GRACE).into_iter().find(|message| message.client_id.as_deref() == Some("7382") && message.id != "7382")); + assert_eq!(ours.receipt_note, "Read receipts are off"); +} + #[test] fn an_unlinked_device_expires_keeps_what_was_read_and_signing_out_unlinks() { let world = World::linked(); diff --git a/docs/product/09-settings.md b/docs/product/09-settings.md index 06266e84..7c98834f 100644 --- a/docs/product/09-settings.md +++ b/docs/product/09-settings.md @@ -409,6 +409,10 @@ the control is not shown on that platform. choices, a Teams admin's policy) is honoured live from the network's events and shown as a fixed row or caption, never stored as a tinyclient value. Signal's P1 and P2 switches are a local stop on top of that, stricter than the account, never the account's value itself. +- Signal's receipt and typing choices are honoured from the phone's last word, and the Signal + adapter keeps that word in its own file (`signal/.settings`) so a restart does not + turn them off until the phone answers again, which it is asked to at every connect (#738). It + stays the network's value, never a tinyclient one. - No setting is written to a network, except the mute that already exists (N12) and is the network's own. - No import from the official apps, browsers or other Macs. No export, no sync, no backup. diff --git a/e2e/scenarios/signal-settings-kept/drive.linux.sh b/e2e/scenarios/signal-settings-kept/drive.linux.sh new file mode 100644 index 00000000..e4696483 --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-settings-kept 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/signal-settings-kept/drive.macos.sh b/e2e/scenarios/signal-settings-kept/drive.macos.sh new file mode 100644 index 00000000..89d6d91d --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-settings-kept 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/signal-settings-kept/drive.py b/e2e/scenarios/signal-settings-kept/drive.py new file mode 100644 index 00000000..d60b26ff --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""The read receipts and typing a Signal phone shared are kept over a chatd restart. + +Starts this build's chatd with the scripted Signal wire (TINYCLIENT_SIGNAL_FAKE), steers it +over its control file the way tests/signal.rs does, and speaks chatd's real socket. The phone +shares its settings at the first connect (read receipts on, typing on), then is away for one +restart (an empty signal.phone-away), so it says nothing at the next connect. A read now asks +the wire for "read receipts=true", a typing signal goes out, and a message sent here does not +say "Read receipts are off". The phone's word is kept under signal/.settings, and when +the phone answers later with receipts off, no receipt goes out. A build from before the fix +forgets the settings with its memory: the read goes out as "receipts=false", no typing signal +is sent, the message says the receipts are off and nothing is kept, so 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 = "a1a1a1a1-0000-4000-8000-000000000001" +GRACE = "b2b2b2b2-0000-4000-8000-000000000002" +GROUP = "g.5a175a175a175a175a175a175a175a175a175a175a175a175a175a175a175a17" +SESSION = json.dumps({"aci": ME, "name": "Ada Quill", "vault": "00"}) +T0MS = 1_791_892_800_000 +FIRST = 1_000 +SECOND = 2_000 + +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 key(id): + return {"network": "signal", "account": ME, "id": id} + + +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 ask(chat, request): + try: + return chat.ask(request) + except Exception: + return None + + +def conversation(chat, id): + answer = ask(chat, {"op": "conversation", "conversation": key(id)}) + return (answer or {}).get("conversation") + + +def stored(chat): + """What the conversation with Grace holds, as chatd pages it to the shell.""" + answer = ask(chat, {"op": "messages", "conversation": key(GRACE), "page": "newest", "limit": 100}) + return (answer or {}).get("messages", []) + + +def lines(path): + """A file the scripted wire appends to, as it stands. Empty until there is one.""" + try: + with open(path, encoding="utf-8") as handle: + return handle.read().splitlines() + except OSError: + return [] + + +def json_file(path): + """A JSON file's content, or None until it is there and reads.""" + try: + with open(path, encoding="utf-8") as handle: + return json.load(handle) + except (OSError, ValueError): + return None + + +def launch(binary, kwargs, stem, sock_path): + """chatd on the scratch directory, once its socket answers: (process, Chat, its logs).""" + out = open(os.path.join(OUT, stem + ".out.log"), "w", encoding="utf-8") + err = open(os.path.join(OUT, stem + ".err.log"), "w", encoding="utf-8") + proc = subprocess.Popen([binary], stdout=out, stderr=err, **kwargs) + chat = None + deadline = time.time() + 15 + while chat is None: + if proc.poll() is not None: + step("chatd stays up for the driver", False) + break + if time.time() > deadline: + step("chatd opens its socket", False) + break + try: + chat = Chat(sock_path) + except OSError: + time.sleep(0.1) + return proc, chat, (out, err) + + +def stop(proc, chat, logs, sock_path): + """chatd off, and gone before anything starts again on its directory.""" + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + for log in logs: + log.close() + if sys.platform != "win32" and os.path.exists(sock_path): + os.remove(sock_path) + + +def connected(chat, words): + return wait(words, chat, lambda: link_is(chat, "connected") or None) is not None + + +def link_is(chat, state): + """True when a Signal account's link is `state` right now.""" + return any(account["link"] == state for account in (ask(chat, {"op": "status"}) or {}).get("accounts", [])) + + +def unread(chat, count): + """None until Grace's row counts `count` unread messages.""" + row = conversation(chat, GRACE) or {} + return row.get("unread") == count or None + + +def before_restart(chat, control, data): + wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) + if not connected(chat, "Signal is connected"): + return + wait("the fake's group is known", chat, lambda: conversation(chat, GROUP)) + + # Grace writes. The settings came with the connect, before her message did. + steer(control, "incoming grace %d Still on for Tuesday?" % (T0MS + FIRST)) + wait("Grace's message is stored, unread", chat, lambda: unread(chat, 1)) + + +def after_restart(chat, control, data): + calls = os.path.join(data, "signal.calls") + kept = os.path.join(data, "signal", ME + ".settings") + connected(chat, "Signal is connected again, with the phone away") + + # The phone said nothing at this connect, so the read goes out as it last said: with a receipt. + first = "%d-%s" % (T0MS + FIRST, GRACE) + step("marking Grace's message read is taken", ask(chat, {"op": "mark_read", "conversation": key(GRACE), "message_id": first}) == {"op": "ok"}) + heard = wait("chatd tells Signal the message is read", chat, lambda: next((c for c in lines(calls) if c.startswith("read receipts=") and c.endswith(" " + first)), None)) + step("the read carries a receipt, as the phone last said (%s)" % heard, heard == "read receipts=true " + first) + + ask(chat, {"op": "typing", "conversation": key(GRACE)}) + wait("a typing signal goes out", chat, lambda: next((c for c in lines(calls) if c == "typing %s started" % GRACE), None)) + + ask(chat, {"op": "send", "conversation": key(GRACE), "client_id": "kept-1", "text": "Tuesday, then"}) + # Read back, as the shell does: the answer to the send does not carry the note. + ours = wait("the message sent now is in the conversation", chat, lambda: next((m for m in stored(chat) if m.get("client_id") == "kept-1" and m.get("id") != "kept-1"), None)) + note = (ours or {}).get("receipt_note") + step("a message sent now does not say the receipts are off (it says: %r)" % note, ours is not None and not note) + + said = wait("the phone's last word is kept", chat, lambda: json_file(kept), seconds=5) + step("what is kept says receipts and typing are on (%s)" % said, bool(said) and said.get("read_receipts") is True and said.get("typing") is True) + + # The phone is back and turned the receipts off: its word wins, and none goes out. + steer(control, "incoming grace %d Bring the score sheet" % (T0MS + SECOND)) + wait("Grace's second message is stored, unread", chat, lambda: unread(chat, 1)) + steer(control, "receipts off") + wait("the phone's later word is kept", chat, lambda: (json_file(kept) or {}).get("read_receipts") is False or None, seconds=5) + second = "%d-%s" % (T0MS + SECOND, GRACE) + step("marking the second message read is taken", ask(chat, {"op": "mark_read", "conversation": key(GRACE), "message_id": second}) == {"op": "ok"}) + wait("the phone's later word is honoured: the read goes out with no receipt", chat, lambda: next((c for c in lines(calls) if c == "read receipts=false " + second), None)) + + +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 + + data = os.path.join(OUT, "data") + os.makedirs(data, exist_ok=True) + sock_path = os.path.join(data, "chat.sock") + control = os.path.join(data, "signal.ctl") + open(control, "a", encoding="utf-8").close() + env = os.environ.copy() + env["TINYCLIENT_DIR"] = data + env["TINYCLIENT_SIGNAL_FAKE"] = "1" + env["TINYCLIENT_SESSION_SIGNAL"] = SESSION + env.pop("TINYCLIENT_SESSION_DISCORD", None) + env.pop("TINYCLIENT_SESSION_SLACK", None) + env.pop("TINYCLIENT_SESSION_TELEGRAM", None) + env.pop("TINYCLIENT_SESSION_TEAMS", None) + kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL} + if sys.platform == "win32": + kwargs["creationflags"] = 0x08000000 + + def run(stem, part): + """chatd on the scratch directory for one part of the drive. False when a step failed.""" + proc, chat, logs = launch(binary, kwargs, stem, sock_path) + try: + if chat is not None: + part(chat, control, data) + return not FAILED + finally: + stop(proc, chat, logs, sock_path) + + if not run("chatd", before_restart): + return 1 + # The phone is off for the next connect: it says nothing of the settings, and what chatd + # kept of its last word is all there is. + open(os.path.join(data, "signal.phone-away"), "a", encoding="utf-8").close() + run("chatd-again", after_restart) + return 1 if FAILED else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/signal-settings-kept/drive.windows.ps1 b/e2e/scenarios/signal-settings-kept/drive.windows.ps1 new file mode 100644 index 00000000..f7c40b3b --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/drive.windows.ps1 @@ -0,0 +1,17 @@ +# signal-settings-kept 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/signal-settings-kept/scenario.json b/e2e/scenarios/signal-settings-kept/scenario.json new file mode 100644 index 00000000..3b761cf7 --- /dev/null +++ b/e2e/scenarios/signal-settings-kept/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "signal-settings-kept", + "title": "The read receipts and typing a Signal phone shared are kept over a chatd restart, until the phone says otherwise", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The phone proof build does not run desktop chatd. The kept settings are desktop chatd's Signal adapter and its file.", + "ios": "The phone proof build does not run desktop chatd. The kept settings are desktop chatd's Signal adapter and its file." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}