Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 146 additions & 25 deletions crates/chatd/src/adapters/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -772,9 +776,13 @@ struct Live {
group_calls: HashMap<String, GroupCallTrack>,
/// Pending incoming Signal group-call ring (`conversation_id`, `group_id`, `era_id`, `caller_aci`, `ring_id`).
group_ring: Option<IncomingGroupRing>,
/// 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<u64>,
/// Disappearing-messages timer per conversation id.
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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<bool>,
}

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<KeptSettings> {
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::<KeptSettings>(&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> {
Expand Down Expand Up @@ -1527,15 +1620,10 @@ pub fn start(ctx: Context, session: &str, inbox: Receiver<Command>) -> 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<Mutex<Option<Arc<Account>>>> = Arc::default();
let (socket_ctx, held, socket_saved, socket_live) = (ctx.clone(), current.clone(), saved.clone(), live.clone());
std::thread::Builder::new()
Expand Down Expand Up @@ -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 } => {
Expand Down Expand Up @@ -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();
Expand Down
19 changes: 17 additions & 2 deletions crates/chatd/src/adapters/signal/fake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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::<StorageSnapshot>(&raw) {
Expand Down
16 changes: 13 additions & 3 deletions crates/chatd/src/adapters/signal/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1013,24 +1013,34 @@ 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())
};
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.
Expand Down
53 changes: 53 additions & 0 deletions crates/chatd/tests/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 4 additions & 0 deletions docs/product/09-settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<account>.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.
Expand Down
9 changes: 9 additions & 0 deletions e2e/scenarios/signal-settings-kept/drive.linux.sh
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading