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
174 changes: 157 additions & 17 deletions crates/chatd/src/adapters/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ fn group_admin_action(person: &str) -> Option<(&str, bool)> {
}
/// What a person with no name we know is called.
const NO_NAME: &str = "Signal user";
/// What a row says when this account is out of a Signal group and cannot write in it.
const LEFT_GROUP: &str = "You are no longer in this group";

fn now_ms() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_millis() as u64)
Expand Down Expand Up @@ -353,6 +355,11 @@ impl GroupRevisions {
self.known.entry(id).or_insert((revision, snap));
}

/// The last revision applied for a group, when it is tracked.
pub fn revision(&self, id: &str) -> Option<u32> {
self.known.get(id).map(|(revision, _)| *revision)
}

/// True only when `id` is tracked and `revision` is strictly newer than the last applied one.
pub fn should_check(&self, id: &str, revision: u32) -> bool {
self.known.get(id).is_some_and(|(known_rev, _)| revision > *known_rev)
Expand All @@ -370,6 +377,43 @@ impl GroupRevisions {
}
}

/// What one message says about a group that moved forward. Who sent it is the one part the
/// Signal protocol vouches for: the bytes of the change on the message are not read, because
/// nothing in the libraries here checks the server's signature on them (`real.rs`,
/// `note_group_change`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GroupStep<'a> {
/// Who sent the message.
pub author: &'a str,
/// The message carries a change. A device sends that to the group right after it changed the
/// group (`patch_group`); a message that only names the revision came from whoever wrote next.
pub announces: bool,
/// The revision the message names.
pub told: u32,
/// The revision applied before this one.
pub previous: u32,
/// The revision stored now.
pub stored: u32,
/// The stored group is what the server gave, not one made here after it refused to hand the
/// group over because this account is out of it.
pub from_server: bool,
}

impl GroupStep<'_> {
/// Whether the author made this change, so that the lines can say who did. That is so only
/// when the message announces the change, the stored group is the server's and exactly one
/// revision on from the last one applied, the message names that revision, and the author is
/// someone a change can have come from: a member before or after. More than one revision at
/// once can be the work of several people, and a group made here says nothing about who.
pub fn names_author(&self, before: &GroupSnap, after: &GroupSnap) -> bool {
self.announces
&& self.from_server
&& self.stored == self.told
&& self.stored == self.previous.saturating_add(1)
&& (before.members.iter().any(|member| member.id == self.author) || after.members.iter().any(|member| member.id == self.author))
}
}

