Skip to content
Open
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
49 changes: 40 additions & 9 deletions crates/chatd/src/adapters/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -5425,6 +5434,16 @@ fn set_own(account: &Account, name: Option<String>, about: Option<String>, 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 {
Expand Down Expand Up @@ -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.
Expand Down
173 changes: 123 additions & 50 deletions crates/chatd/src/adapters/signal/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
let was: HashMap<&str, bool> = before.members.iter().map(|member| (member.id.as_str(), member.admin)).collect();
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -981,6 +1018,9 @@ struct Session {
groups: HashMap<String, [u8; 32]>,
/// 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<String>,
/// Currently blocked ACIs and group ids, so a `SyncMessage.blocked` write sends the full list.
blocked_acis: HashSet<String>,
blocked_groups: HashSet<String>,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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()),
Expand Down Expand Up @@ -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.
Expand All @@ -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,
}
Expand All @@ -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.
Expand Down Expand Up @@ -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<Option<presage::model::groups::Group>, Fault> {
let (push, _, auth) = self.group_session(key).await?;
Expand All @@ -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> {
Expand Down Expand Up @@ -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;
}
}
Expand All @@ -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),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading