diff --git a/crates/chatd/src/adapters/signal.rs b/crates/chatd/src/adapters/signal.rs index 02671b66..ab02617c 100644 --- a/crates/chatd/src/adapters/signal.rs +++ b/crates/chatd/src/adapters/signal.rs @@ -1517,6 +1517,16 @@ impl Account { fn live(&self) -> MutexGuard<'_, Live> { self.live.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } + + /// The picker's sticker packs, read from this account's file the first time they are asked for. + fn sticker_packs(&self) -> Vec { + let mut live = self.live(); + if !live.stickers_loaded { + live.sticker_packs = read_sticker_packs(&live.stickers_path); + live.stickers_loaded = true; + } + live.sticker_packs.clone() + } } pub fn start(ctx: Context, session: &str, inbox: Receiver) -> Result<(), String> { @@ -2671,43 +2681,7 @@ fn apply(account: &Account, event: Event) { write_sticker_packs(&live.stickers_path, &live.sticker_packs); account.ctx.hub.catalogs.forget_matching(|(acct, kind, ..)| *acct == account.ctx.account && *kind == CatalogKind::Stickers); } - Event::StickerPackOp { pack_id, pack_key, install } => { - if install { - let mut pack = account - .wire - .preview_sticker_pack(&pack_id, &pack_key) - .unwrap_or_else(|_| wire::StickerPackInfo { - id: pack_id.clone(), - key: pack_key.clone(), - title: "Sticker pack".to_owned(), - author: String::new(), - cover_id: Some(0), - stickers: Vec::new(), - installed: true, - }); - pack.installed = true; - let mut live = account.live(); - if !live.stickers_loaded { - live.sticker_packs = read_sticker_packs(&live.stickers_path); - live.stickers_loaded = true; - } - if let Some(existing) = live.sticker_packs.iter_mut().find(|p| p.id == pack.id) { - *existing = pack; - } else if live.sticker_packs.len() < 128 { - live.sticker_packs.push(pack); - } - write_sticker_packs(&live.stickers_path, &live.sticker_packs); - } else { - let mut live = account.live(); - if !live.stickers_loaded { - live.sticker_packs = read_sticker_packs(&live.stickers_path); - live.stickers_loaded = true; - } - live.sticker_packs.retain(|p| p.id != pack_id); - write_sticker_packs(&live.stickers_path, &live.sticker_packs); - } - account.ctx.hub.catalogs.forget_matching(|(acct, kind, ..)| *acct == account.ctx.account && *kind == CatalogKind::Stickers); - } + Event::StickerPackOp { pack_id, pack_key, install } => apply_sticker_pack_op(account, &pack_id, &pack_key, install), Event::Story(story) => apply_story(account, story), Event::StoryReaction { by, story_author, story_sent, emoji, removed, .. } => { if account.live().stories_disabled { @@ -2980,6 +2954,65 @@ fn apply_storage_sync(account: &Account, snapshot: wire::StorageSnapshot) { if disabled_stories { let _ = ctx.forget_conversation(STORIES_CONVERSATION); } + apply_storage_sticker_packs(account, snapshot.sticker_packs); +} + +/// Puts a pack another device installed into the picker's list, or takes a removed one out. The +/// pack's manifest is fetched as for any install, so the list holds its title and stickers. +fn apply_sticker_pack_op(account: &Account, pack_id: &str, pack_key: &str, install: bool) { + if install { + // Asked of the wire before the list is touched, so no lock is held on the way to Signal. + let mut pack = account + .wire + .preview_sticker_pack(pack_id, pack_key) + .unwrap_or_else(|_| wire::StickerPackInfo { + id: pack_id.to_owned(), + key: pack_key.to_owned(), + title: "Sticker pack".to_owned(), + author: String::new(), + cover_id: Some(0), + stickers: Vec::new(), + installed: true, + }); + pack.installed = true; + let mut live = account.live(); + if !live.stickers_loaded { + live.sticker_packs = read_sticker_packs(&live.stickers_path); + live.stickers_loaded = true; + } + if let Some(existing) = live.sticker_packs.iter_mut().find(|p| p.id == pack.id) { + *existing = pack; + } else if live.sticker_packs.len() < 128 { + live.sticker_packs.push(pack); + } + write_sticker_packs(&live.stickers_path, &live.sticker_packs); + } else { + let mut live = account.live(); + if !live.stickers_loaded { + live.sticker_packs = read_sticker_packs(&live.stickers_path); + live.stickers_loaded = true; + } + live.sticker_packs.retain(|p| p.id != pack_id); + write_sticker_packs(&live.stickers_path, &live.sticker_packs); + } + account.ctx.hub.catalogs.forget_matching(|(acct, kind, ..)| *acct == account.ctx.account && *kind == CatalogKind::Stickers); +} + +/// Applies the sticker pack records of a Storage Service snapshot, which is read on every storage +/// change: a pack this device already holds, stickers and all, is not fetched from Signal again, +/// and a removal is always carried out. +fn apply_storage_sticker_packs(account: &Account, packs: Vec) { + let held: Vec = account + .sticker_packs() + .into_iter() + .filter(|pack| pack.installed && !pack.stickers.is_empty()) + .map(|pack| pack.id) + .collect(); + for pack in packs { + if pack.removed || !held.contains(&pack.id) { + apply_sticker_pack_op(account, &pack.id, &pack.key, !pack.removed); + } + } } fn ensure_stories_row(account: &Account) { @@ -5830,14 +5863,7 @@ fn pin_message(account: &Account, conversation_id: &str, message_id: &str, pinne fn catalog(account: &Account, kind: CatalogKind, query: &str, cursor: Option<&str>) -> Result { if kind == CatalogKind::Stickers { let q = query.trim().to_ascii_lowercase(); - let packs = { - let mut live = account.live(); - if !live.stickers_loaded { - live.sticker_packs = read_sticker_packs(&live.stickers_path); - live.stickers_loaded = true; - } - live.sticker_packs.clone() - }; + let packs = account.sticker_packs(); let mut items = Vec::new(); let mut media = Vec::new(); { diff --git a/crates/chatd/src/adapters/signal/real.rs b/crates/chatd/src/adapters/signal/real.rs index ee7375dc..3040f9ce 100644 --- a/crates/chatd/src/adapters/signal/real.rs +++ b/crates/chatd/src/adapters/signal/real.rs @@ -14,7 +14,8 @@ use super::wire::{ GifEntry, GroupAccess, GroupCallCredentials, GroupCallInfo, GroupCallSignal, GroupEdit, GroupInfo, GroupMember, GroupMembers, HangupKind, HistoryTransfer, IdentityState, InviteLinkMode, LinkPreview, Linked, Linker, MessageRequestAction, OwnCard, Peer, PersonProfile, Pointer, Quote, QuotedAttachment, SafetyNumber, Sticker, - StickerEntry, StickerPackInfo, StorageAccount, StorageContact, StorageGroup, StorageSnapshot, StoryContext, + StickerEntry, StickerPackInfo, StorageAccount, StorageContact, StorageGroup, StorageSnapshot, StorageStickerPack, + StoryContext, StoryDistributionList, StoryMessageData, StoryText, Text, TransferOutcome, TransferProgress, TurnServer, Wire, }; use super::{group_delta, GroupRevisions, GroupSnap, MemberSnap, Saved}; @@ -39,8 +40,8 @@ use presage::proto::{ body_range::{AssociatedValue, Style as RangeStyle}, call_message, chat_folder_record, contact_record, conversation_identifier, data_message, receipt_message, recipient, storage_record, sync_message, typing_message, verified, AddressableMessage, BodyRange, CallMessage, - ConversationIdentifier, DataMessage, EditMessage, GroupContextV2, ReceiptMessage, SyncMessage, TypingMessage, - Verified, + ConversationIdentifier, DataMessage, EditMessage, GroupContextV2, ReadOperation, ReceiptMessage, StorageItem, + StorageItems, SyncMessage, TypingMessage, Verified, }; use presage::store::{ContentsStore, StateStore}; use presage::Manager; @@ -1047,23 +1048,30 @@ impl Session { None } - /// Reads Signal's encrypted Storage Service manifest and items (contact, group, account, folder records) - /// in read-only mode to seed contacts, groups, pins, archive, mutes, nicknames, notes, and settings. + /// Reads Signal's encrypted Storage Service manifest and items (contact, group, account, folder and + /// sticker pack records) in read-only mode to seed contacts, groups, pins, archive, mutes, nicknames, + /// notes, settings, and the sticker packs the other devices installed. async fn sync_storage(&mut self) { let Some(storage_key) = self.storage_key().await else { return; }; + let storage_key_bytes = storage_key.inner; let Ok(credentials) = self.credentials() else { return; }; - let push = PushService::new(SignalServers::Production, Some(credentials), "tinyclient"); + let push = PushService::new(SignalServers::Production, Some(credentials.clone()), "tinyclient"); let Ok(storage) = StorageService::new(push, storage_key).await else { return; }; let Ok(manifest) = storage.manifest().await else { return; }; - let keys: Vec> = manifest.identifiers.into_iter().map(|id| id.raw).collect(); + // A sticker pack record is not one of the library's record types, so its identifiers are + // read apart from the rest. + let (packs, others): (Vec<_>, Vec<_>) = + manifest.identifiers.into_iter().partition(|id| id.r#type == STICKER_PACK_RECORD_TYPE); + let pack_ids: Vec> = packs.into_iter().map(|id| id.raw).collect(); + let keys: Vec> = others.into_iter().map(|id| id.raw).collect(); if keys.is_empty() { return; } @@ -1071,6 +1079,14 @@ impl Session { let Ok(records) = storage.read_items(keys, ikm).await else { return; }; + let mut sticker_packs = Vec::new(); + if !pack_ids.is_empty() { + // Read sealed, as the server sends them, and opened here (`sticker_packs_in_items`). + let reader = PushService::new(SignalServers::Production, Some(credentials), "tinyclient"); + if let Ok(items) = sealed_storage_items(&reader, pack_ids).await { + sticker_packs = sticker_packs_in_items(&storage_key_bytes, &items, ikm); + } + } self.blocked_known = true; let join_name = |given: &str, family: &str| -> String { [given.trim(), family.trim()] @@ -1272,12 +1288,18 @@ impl Session { _ => {} } } - if !contacts.is_empty() || !groups.is_empty() || account_record.is_some() || !distribution_lists.is_empty() { + if !contacts.is_empty() + || !groups.is_empty() + || account_record.is_some() + || !distribution_lists.is_empty() + || !sticker_packs.is_empty() + { self.tell(Event::StorageSync(StorageSnapshot { contacts, groups, account: account_record, distribution_lists, + sticker_packs, })); } if !folders.is_empty() { @@ -4104,6 +4126,144 @@ async fn fetch_picture( } } +/// `ManifestRecord.Identifier.Type.STICKER_PACK`: an installed sticker pack in the Storage Service. +const STICKER_PACK_RECORD_TYPE: i32 = 6; + +/// The most this adapter reads of the sealed items behind the sticker pack records in one answer. +/// A record is under 200 bytes, so this holds every pack an account could install and stops +/// anything larger. +const MAX_STICKER_RECORD_BYTES: usize = 256 * 1024; + +/// An `InstalledStickerPackRecord` of the Storage Service (`StorageService.proto`). The pinned +/// libsignal-service predates it: its `StorageRecord` has no sticker pack field, so its reader +/// decodes each item into the record types it knows and drops this one. +#[derive(prost::Message)] +struct StickerPackRecord { + /// 16 bytes. + #[prost(bytes = "vec", tag = "1")] + pack_id: Vec, + /// 32 bytes; unset on a record that only says the pack was removed. + #[prost(bytes = "vec", tag = "2")] + pack_key: Vec, + /// Where the other devices show the pack in their picker. + #[prost(uint32, tag = "3")] + position: u32, + /// Non-zero when another device removed the pack. + #[prost(uint64, tag = "4")] + deleted_at_timestamp: u64, +} + +/// The key of one Storage Service item, named by its identifier in the manifest: from the +/// manifest's key (`record_ikm`) on accounts since 2024-08, and before that from the account's +/// storage key. libsignal-service keeps its own a private function. `None` when it cannot be made. +fn storage_item_key(storage_key: &[u8; 32], raw_id: &[u8], record_ikm: Option<&[u8]>) -> Option<[u8; 32]> { + use hmac::{Hmac, Mac}; + + const ITEM_KEY_INFO_PREFIX: &[u8] = b"20240801_SIGNAL_STORAGE_SERVICE_ITEM_"; + let mut key = [0u8; 32]; + match record_ikm { + Some(ikm) if !ikm.is_empty() => { + hkdf::Hkdf::::new(None, ikm).expand(&[ITEM_KEY_INFO_PREFIX, raw_id].concat(), &mut key).ok()?; + } + _ => { + let mut mac = as Mac>::new_from_slice(storage_key).ok()?; + mac.update(b"Item_"); + mac.update(base64::Engine::encode(&base64::engine::general_purpose::STANDARD, raw_id).as_bytes()); + key = mac.finalize().into_bytes().into(); + } + } + Some(key) +} + +/// Opens one sealed Storage Service item to the bytes before decoding, which is where the +/// library's reader loses a sticker pack. `None` when the item does not open. +fn open_storage_item(storage_key: &[u8; 32], item: &StorageItem, record_ikm: Option<&[u8]>) -> Option> { + use aes_gcm::aead::Aead; + use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; + + let key = storage_item_key(storage_key, &item.key, record_ikm)?; + // The item is `iv (12 bytes) || ciphertext || tag` under AES-256-GCM. + let (iv, sealed) = item.value.split_at_checked(12)?; + Aes256Gcm::new(Key::::from_slice(&key[..])).decrypt(Nonce::from_slice(iv), sealed).ok() +} + +/// Reads the sealed Storage Service items behind `ids` as the server sends them, without decoding +/// them: the library's own reader answers only the records it has decoded. An answer larger than +/// [`MAX_STICKER_RECORD_BYTES`] is refused. +async fn sealed_storage_items(push: &PushService, ids: Vec>) -> Result, Fault> { + use presage::libsignal_service::configuration::Endpoint; + use presage::libsignal_service::push_service::{HttpAuth, HttpAuthOverride}; + + // The Storage Service takes a login of its own, fetched with the account's. + #[derive(serde::Deserialize)] + struct StorageAuth { + #[serde(default)] + username: String, + #[serde(default)] + password: String, + } + let refused = |err: reqwest::Error| Fault::Net(err.to_string()); + let resp = push + .request(reqwest::Method::GET, Endpoint::service("/v1/storage/auth"), HttpAuthOverride::NoOverride) + .map_err(|err| Fault::Net(err.to_string()))? + .send() + .await + .map_err(refused)?; + if !resp.status().is_success() { + return Err(Fault::Net(format!("storage auth: {}", resp.status()))); + } + let auth: StorageAuth = resp.json().await.map_err(refused)?; + let resp = push + .request( + reqwest::Method::PUT, + Endpoint::storage("/v1/storage/read"), + HttpAuthOverride::Identified(HttpAuth { username: auth.username, password: auth.password }), + ) + .map_err(|err| Fault::Net(err.to_string()))? + .header("Content-Type", "application/x-protobuf") + .body(prost::Message::encode_to_vec(&ReadOperation { read_key: ids })) + .send() + .await + .map_err(refused)?; + if !resp.status().is_success() { + return Err(Fault::Net(format!("storage read: {}", resp.status()))); + } + let mut bytes = Vec::new(); + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(refused)?; + if bytes.len() + chunk.len() > MAX_STICKER_RECORD_BYTES { + return Err(Fault::Refused("Signal's sticker pack records are larger than expected.".to_owned())); + } + bytes.extend_from_slice(&chunk); + } + let items: StorageItems = prost::Message::decode(bytes.as_slice()).map_err(|err| Fault::Net(err.to_string()))?; + Ok(items.items) +} + +/// The sticker pack records among `items`, in the order the other devices show them: by +/// `position`, then by pack id. A record that does not open, or that names no pack this client +/// can fetch, is left out. That is the rule Signal's own apps keep: an id of 16 bytes, and a key +/// of 32 unless the pack was removed. +fn sticker_packs_in_items(storage_key: &[u8; 32], items: &[StorageItem], record_ikm: Option<&[u8]>) -> Vec { + let mut packs: Vec<(u32, StorageStickerPack)> = items + .iter() + .filter_map(|item| { + let opened = open_storage_item(storage_key, item, record_ikm)?; + let record: StickerPackRecord = prost::Message::decode(opened.as_slice()).ok()?; + let removed = record.deleted_at_timestamp != 0; + if record.pack_id.len() != 16 || (!removed && record.pack_key.len() != 32) { + return None; + } + // A removal keeps no key, whatever it was sealed with. + let key = if removed { String::new() } else { hex(&record.pack_key) }; + Some((record.position, StorageStickerPack { id: hex(&record.pack_id), key, removed })) + }) + .collect(); + packs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.id.cmp(&b.1.id))); + packs.into_iter().map(|(_, pack)| pack).collect() +} + async fn preview_sticker_pack_with( vault: &Vault, pack_id: &str, @@ -4963,4 +5123,93 @@ mod tests { drop(rx); assert!(reply.is_closed()); } + + /// Seals `plain` the way the Storage Service keeps an item: `iv (12 bytes) || ciphertext || tag`. + fn sealed(key: &[u8; 32], plain: &[u8]) -> Vec { + use aes_gcm::aead::{Aead, KeyInit}; + use aes_gcm::{Aes256Gcm, Key, Nonce}; + + let iv = [7u8; 12]; + let ciphertext = Aes256Gcm::new(Key::::from_slice(&key[..])) + .encrypt(Nonce::from_slice(&iv[..]), plain) + .expect("AES-256-GCM seals"); + let mut value = iv.to_vec(); + value.extend_from_slice(&ciphertext); + value + } + + #[test] + fn a_storage_item_opens_as_the_library_sealed_it() { + use presage::proto::{storage_record, GroupV2Record, StorageRecord}; + + // The library derives an item's key itself and keeps that private. An item it seals has to + // open here to the same record, on an account with a manifest key and on an older one. + let storage_key = StorageServiceKey { inner: [9u8; 32] }; + let ikm = [4u8; 32]; + let record = StorageRecord { + record: Some(storage_record::Record::GroupV2(GroupV2Record { master_key: vec![5; 32], ..Default::default() })), + }; + for ikm in [None, Some(ikm.as_slice())] { + let item = StorageService::encrypt_item(&storage_key, vec![0xab; 16], &record, ikm); + let opened = open_storage_item(&storage_key.inner, &item, ikm).expect("the sealed item opens"); + let decoded: StorageRecord = ::decode(opened.as_slice()).unwrap(); + assert!(decoded == record, "another record came out"); + + // Another item's identifier does not open it. On an account with no manifest key the + // item is keyed by the account's storage key, so another account's does not open it. + let mut renamed = item.clone(); + renamed.key = vec![0xac; 16]; + assert!(open_storage_item(&storage_key.inner, &renamed, ikm).is_none()); + if ikm.is_none() { + let stranger = StorageServiceKey { inner: [8u8; 32] }; + assert!(open_storage_item(&stranger.inner, &item, ikm).is_none()); + } + } + // An item shorter than its iv is not opened. + let item = StorageService::encrypt_item(&storage_key, vec![0xab; 16], &record, None); + for cut in 0..12 { + let mut short = item.clone(); + short.value.truncate(cut); + assert!(open_storage_item(&storage_key.inner, &short, None).is_none()); + } + } + + #[test] + fn sticker_pack_records_are_read_in_the_pickers_order_and_bad_ones_are_left_out() { + let record = |pack_id: Vec, pack_key: Vec, position: u32, deleted_at_timestamp: u64| StickerPackRecord { + pack_id, + pack_key, + position, + deleted_at_timestamp, + }; + let cats = record(vec![1; 16], vec![2; 32], 1, 0); + let dogs = record(vec![3; 16], vec![4; 32], 0, 0); + let removed = record(vec![5; 16], vec![6; 32], 0, 1_700_000_000_000); + let short_id = record(vec![6; 8], vec![4; 32], 0, 0); + let keyless = record(vec![7; 16], Vec::new(), 0, 0); + + // An older account names each item in an HMAC of the storage key. + let storage_key = [9u8; 32]; + let mut items: Vec = [cats, dogs, removed, short_id, keyless] + .iter() + .enumerate() + .map(|(at, record)| { + let raw_id = [6u8, at as u8]; + let key = storage_item_key(&storage_key, &raw_id, None).expect("an item key"); + StorageItem { key: raw_id.to_vec(), value: sealed(&key, &prost::Message::encode_to_vec(record)) } + }) + .collect(); + items.push(StorageItem { key: vec![6, 9], value: vec![1, 2, 3] }); + + // By position, then by id. A removed pack keeps its id and no key. An id of the wrong + // length, a pack with no key and bytes that do not open are left out. + assert_eq!( + sticker_packs_in_items(&storage_key, &items, None), + vec![ + StorageStickerPack { id: hex(&[3; 16]), key: hex(&[4; 32]), removed: false }, + StorageStickerPack { id: hex(&[5; 16]), key: String::new(), removed: true }, + StorageStickerPack { id: hex(&[1; 16]), key: hex(&[2; 32]), removed: false }, + ] + ); + } } diff --git a/crates/chatd/src/adapters/signal/wire.rs b/crates/chatd/src/adapters/signal/wire.rs index ee58267b..e1ff97b9 100644 --- a/crates/chatd/src/adapters/signal/wire.rs +++ b/crates/chatd/src/adapters/signal/wire.rs @@ -500,6 +500,20 @@ pub fn resolve_story_recipients( out } +/// One sticker pack record decrypted from Signal's Storage Service (`InstalledStickerPackRecord`). +/// The record names a pack; its stickers are fetched from Signal's CDN as for any install. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct StorageStickerPack { + /// 16-byte pack id, lowercase hex (32 chars). + pub id: String, + /// 32-byte pack key, lowercase hex (64 chars). Empty on a removal. + #[serde(default)] + pub key: String, + /// Another device removed the pack; the record only says so. + #[serde(default)] + pub removed: bool, +} + /// Full read-only snapshot decrypted from Signal's Storage Service manifest. #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct StorageSnapshot { @@ -511,6 +525,9 @@ pub struct StorageSnapshot { pub account: Option, #[serde(default)] pub distribution_lists: Vec, + /// The installed sticker packs, in the order the other devices show them. + #[serde(default)] + pub sticker_packs: Vec, } /// One Signal chat folder from the storage service (`ChatFolderRecord`). diff --git a/crates/chatd/tests/signal.rs b/crates/chatd/tests/signal.rs index 00d0e765..91a34610 100644 --- a/crates/chatd/tests/signal.rs +++ b/crates/chatd/tests/signal.rs @@ -2283,6 +2283,65 @@ fn storage_service_manifest_seeds_contacts_groups_pins_archive_and_mutes_on_firs }); } +#[test] +fn sticker_packs_the_storage_service_holds_fill_the_picker_and_a_removal_takes_one_out() { + // Both packs were installed on the phone before this device was linked: it never hears the + // sync message that announced them, only what the Storage Service keeps, an id and a key. + let pack_id = "0123456789abcdef0123456789abcdef"; + let pack_key = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let other_id = "fedcba9876543210fedcba9876543210"; + let other_key = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + let installed = |id: &str, key: &str| format!(r#"{{"id":"{id}","key":"{key}"}}"#); + let previews = |world: &World, id: &str| world.calls().iter().filter(|call| **call == format!("sticker-pack-preview {id}")).count(); + let mut world = World::start_with_setup(Some(SESSION), |dir| { + let manifest = format!(r#"{{"sticker_packs":[{},{}]}}"#, installed(pack_id, pack_key), installed(other_id, other_key)); + std::fs::write(dir.join("signal.storage.json"), &manifest).unwrap(); + }); + world.connected(); + + let stickers = |world: &World| -> Vec { + match world.ask(Request::Catalog { + account: account(), + space: None, + kind: protocol::CatalogKind::Stickers, + query: String::new(), + cursor: None, + }) { + Response::Catalog { items, .. } => items, + other => panic!("{other:?}"), + } + }; + // Each pack's manifest is fetched as for any install, so the picker holds the pack's stickers. + let items = world.until("both packs from the storage are in the picker", || { + let items = stickers(&world); + (items.len() == 4).then_some(items) + }); + let mut ids: Vec = items.iter().map(|item| item.id.clone()).collect(); + ids.sort(); + assert_eq!(ids, [format!("{pack_id}:0"), format!("{pack_id}:1"), format!("{other_id}:0"), format!("{other_id}:1")]); + assert!(items.iter().all(|item| item.pack == "Signal Cats"), "{items:?}"); + assert_eq!(previews(&world, pack_id), 1); + assert_eq!(previews(&world, other_id), 1); + + // A pack removed on the phone leaves the picker. The storage is read on every change, so a + // pack this device already holds is not fetched from Signal again. + let updated = format!(r#"{{"sticker_packs":[{{"id":"{pack_id}","removed":true}},{}]}}"#, installed(other_id, other_key)); + world.steer(&format!("storage-manifest {updated}")); + world.until("the removed pack is out of the picker and the other stays", || { + let items = stickers(&world); + (items.len() == 2 && items.iter().all(|item| item.id.starts_with(other_id))).then_some(()) + }); + assert_eq!(previews(&world, other_id), 1, "a held pack was fetched again"); + + // The same after a restart: the held pack is read from this device's list, not fetched anew. + std::fs::write(world.dir.join("signal.storage.json"), &updated).unwrap(); + world.restart(); + world.connected(); + world.until("the held pack is in the picker after the restart", || (!stickers(&world).is_empty()).then_some(())); + assert!(stickers(&world).iter().all(|item| item.id.starts_with(other_id))); + assert_eq!(previews(&world, other_id), 1, "the held pack was fetched again after the restart"); +} + #[test] fn safety_number_change_writes_system_rows_and_blocks_verified_send_until_approved() { let world = World::linked(); diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh b/e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh new file mode 100644 index 00000000..07137b52 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.linux.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-sticker-packs-from-storage 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-sticker-packs-from-storage/drive.macos.sh b/e2e/scenarios/signal-sticker-packs-from-storage/drive.macos.sh new file mode 100644 index 00000000..5fb841f5 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.macos.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# signal-sticker-packs-from-storage 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-sticker-packs-from-storage/drive.py b/e2e/scenarios/signal-sticker-packs-from-storage/drive.py new file mode 100644 index 00000000..028941a2 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""A sticker pack the phone keeps in Signal's storage service is in the picker of a freshly linked +device, and a removal there takes it out. + +Starts this build's chatd with the scripted Signal wire (TINYCLIENT_SIGNAL_FAKE) on an isolated +TINYCLIENT_DIR, steers it over its control file the way tests/signal.rs does, and speaks chatd's +real socket. The storage file the scripted wire reads as the account's storage service names one +pack this device never heard a sync message about; the picker's Stickers catalog must list that +pack's two stickers, fetched as for any install. A later storage read that marks the pack removed +must empty the catalog. A build from before the fix lists no sticker at all, because it does not +read sticker pack records from the storage service, 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"}) +# A 16-byte pack id and a 32-byte pack key, as the storage service keeps them. +PACK = "0123456789abcdef0123456789abcdef" +PACK_KEY = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + +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() + # What the storage service holds: one pack installed on the phone before this device was linked. + with open(os.path.join(data, "signal.storage.json"), "w", encoding="utf-8") as handle: + handle.write(json.dumps({"sticker_packs": [{"id": PACK, "key": PACK_KEY}]})) + 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 account(): + return {"network": "signal", "account": ME} + + +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 stickers(chat): + answer = ask(chat, {"op": "catalog", "account": account(), "kind": "stickers"}) + return (answer or {}).get("items") or [] + + +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)) + + # The pack's manifest is fetched as for any install, so the picker holds the pack's stickers. + items = wait("the picker lists the stickers of the pack the storage service holds", chat, lambda: stickers(chat) or None) + if items is not None: + step("they are the pack's two stickers, named after it", sorted(item.get("id") for item in items) == [PACK + ":0", PACK + ":1"] and all(item.get("pack") == "Signal Cats" for item in items)) + + # Removed on the phone: the next read of the storage service takes the pack out of the picker. + steer(control, 'storage-manifest {"sticker_packs":[{"id":"%s","removed":true}]}' % PACK) + wait("a pack removed on the phone leaves the picker", chat, lambda: (not stickers(chat)) or None) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 b/e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 new file mode 100644 index 00000000..68b2c38b --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/drive.windows.ps1 @@ -0,0 +1,17 @@ +# signal-sticker-packs-from-storage 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-sticker-packs-from-storage/scenario.json b/e2e/scenarios/signal-sticker-packs-from-storage/scenario.json new file mode 100644 index 00000000..4fdd0d06 --- /dev/null +++ b/e2e/scenarios/signal-sticker-packs-from-storage/scenario.json @@ -0,0 +1,12 @@ +{ + "id": "signal-sticker-packs-from-storage", + "title": "A sticker pack the phone keeps in the storage service is in the picker on a freshly linked device, and a removal takes it out", + "platforms": ["windows", "macos", "linux"], + "not_applicable": { + "android": "The phone proof build does not run desktop chatd. The sticker pack list is read and kept by the desktop's chatd.", + "ios": "The phone proof build does not run desktop chatd. The sticker pack list is read and kept by the desktop's chatd." + }, + "needs": [], + "release": false, + "max_still_seconds": 60 +}