fn person(id: &str, me: &str, name: &impl Fn(&str) -> String) -> String {
if id == me {
"You".to_owned()
Expand All @@ -396,7 +440,9 @@ fn duration(secs: u32) -> String {

/// The lines and the row fields for one group revision. The first snapshot of a connection is not
/// passed here: a connect has no "before", so it shows the current name and no system lines.
pub fn group_delta(before: &GroupSnap, after: &GroupSnap, me: &str, name: impl Fn(&str) -> String) -> GroupDelta {
/// `by` is who made the change when that can be said (`GroupStep`), and empty when it cannot:
/// the lines then say that someone joined or is gone, not who made it so.
pub fn group_delta(before: &GroupSnap, after: &GroupSnap, me: &str, by: &str, name: impl Fn(&str) -> String) -> GroupDelta {
let mut lines = Vec::new();
let title = (before.title != after.title).then(|| {
lines.push(format!("The group name is now {}", after.title));
Expand Down Expand Up @@ -425,14 +471,25 @@ pub fn group_delta(before: &GroupSnap, after: &GroupSnap, me: &str, name: impl F
}
let was: HashMap<&str, bool> = before.members.iter().map(|member| (member.id.as_str(), member.admin)).collect();
let now: HashMap<&str, bool> = after.members.iter().map(|member| (member.id.as_str(), member.admin)).collect();
let pending: HashSet<&str> = before.pending.iter().map(String::as_str).collect();
let asking: HashSet<&str> = before.requesting.iter().map(String::as_str).collect();
let mut joined: Vec<&str> = now.keys().copied().filter(|id| !was.contains_key(id)).collect();
joined.sort_unstable();
let mut rejoined = false;
for id in joined {
if id == me {
rejoined = true;
}
lines.push(format!("{} joined the group", person(id, me, &name)));
let one = person(id, me, &name);
let them = if id == me { "you" } else { one.as_str() };
lines.push(if by == id && !pending.contains(id) && !asking.contains(id) {
// Nobody gets themselves into a group without an invitation, except through its link.
format!("{one} joined the group using the group link")
} else if by.is_empty() || by == id {
format!("{one} joined the group")
} else {
format!("{} added {them} to the group", person(by, me, &name))
});
}
let mut stayed: Vec<&str> = now.keys().copied().filter(|id| was.get(id).is_some_and(|admin| *admin != now[id])).collect();
stayed.sort_unstable();
Expand All @@ -453,18 +510,22 @@ pub fn group_delta(before: &GroupSnap, after: &GroupSnap, me: &str, name: impl F
for id in gone {
if id == me {
left = true;
lines.push("You are no longer in this group".to_owned());
} else {
lines.push(format!("{} is no longer in the group", person(id, me, &name)));
}
let one = person(id, me, &name);
let them = if id == me { "you" } else { one.as_str() };
lines.push(if by == id {
format!("{one} left the group")
} else if by.is_empty() {
if id == me { LEFT_GROUP.to_owned() } else { format!("{one} is no longer in the group") }
} else {
format!("{} removed {them} from the group", person(by, me, &name))
});
}
let pending: HashSet<&str> = before.pending.iter().map(String::as_str).collect();
let mut invited: Vec<&str> = after.pending.iter().map(String::as_str).filter(|id| !pending.contains(id) && !now.contains_key(id)).collect();
invited.sort_unstable();
for id in invited {
lines.push(format!("{} was invited", person(id, me, &name)));
}
let asking: HashSet<&str> = before.requesting.iter().map(String::as_str).collect();
let mut requests: Vec<&str> = after.requesting.iter().map(String::as_str).filter(|id| !asking.contains(id)).collect();
requests.sort_unstable();
for id in requests {
Expand All @@ -477,12 +538,12 @@ pub fn group_delta(before: &GroupSnap, after: &GroupSnap, me: &str, name: impl F
pub fn prove_signal_group_rename() -> Result<(), String> {
let before = GroupSnap { title: "Bridge club".into(), ..GroupSnap::default() };
let after = GroupSnap { title: "Wednesday club".into(), ..GroupSnap::default() };
let delta = group_delta(&before, &after, "me", |_| String::new());
let delta = group_delta(&before, &after, "me", "", |_| String::new());
if delta.title.as_deref() != Some("Wednesday club") || delta.lines != ["The group name is now Wednesday club"] || delta.left {
return Err("a renamed group must take the new name and one line".into());
}
let member = GroupSnap { members: vec![MemberSnap { id: "me".into(), admin: false }], ..GroupSnap::default() };
let left = group_delta(&member, &GroupSnap::default(), "me", |_| String::new());
let left = group_delta(&member, &GroupSnap::default(), "me", "", |_| String::new());
if !left.left || left.lines != ["You are no longer in this group"] {
return Err("leaving the group must say so".into());
}
Expand Down Expand Up @@ -2059,9 +2120,15 @@ 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();
}
// Someone out of the group for good is told so; someone invited, or waiting to
// be let in, is not.
row.read_only_reason = if !group.member && !group.waiting {
LEFT_GROUP.to_owned()
} else if group.member && group.announcements_only && !is_admin {
"Only admins can send messages".to_owned()
} else {
String::new()
};
row.rights = rights;
row.avatar = ctx.avatar_of(&row.id);
let _ = ctx.conversation(&row);
Expand All @@ -2085,11 +2152,15 @@ fn apply(account: &Account, event: Event) {
} else {
known.as_ref().is_some_and(|row| row.read_only)
};
row.read_only_reason = if left {
LEFT_GROUP.to_owned()
} else if rejoined {
String::new()
} else {
known.as_ref().map(|row| row.read_only_reason.clone()).unwrap_or_default()
};
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 @@ -7629,13 +7700,82 @@ mod tests {
fn rejoining_a_group_sets_rejoined_and_clears_left() {
let out = GroupSnap::default();
let inside = GroupSnap { members: vec![MemberSnap { id: "me".into(), admin: false }], ..GroupSnap::default() };
let left = group_delta(&inside, &out, "me", |_| String::new());
let left = group_delta(&inside, &out, "me", "", |_| String::new());
assert!(left.left && !left.rejoined);
let back = group_delta(&out, &inside, "me", |_| String::new());
let back = group_delta(&out, &inside, "me", "", |_| String::new());
assert!(!back.left && back.rejoined);
assert_eq!(back.lines, ["You joined the group"]);
}

/// One group: me, Grace and Alan.
fn club() -> GroupSnap {
GroupSnap { members: vec![MemberSnap { id: "me".into(), admin: true }, MemberSnap { id: "grace".into(), admin: false }, MemberSnap { id: "alan".into(), admin: false }], ..GroupSnap::default() }
}

/// The same members but one.
fn minus(members: Vec<MemberSnap>, id: &str) -> Vec<MemberSnap> {
members.into_iter().filter(|member| member.id != id).collect()
}

fn named(id: &str) -> String {
match id {
"grace" => "Grace Ombra".into(),
"alan" => "Alan Ferro".into(),
_ => String::new(),
}
}

#[test]
fn a_change_is_named_to_its_author_only_when_the_message_announces_it() {
let before = club();
let alan_gone = GroupSnap { members: minus(before.members.clone(), "alan"), ..GroupSnap::default() };
// The message that tells of the change carries it, and names the revision stored.
let said = |step: GroupStep| step.names_author(&before, &alan_gone);
let whole = GroupStep { author: "grace", announces: true, told: 6, previous: 5, stored: 6, from_server: true };
assert!(said(whole));
// Whoever wrote next did not make the change.
assert!(!said(GroupStep { announces: false, ..whole }));
// Two revisions at once may be two people's work.
assert!(!said(GroupStep { previous: 4, ..whole }));
// A group made here, after the server refused to hand it over, says nothing about who.
assert!(!said(GroupStep { from_server: false, ..whole }));
// The message names another revision than the one stored.
assert!(!said(GroupStep { told: 5, ..whole }));
assert!(!said(GroupStep { told: 7, ..whole }));
// Someone who is not a member before or after did not make it.
assert!(!said(GroupStep { author: "stranger", ..whole }));
// The one who left, or who joined, sent it themselves.
let alan_left = GroupStep { author: "alan", ..whole };
assert!(alan_left.names_author(&before, &alan_gone));
let alan_back = before.clone();
assert!(GroupStep { author: "alan", ..whole }.names_author(&alan_gone, &alan_back));
}

#[test]
fn a_group_delta_names_who_added_who_removed_and_who_left() {
let full = club();
let alan_out = GroupSnap { members: minus(full.members.clone(), "alan"), ..GroupSnap::default() };
// Grace adds Alan, and Alan gets in through the link himself.
assert_eq!(group_delta(&alan_out, &full, "me", "grace", named).lines, ["Grace Ombra added Alan Ferro to the group"]);
assert_eq!(group_delta(&alan_out, &full, "me", "alan", named).lines, ["Alan Ferro joined the group using the group link"]);
// Someone who was invited first joined by taking the invitation.
let invited = GroupSnap { pending: vec!["alan".into()], ..alan_out.clone() };
assert_eq!(group_delta(&invited, &full, "me", "alan", named).lines, ["Alan Ferro joined the group"]);
// Leaving and being removed read differently, and this account reads as "you".
assert_eq!(group_delta(&full, &alan_out, "me", "alan", named).lines, ["Alan Ferro left the group"]);
assert_eq!(group_delta(&full, &alan_out, "me", "grace", named).lines, ["Grace Ombra removed Alan Ferro from the group"]);
let me_out = GroupSnap { members: minus(full.members.clone(), "me"), ..GroupSnap::default() };
assert_eq!(group_delta(&full, &me_out, "me", "grace", named).lines, ["Grace Ombra removed you from the group"]);
assert_eq!(group_delta(&full, &me_out, "me", "me", named).lines, ["You left the group"]);
assert_eq!(group_delta(&me_out, &full, "me", "grace", named).lines, ["Grace Ombra added you to the group"]);
// Without a name for who did it, the lines stay as they were.
assert_eq!(group_delta(&alan_out, &full, "me", "", named).lines, ["Alan Ferro joined the group"]);
assert_eq!(group_delta(&full, &alan_out, "me", "", named).lines, ["Alan Ferro is no longer in the group"]);
assert_eq!(group_delta(&full, &me_out, "me", "", named).lines, [LEFT_GROUP]);
let removed = group_delta(&full, &me_out, "me", "grace", named);
assert!(removed.left && !removed.rejoined);
}

#[test]
fn a_group_is_seen_only_when_every_other_member_has_read() {
super::prove_signal_message_info().unwrap();
Expand Down
Loading
Loading