diff --git a/crates/chatd/src/adapters/signal.rs b/crates/chatd/src/adapters/signal.rs index 02671b66..beddbccf 100644 --- a/crates/chatd/src/adapters/signal.rs +++ b/crates/chatd/src/adapters/signal.rs @@ -2044,7 +2044,7 @@ fn apply(account: &Account, event: Event) { let peer = Peer::Group(group.id.clone()); let conv = peer.conversation(); let rights = group_rights(&group, &account.me); - let is_admin = group.admins.iter().any(|id| id == &account.me); + let lock = send_lock(&group, &account.me); { let mut live = account.live(); live.groups.insert(conv.clone(), group.member_ids.clone()); @@ -2058,9 +2058,9 @@ fn apply(account: &Account, event: Event) { } let mut row = row(&peer, &group.title); row.topic = group.description.chars().take(300).collect(); - row.read_only = !group.member || (group.announcements_only && !is_admin); - if group.member && group.announcements_only && !is_admin { - row.read_only_reason = "Only admins can send messages".to_owned(); + row.read_only = !group.member || !lock.is_empty(); + if group.member { + row.read_only_reason = lock.to_owned(); } row.rights = rights; row.avatar = ctx.avatar_of(&row.id); @@ -2077,19 +2077,28 @@ fn apply(account: &Account, event: Event) { let title = title.unwrap_or_else(|| known.as_ref().map(|row| row.title.clone()).unwrap_or_default()); let mut row = row(&peer, &title); row.topic = description.unwrap_or_else(|| known.as_ref().map(|row| row.topic.clone()).unwrap_or_default()).chars().take(300).collect(); - // A later rename does not put a removed member back, while re-adding clears read-only. + // A later rename does not put a removed member back, and leaving stays read-only. + // Being added back follows the group as it last stood: one where only admins send + // is still read-only for anyone who is not an admin. + let lock = if rejoined { + account.live().group_info.get(&id).map(|group| send_lock(group, &account.me)).unwrap_or_default() + } else { + "" + }; row.read_only = if left { true } else if rejoined { - false + !lock.is_empty() } else { known.as_ref().is_some_and(|row| row.read_only) }; + if rejoined { + row.read_only_reason = lock.to_owned(); + } else if let Some(known) = &known { + row.read_only_reason = known.read_only_reason.clone(); + } if let Some(known) = &known { row.rights = known.rights; - if !rejoined { - row.read_only_reason = known.read_only_reason.clone(); - } } row.avatar = ctx.avatar_of(&row.id); let _ = ctx.conversation(&row); @@ -5425,6 +5434,16 @@ fn set_own(account: &Account, name: Option, about: Option, emoji Ok(()) } +/// Why this account cannot send in a group as it stands, in the words the composer shows. Empty +/// when it can: only a group where just the admins send is closed to anyone who is not one. +fn send_lock(group: &wire::GroupInfo, me: &str) -> &'static str { + if group.announcements_only && !group.admins.iter().any(|id| id == me) { + "Only admins can send messages" + } else { + "" + } +} + /// Computes `ConversationRights` for a Signal group from its access control and our role. fn group_rights(group: &wire::GroupInfo, me: &str) -> ConversationRights { if !group.member { @@ -7506,6 +7525,18 @@ mod tests { assert!(group_settings_commands(&ChatSettings { slowmode_seconds: Some(30), ..ChatSettings::default() }).is_empty()); } + #[test] + fn only_an_admin_sends_in_a_group_where_only_admins_send() { + let admins = "b2b2b2b2-0000-4000-8000-000000000002"; + let me = "a1a1a1a1-0000-4000-8000-000000000001"; + let mut group = wire::GroupInfo { announcements_only: true, admins: vec![admins.into()], ..wire::GroupInfo::default() }; + assert_eq!(send_lock(&group, me), "Only admins can send messages"); + assert_eq!(send_lock(&group, admins), ""); + // A group everyone sends in locks nobody, whoever they are. + group.announcements_only = false; + assert_eq!(send_lock(&group, me), ""); + } + #[test] fn a_linked_account_claims_no_calls_and_no_chat_filing() { // No scripted wire here: this is what a linked account is told it can do. diff --git a/crates/chatd/src/adapters/signal/real.rs b/crates/chatd/src/adapters/signal/real.rs index ee7375dc..b53c802b 100644 --- a/crates/chatd/src/adapters/signal/real.rs +++ b/crates/chatd/src/adapters/signal/real.rs @@ -279,6 +279,42 @@ fn snap_of(group: &Group) -> GroupSnap { } } +/// One stored group as the contract tells it whole. `announcements_only` is what the vault read +/// for the group's revision: presage's reading of the group does not say. +fn info_of(key: &[u8; 32], group: &Group, snap: &GroupSnap, me: &str, announcements_only: bool) -> GroupInfo { + let member = snap.members.iter().any(|member| member.id == me); + let member_ids = group.members.iter().map(|member| ServiceId::from(member.aci).raw_uuid().to_string()).collect(); + let admins = group + .members + .iter() + .filter(|member| member.role == Role::Administrator) + .map(|member| ServiceId::from(member.aci).raw_uuid().to_string()) + .collect(); + let member_access = group.access_control.as_ref().map_or(GroupAccess::Member, |ac| access_of(ac.members)); + let attributes_access = group.access_control.as_ref().map_or(GroupAccess::Member, |ac| access_of(ac.attributes)); + let invite_link_access = group.access_control.as_ref().map_or(GroupAccess::Unsatisfiable, |ac| access_of(ac.add_from_invite_link)); + let invite_link = if !group.invite_link_password.is_empty() && invite_link_access != GroupAccess::Unsatisfiable { + format_group_invite_link(key, &group.invite_link_password) + } else { + String::new() + }; + GroupInfo { + id: group_id(key), + title: group.title.clone(), + description: group.description.clone().unwrap_or_default(), + members: group.members.len() as u32, + member, + member_ids, + admins, + member_access, + attributes_access, + invite_link_access, + announcements_only, + invite_link, + timer_secs: snap.timer_secs, + } +} + /// Ids whose membership, role, invite or request changed. A rename does not name a person. fn people_who_changed(before: &GroupSnap, after: &GroupSnap) -> Vec { let was: HashMap<&str, bool> = before.members.iter().map(|member| (member.id.as_str(), member.admin)).collect(); @@ -521,6 +557,7 @@ impl Real { names: HashMap::new(), groups: HashMap::new(), known: GroupRevisions::default(), + send_rule_settled: HashSet::new(), blocked_acis: HashSet::new(), blocked_groups: HashSet::new(), blocked_numbers: HashSet::new(), @@ -981,6 +1018,9 @@ struct Session { groups: HashMap, /// Last revision applied for a group, and the snapshot behind it. The first one is not announced. known: GroupRevisions, + /// Groups that need not be asked who may send on this connection: their send rule was known + /// when they were told, or Signal was asked once and did not say. + send_rule_settled: HashSet, /// Currently blocked ACIs and group ids, so a `SyncMessage.blocked` write sends the full list. blocked_acis: HashSet, blocked_groups: HashSet, @@ -1323,44 +1363,38 @@ impl Session { let id = group_id(&key); let revision = group.revision; let snap = snap_of(&group); - let timer_secs = snap.timer_secs; - let member = snap.members.iter().any(|member| member.id == self.me); - let member_ids = group.members.iter().map(|member| ServiceId::from(member.aci).raw_uuid().to_string()).collect(); - let admins = group - .members - .iter() - .filter(|member| member.role == Role::Administrator) - .map(|member| ServiceId::from(member.aci).raw_uuid().to_string()) - .collect(); - let member_access = group.access_control.as_ref().map_or(GroupAccess::Member, |ac| access_of(ac.members)); - let attributes_access = group.access_control.as_ref().map_or(GroupAccess::Member, |ac| access_of(ac.attributes)); - let invite_link_access = group.access_control.as_ref().map_or(GroupAccess::Unsatisfiable, |ac| access_of(ac.add_from_invite_link)); - let invite_link = if !group.invite_link_password.is_empty() && invite_link_access != GroupAccess::Unsatisfiable { - format_group_invite_link(&key, &group.invite_link_password) - } else { - String::new() - }; + let announcements_only = self.vault.announcements_only(key); + let info = info_of(&key, &group, &snap, &self.me, announcements_only.unwrap_or(false)); self.groups.insert(id.clone(), key); self.known.seed(id.clone(), revision, snap); - told.push(GroupInfo { - id, - title: group.title, - description: group.description.unwrap_or_default(), - members: group.members.len() as u32, - member, - member_ids, - admins, - member_access, - attributes_access, - invite_link_access, - announcements_only: false, - invite_link, - timer_secs, - }); + if announcements_only.is_some() { + self.send_rule_settled.insert(id); + } + told.push(info); } self.tell(Event::Groups(told)); } + /// One stored group, told whole: what `groups_changed` tells of every group, for the one whose + /// revision was just read or applied. + async fn group_told(&mut self, id: &str) { + let Some(key) = self.groups.get(id).copied() else { + return; + }; + let Some(group) = self.vault.group(key).await.ok().flatten() else { + return; + }; + let announcements_only = self.vault.announcements_only(key).unwrap_or(false); + let info = info_of(&key, &group, &snap_of(&group), &self.me, announcements_only); + self.tell(Event::Groups(vec![info])); + } + + /// Reads a group once more for the one thing its stored copy does not say: whether only admins + /// may send. Presage stores a group without it. `true` when the group was read. + async fn read_send_rule(&mut self, key: &[u8; 32]) -> bool { + matches!(self.fetch_group(key).await, Ok(Some(_))) + } + /// Why the messages ended: an unlinked device is told apart from a dropped connection. async fn why_closed(&mut self) -> Event { match self.manager.whoami().await { @@ -1404,12 +1438,20 @@ impl Session { let id = group_id(&key); if !self.known.contains(&id) { self.groups.insert(id.clone(), key); + // Presage has just stored this group, without saying who may send in it. + self.read_send_rule(&key).await; self.groups_changed().await; return Peer::Group(id); } if let Some(revision) = group.and_then(|group| group.revision) { self.note_group_change(&id, &key, revision).await; } + // A group told while nothing said who may send in it: one stored before that was + // read here, or one whose read failed since. Asked once a connection, so a group + // Signal will not answer for costs no request on every message. + if self.send_rule_settled.insert(id.clone()) && self.vault.announcements_only(key).is_none() && self.read_send_rule(&key).await { + self.group_told(&id).await; + } Peer::Group(id) } None => Peer::Direct(person.to_owned()), @@ -1456,7 +1498,10 @@ impl Session { let Some(mut group) = self.vault.group_keys().ok().and_then(|groups| groups.into_iter().find(|(stored, _)| stored == key).map(|(_, group)| group)) else { return; }; - if group.revision < revision { + // The group is read once more when the stored one is behind this message, and when nothing + // says who may send in it: presage's reading of a group drops that, so a revision it just + // stored does not have it. + if group.revision < revision || self.vault.announcements_only(*key).is_none() { // The fetch behind this message failed, which is all a removed member ever gets. // Ask once more: the answer is the new group, or that we are out of it. Any other // failure leaves the revision unapplied, so the next message asks again. @@ -1465,7 +1510,7 @@ impl Session { Ok(None) => { let me = self.me.clone(); group.members.retain(|m| ServiceId::from(m.aci).raw_uuid().to_string() != me); - group.revision = revision; + group.revision = group.revision.max(revision); } Err(_) => return, } @@ -1491,18 +1536,20 @@ impl Session { names.insert(person, name); } let delta = group_delta(&before, &after, &me, |person| names.get(person).cloned().unwrap_or_default()); - if delta.lines.is_empty() { - return; + if !delta.lines.is_empty() { + self.tell(Event::GroupChanged { + peer: Peer::Group(id.to_owned()), + by: String::new(), + changes: delta.lines, + title: delta.title, + description: delta.description, + left: delta.left, + rejoined: delta.rejoined, + }); } - self.tell(Event::GroupChanged { - peer: Peer::Group(id.to_owned()), - by: String::new(), - changes: delta.lines, - title: delta.title, - description: delta.description, - left: delta.left, - rejoined: delta.rejoined, - }); + // Told whole after the lines: who may send, and what this account may do in the group, + // can change with a revision, and no line says so. + self.group_told(id).await; } /// A long text read whole from its attachment. None when it is not one, or the read failed. @@ -2945,7 +2992,8 @@ impl Session { Ok((push, groups_mgr, auth)) } - /// Reads a group from the Groups service. `None` when the service says this account is not + /// Reads a group from the Groups service and keeps it, with whether only admins may send, which + /// presage's own reading of a group drops. `None` when the service says this account is not /// in the group: it answers 403 to anyone who is neither a member nor invited. async fn fetch_group(&mut self, key: &[u8; 32]) -> Result, Fault> { let (push, _, auth) = self.group_session(key).await?; @@ -2967,7 +3015,10 @@ impl Session { } let bytes = resp.bytes().await.map_err(|err| Fault::Net(err.to_string()))?; let encrypted: presage::proto::Group = prost::Message::decode(bytes).map_err(|err| Fault::Net(err.to_string()))?; - presage::libsignal_service::groups_v2::decrypt_group(key, encrypted).map(|group| Some(group.into())).map_err(|err| Fault::Net(err.to_string())) + let decrypted: presage::libsignal_service::groups_v2::Group = + presage::libsignal_service::groups_v2::decrypt_group(key, encrypted).map_err(|err| Fault::Net(err.to_string()))?; + self.vault.keep_decrypted_group(*key, &decrypted).await.map_err(|err| Fault::Net(err.to_string()))?; + Ok(Some(decrypted.into())) } async fn patch_group(&mut self, group_id: &str, actions: presage::proto::group_change::Actions) -> Result<(), Fault> { @@ -2998,7 +3049,7 @@ impl Session { if status == reqwest::StatusCode::CONFLICT { if let Ok(encrypted) = groups_mgr.fetch_encrypted_group(&mut rand::rng(), &key).await { if let Ok(decrypted) = presage::libsignal_service::groups_v2::decrypt_group(&key, encrypted) { - let _ = self.vault.save_group(key, decrypted).await; + let _ = self.vault.keep_decrypted_group(key, &decrypted).await; self.groups_changed().await; } } @@ -3010,7 +3061,7 @@ impl Session { if let Ok(encrypted) = groups_mgr.fetch_encrypted_group(&mut rand::rng(), &key).await { if let Ok(decrypted) = presage::libsignal_service::groups_v2::decrypt_group(&key, encrypted) { let rev = decrypted.version; - let _ = self.vault.save_group(key, decrypted).await; + let _ = self.vault.keep_decrypted_group(key, &decrypted).await; let ctx = GroupContextV2 { master_key: Some(key.to_vec()), revision: Some(rev), @@ -4697,7 +4748,7 @@ impl Linker for RealLinker { // Closed before the user saw it finish: undone, never left on the account. if cancelled.load(Ordering::Relaxed) { let (ready_tx, _) = async_mpsc::unbounded_channel(); - let mut session = Session { manager, vault: store.clone(), me: aci, events: channel().0, names: HashMap::new(), groups: HashMap::new(), known: GroupRevisions::default(), blocked_acis: HashSet::new(), blocked_groups: HashSet::new(), blocked_numbers: HashSet::new(), blocked_known: false, ready_sends: ready_tx }; + let mut session = Session { manager, vault: store.clone(), me: aci, events: channel().0, names: HashMap::new(), groups: HashMap::new(), known: GroupRevisions::default(), send_rule_settled: HashSet::new(), blocked_acis: HashSet::new(), blocked_groups: HashSet::new(), blocked_numbers: HashSet::new(), blocked_known: false, ready_sends: ready_tx }; let _ = local.block_on(&runtime, session.unlink()); drop(session); vault::remove(&pending); @@ -4955,6 +5006,28 @@ mod tests { vault::remove(&path); } + #[test] + fn a_group_is_told_with_who_may_send_as_it_was_read() { + let key = [0x42u8; 32]; + let group = Group { + title: "Team".into(), + avatar: String::new(), + disappearing_messages_timer: None, + access_control: None, + revision: 7, + members: Vec::new(), + pending_members: Vec::new(), + requesting_members: Vec::new(), + invite_link_password: Vec::new(), + description: Some("Tuesdays".into()), + }; + let admins_only = info_of(&key, &group, &snap_of(&group), "me", true); + assert!(admins_only.announcements_only && !admins_only.member); + assert_eq!((admins_only.title.as_str(), admins_only.description.as_str(), admins_only.id.len()), ("Team", "Tuesdays", 64)); + // What was read is what is told: a group read as open to everyone is not told as admins-only. + assert!(!info_of(&key, &group, &snap_of(&group), "me", false).announcements_only); + } + #[test] fn cancelled_send_reply_marks_closed_to_prevent_ghost_send() { let (reply, rx, closed) = SendReply::channel(); diff --git a/crates/chatd/src/adapters/signal/vault.rs b/crates/chatd/src/adapters/signal/vault.rs index b560e615..ca42181b 100644 --- a/crates/chatd/src/adapters/signal/vault.rs +++ b/crates/chatd/src/adapters/signal/vault.rs @@ -81,6 +81,16 @@ impl From for SignalProtocolError { type Held = Result; +/// A stored group as this vault reads it back for itself. Everything else in the record is +/// presage's reading of the group, which has no place for who may send. +#[derive(serde::Deserialize)] +struct KeptGroup { + revision: u32, + /// Whether only the admins may send, when that was read for `revision`. Absent otherwise. + #[serde(default)] + announcements_only: Option, +} + struct Inner { db: Mutex, cipher: Aes256GcmSiv, @@ -385,6 +395,35 @@ impl Vault { } Ok(groups) } + + fn kept(&self, master_key: GroupMasterKeyBytes) -> Held> { + self.json(&format!("group.{}", hex(&master_key))) + } + + /// Whether only the group's admins may send, as read for the revision now stored. `None` when + /// nothing says: presage stores a group without it, and so did this vault before it kept it. + pub fn announcements_only(&self, master_key: GroupMasterKeyBytes) -> Option { + self.kept(master_key).ok().flatten().and_then(|kept| kept.announcements_only) + } + + /// Keeps a group libsignal has just decrypted, whole: everything presage reads of it, and + /// whether only admins may send. Presage's own reading of a group has no place for that and + /// drops it, so this is the one place it is read. + pub async fn keep_decrypted_group(&self, master_key: GroupMasterKeyBytes, group: &presage::libsignal_service::groups_v2::Group) -> Held<()> { + self.write_group(master_key, group.clone().into(), Some(group.announcements_only)).await + } + + /// Writes a stored group. Who may send is written only when it is known for this revision. + async fn write_group(&self, master_key: GroupMasterKeyBytes, group: Group, announcements_only: Option) -> Held<()> { + let mut value = serde_json::to_value(&group)?; + let serde_json::Value::Object(record) = &mut value else { + return Err(VaultError("a group was not written as a record".into())); + }; + if let Some(announcements_only) = announcements_only { + record.insert("announcements_only".to_owned(), announcements_only.into()); + } + self.put(&format!("group.{}", hex(&master_key)), &serde_json::to_vec(&value)?) + } } /// Computes the exclusive lexicographical upper bound for a UTF-8 prefix so SQLite can satisfy @@ -569,8 +608,12 @@ impl ContentsStore for Vault { Ok(()) } + /// A group presage read itself. Who may send belongs to the revision it was read for, so it + /// stays only while this is that revision. async fn save_group(&self, master_key: GroupMasterKeyBytes, group: impl Into) -> Held<()> { - self.put_json(&format!("group.{}", hex(&master_key)), &group.into()) + let group = group.into(); + let announcements_only = self.kept(master_key).ok().flatten().filter(|kept| kept.revision == group.revision).and_then(|kept| kept.announcements_only); + self.write_group(master_key, group, announcements_only).await } async fn groups(&self) -> Held { @@ -1133,4 +1176,56 @@ mod tests { assert_eq!(vault.get("session.1").unwrap().as_deref(), Some(&b"s1"[..])); remove(&path); } + + /// A group as libsignal decrypts it, at `version` with `announcements_only`. + fn decrypted(version: u32, announcements_only: bool) -> presage::libsignal_service::groups_v2::Group { + presage::libsignal_service::groups_v2::Group { + title: "Bridge club".into(), + avatar: String::new(), + disappearing_messages_timer: None, + access_control: None, + version, + members: Vec::new(), + members_pending_profile_key: Vec::new(), + members_pending_admin_approval: Vec::new(), + invite_link_password: Vec::new(), + description_text: None, + announcements_only, + members_banned: Vec::new(), + } + } + + #[test] + fn a_decrypted_group_keeps_who_may_send_for_as_long_as_its_revision_is_stored() { + let path = std::env::temp_dir().join(format!("tinyclient-vault-group-{}.state", std::process::id())); + remove(&path); + let vault = Vault::open(&path, &new_key().unwrap()).unwrap(); + let key = [0x5au8; 32]; + // Presage's reading of the stored group, at the revision named: what it hands back. + let stored = |revision: u32| Group { revision, ..vault.group_by_key(key).unwrap().unwrap() }; + futures::executor::block_on(async { + // The group presage stores after it fetches it, handed over as libsignal decrypted + // it: nothing is read for it, so nothing says who may send. + vault.save_group(key, decrypted(7, true)).await.unwrap(); + assert_eq!(vault.announcements_only(key), None); + + // Decrypted here, the group is kept whole, and presage still reads it. + vault.keep_decrypted_group(key, &decrypted(7, true)).await.unwrap(); + assert_eq!(vault.announcements_only(key), Some(true)); + assert_eq!(vault.group_by_key(key).unwrap().map(|group| (group.revision, group.title)), Some((7, "Bridge club".into()))); + + // Presage storing the same revision again keeps it. + vault.save_group(key, stored(7)).await.unwrap(); + assert_eq!(vault.announcements_only(key), Some(true)); + + // Presage storing another revision leaves it behind: it was read for the old one. + vault.save_group(key, stored(8)).await.unwrap(); + assert_eq!(vault.announcements_only(key), None); + + // A group read as open to everyone says so, which is not the same as nothing said. + vault.keep_decrypted_group(key, &decrypted(8, false)).await.unwrap(); + assert_eq!(vault.announcements_only(key), Some(false)); + }); + remove(&path); + } } diff --git a/crates/chatd/tests/signal.rs b/crates/chatd/tests/signal.rs index 00d0e765..b5411cfd 100644 --- a/crates/chatd/tests/signal.rs +++ b/crates/chatd/tests/signal.rs @@ -1914,6 +1914,37 @@ fn an_announcement_only_group_is_read_only_for_non_admins() { assert_eq!(sent.text, "Admin announcement"); } +/// A group where only admins send stays read-only for this account while it is not an admin: being +/// taken out and added back does not open the composer again. The line that says so is written +/// after the row of that change, so it is the sign the change has landed. +#[test] +fn an_announcements_only_group_stays_read_only_for_a_member_who_is_added_back() { + let world = World::linked(); + world.connected(); + let line = |text: &str| world.messages(CLUB).into_iter().find(|message| message.kind == MessageKind::System && message.text == text); + + world.steer("group-role me member"); + world.steer("group-access announcements=on"); + let row = world.until("read-only for a member who is not an admin", || { + let row = world.conversation(CLUB)?; + row.read_only.then_some(row) + }); + assert_eq!(row.read_only_reason, "Only admins can send messages"); + + // Out of the group, then added back by an admin: the group is as it was, and so is the row. + world.steer("group-leave"); + world.until("the line that says we are out", || line("You are no longer in this group")); + world.steer("group-rejoin"); + world.until("the line that says we are back", || line("You joined the group")); + let row = world.conversation(CLUB).unwrap(); + assert!(row.read_only, "being added back to a group where only admins send must not open the composer: {row:?}"); + assert_eq!(row.read_only_reason, "Only admins can send messages"); + + // Made an admin, the composer opens. + world.steer("group-role me admin"); + world.until("an admin may send", || (!world.conversation(CLUB)?.read_only).then_some(())); +} + #[test] fn editing_group_name_description_avatar_and_permissions() { let world = World::linked(); diff --git a/e2e/scenarios/signal-announcements-only/drive.linux.sh b/e2e/scenarios/signal-announcements-only/drive.linux.sh new file mode 100644 index 00000000..2508f244 --- /dev/null +++ b/e2e/scenarios/signal-announcements-only/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-announcements-only 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-announcements-only/drive.macos.sh b/e2e/scenarios/signal-announcements-only/drive.macos.sh new file mode 100644 index 00000000..e72ecefa --- /dev/null +++ b/e2e/scenarios/signal-announcements-only/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-announcements-only 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-announcements-only/drive.py b/e2e/scenarios/signal-announcements-only/drive.py new file mode 100644 index 00000000..cb0f1daa --- /dev/null +++ b/e2e/scenarios/signal-announcements-only/drive.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""A Signal group where only admins send is read-only for everyone who is not an admin. + +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: a member +who is not an admin gets a read-only row that says "Only admins can send messages", a send is +refused in those words, and being taken out and added back leaves the row read-only until they +are made an admin. A build from before the fix opens the composer again when the member is +added back, 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" +SESSION = json.dumps({"aci": ME, "name": "Ada Quill", "vault": "00"}) +CLUB = "g." + "5a175a175a175a175a175a175a175a175a175a175a175a175a175a175a175a17" +REASON = "Only admins can send messages" + +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 + + 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 + with open(os.path.join(OUT, "chatd.out.log"), "w", encoding="utf-8") as out, open(os.path.join(OUT, "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 1 + if time.time() > deadline: + step("chatd opens its socket", False) + return 1 + try: + chat = Chat(sock_path) + except OSError: + time.sleep(0.1) + drive(chat, control) + finally: + if chat: + chat.close() + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + return 1 if FAILED else 0 + + +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 messages(chat, id): + answer = ask(chat, {"op": "messages", "conversation": key(id), "page": "newest", "limit": 100}) + return (answer or {}).get("messages", []) + + +def drive(chat, control): + status = wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"})) + if status is None: + return + wait("Signal is connected", chat, lambda: (any(a["link"] == "connected" for a in ask(chat, {"op": "status"})["accounts"]) or None)) + wait("the fake's group is known", chat, lambda: conversation(chat, CLUB) and True) + + def locked(): + row = conversation(chat, CLUB) + return row if row and row.get("read_only") else None + + def line(text): + return next((m for m in messages(chat, CLUB) if m.get("kind") == {"kind": "system"} and m.get("text") == text), None) + + def refuses(client_id): + answer = ask(chat, {"op": "send", "conversation": key(CLUB), "client_id": client_id, "text": "Hello?"}) or {} + return answer.get("op") == "error" and answer.get("code") == "refused" and answer.get("detail") == REASON + + # No longer an admin: the rights to manage the group go with the role. + steer(control, "group-role me member") + wait("the member is no admin", chat, lambda: (not (conversation(chat, CLUB) or {}).get("rights", {}).get("manage_members")) or None) + + # Only admins may send: the row says so, and a send is refused in the same words. + steer(control, "group-access announcements=on") + wait("the group is read-only for a member who is not an admin", chat, locked) + row = conversation(chat, CLUB) or {} + step("the row says only admins can send", row.get("read_only_reason") == REASON) + step("a send is refused in those words", refuses("ann-1")) + + # Taken out, then added back by an admin: the group is as it was, and so is the row. + steer(control, "group-leave") + wait("the line that says the member is out", chat, lambda: line("You are no longer in this group")) + steer(control, "group-rejoin") + wait("the line that says the member is back", chat, lambda: line("You joined the group")) + row = conversation(chat, CLUB) or {} + step("being added back leaves the group read-only", bool(row.get("read_only"))) + step("the row still says only admins can send", row.get("read_only_reason") == REASON) + step("a send is still refused", refuses("ann-2")) + + # An admin may send. + steer(control, "group-role me admin") + wait("an admin may send again", chat, lambda: ((conversation(chat, CLUB) or {}).get("read_only") in (None, False)) or None) + answer = ask(chat, {"op": "send", "conversation": key(CLUB), "client_id": "ann-3", "text": "Admin announcement"}) or {} + step("an admin's send is taken", answer.get("op") == "sent") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/signal-announcements-only/drive.windows.ps1 b/e2e/scenarios/signal-announcements-only/drive.windows.ps1 new file mode 100644 index 00000000..f5fbab28 --- /dev/null +++ b/e2e/scenarios/signal-announcements-only/drive.windows.ps1 @@ -0,0 +1,17 @@ +# signal-announcements-only 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-announcements-only/scenario.json b/e2e/scenarios/signal-announcements-only/scenario.json new file mode 100644 index 00000000..1d1673df --- /dev/null +++ b/e2e/scenarios/signal-announcements-only/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "signal-announcements-only", + "title": "A Signal group where only admins send is read-only for everyone who is not an admin, and stays so for a member added back to it", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The phone proof build does not run desktop chatd. The read-only row is the desktop adapter's, on the scripted Signal wire.", + "ios": "The phone proof build does not run desktop chatd. The read-only row is the desktop adapter's, on the scripted Signal wire." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}