Skip to main content

iris_chat_protocol/protocol_engine/
engine_invite_owner.rs

1const INVITE_OWNER_APP_KEYS_MAX_EVENT_BYTES: usize = 64 * 1024;
2const INVITE_OWNER_APP_KEYS_MAX_DEVICES: usize = 64;
3const INVITE_OWNER_APP_KEYS_MAX_FUTURE_SKEW_SECS: u64 = 5 * 60;
4
5impl ProtocolEngine {
6    fn update_invite_owner_app_keys_evidence(
7        &mut self,
8        owner: NdrOwnerPubkey,
9        event: &Event,
10        app_keys: &AppKeys,
11    ) -> bool {
12        if !app_keys_event_is_acceptable_for_owner(event.pubkey, event, unix_now().get()) {
13            return false;
14        }
15        let previous = self.invite_owner_app_keys_evidence.get(&owner).cloned();
16        let created_at_secs = event.created_at.as_secs();
17        let next = match previous.clone() {
18            None => ProtocolAppKeysEvidence::Verified(Box::new(event.clone())),
19            Some(ProtocolAppKeysEvidence::Ambiguous {
20                created_at_secs: ambiguous_at,
21            }) if created_at_secs > ambiguous_at => {
22                ProtocolAppKeysEvidence::Verified(Box::new(event.clone()))
23            }
24            Some(ProtocolAppKeysEvidence::Ambiguous {
25                created_at_secs: ambiguous_at,
26            }) => ProtocolAppKeysEvidence::Ambiguous {
27                created_at_secs: ambiguous_at,
28            },
29            Some(ProtocolAppKeysEvidence::Verified(current)) => {
30                let current_created_at = current.created_at.as_secs();
31                if created_at_secs > current_created_at {
32                    ProtocolAppKeysEvidence::Verified(Box::new(event.clone()))
33                } else if created_at_secs < current_created_at || current.id == event.id {
34                    ProtocolAppKeysEvidence::Verified(current)
35                } else {
36                    let same_roster =
37                        AppKeys::from_event(current.as_ref()).is_ok_and(|current_app_keys| {
38                            app_keys_device_pubkeys(&current_app_keys)
39                                == app_keys_device_pubkeys(app_keys)
40                        });
41                    if same_roster {
42                        ProtocolAppKeysEvidence::Verified(if event.id < current.id {
43                            Box::new(event.clone())
44                        } else {
45                            current
46                        })
47                    } else {
48                        ProtocolAppKeysEvidence::Ambiguous { created_at_secs }
49                    }
50                }
51            }
52        };
53        let changed = previous.as_ref() != Some(&next);
54        self.invite_owner_app_keys_evidence.insert(owner, next);
55        changed
56    }
57
58    pub fn import_private_invite_session_once(
59        &mut self,
60        response_event_id: &str,
61        owner_pubkey: PublicKey,
62        authenticated_device: PublicKey,
63        state: SessionState,
64        now: UnixSeconds,
65    ) -> anyhow::Result<ProtocolInviteSessionImportOutcome> {
66        if self
67            .processed_private_invite_response_ids
68            .iter()
69            .any(|processed| processed == response_event_id)
70        {
71            return Ok(ProtocolInviteSessionImportOutcome::AlreadyImported);
72        }
73        if owner_pubkey != authenticated_device {
74            match self.invite_owner_app_keys_membership(
75                ndr_owner(owner_pubkey),
76                authenticated_device,
77            ) {
78                Some(true) => {}
79                Some(false) => {
80                    return Ok(ProtocolInviteSessionImportOutcome::Blocked(
81                        ProtocolAcceptInviteBlock::UnauthorizedDevice {
82                            owner_pubkey,
83                            device_pubkey: authenticated_device,
84                        },
85                    ))
86                }
87                None => {
88                    return Ok(ProtocolInviteSessionImportOutcome::Blocked(
89                        ProtocolAcceptInviteBlock::MissingOwnerRoster {
90                            owner_pubkey,
91                            device_pubkey: authenticated_device,
92                        },
93                    ))
94                }
95            }
96        }
97
98        let checkpoint = self.state_checkpoint();
99        self.session_manager.import_session_state(
100            ndr_owner(owner_pubkey),
101            ndr_device(authenticated_device),
102            state,
103            NdrUnixSeconds(now.get()),
104        );
105        self.processed_private_invite_response_ids
106            .push(response_event_id.to_string());
107        let excess = self
108            .processed_private_invite_response_ids
109            .len()
110            .saturating_sub(PROCESSED_PRIVATE_INVITE_RESPONSE_LIMIT);
111        if excess > 0 {
112            self.processed_private_invite_response_ids.drain(0..excess);
113        }
114        self.invalidate_known_message_author_cache();
115        if let Err(error) = self.persist() {
116            self.restore_checkpoint(checkpoint);
117            return Err(error);
118        }
119        let retry_batch = self.retry_pending_protocol(NdrUnixSeconds(now.get()))?;
120        Ok(ProtocolInviteSessionImportOutcome::Imported(retry_batch))
121    }
122
123    fn invite_owner_app_keys_membership(
124        &self,
125        owner: NdrOwnerPubkey,
126        device: PublicKey,
127    ) -> Option<bool> {
128        self.invite_owner_exact_app_keys_membership(owner, device)
129    }
130
131    fn invite_owner_exact_app_keys_membership(
132        &self,
133        owner: NdrOwnerPubkey,
134        device: PublicKey,
135    ) -> Option<bool> {
136        match self.invite_owner_app_keys_evidence.get(&owner)? {
137            ProtocolAppKeysEvidence::Verified(event) => AppKeys::from_event(event)
138                .ok()
139                .map(|app_keys| app_keys.get_device(&device).is_some()),
140            ProtocolAppKeysEvidence::Ambiguous { .. } => None,
141        }
142    }
143
144    /// Reads only existing protocol state and checks exact signed AppKeys
145    /// evidence. It never creates protocol state or treats a generic
146    /// cached roster projection as authorization.
147    pub fn persisted_invite_owner_device_is_authorized(
148        storage: Arc<dyn StorageAdapter>,
149        local_owner_pubkey: PublicKey,
150        local_device_keys: &Keys,
151        invite_owner_pubkey: PublicKey,
152        invite_device_pubkey: PublicKey,
153    ) -> anyhow::Result<bool> {
154        if invite_owner_pubkey == invite_device_pubkey {
155            return Ok(true);
156        }
157        let local_owner = ndr_owner(local_owner_pubkey);
158        let local_device = ndr_device(local_device_keys.public_key());
159        let Some(engine) = Self::load_persisted_state(
160            storage,
161            local_owner_pubkey,
162            local_owner,
163            local_device,
164            local_device_keys.secret_key().to_secret_bytes(),
165        )?
166        else {
167            return Ok(false);
168        };
169        Ok(matches!(
170            engine.invite_owner_exact_app_keys_membership(
171                ndr_owner(invite_owner_pubkey),
172                invite_device_pubkey,
173            ),
174            Some(true)
175        ))
176    }
177}
178
179fn sanitize_invite_owner_persisted_state(state: &mut ProtocolEnginePersistedState) {
180    state.invite_owner_app_keys_evidence.retain(|owner, evidence| {
181        match evidence {
182            ProtocolAppKeysEvidence::Verified(event) => {
183                public_owner(*owner).is_ok_and(|owner| {
184                    app_keys_event_is_acceptable_for_owner(owner, event, unix_now().get())
185                })
186            }
187            ProtocolAppKeysEvidence::Ambiguous { .. } => true,
188        }
189    });
190    let exact_verified_owners = state
191        .invite_owner_app_keys_evidence
192        .iter()
193        .filter_map(|(owner, evidence)| {
194            matches!(evidence, ProtocolAppKeysEvidence::Verified(_)).then_some(*owner)
195        })
196        .collect::<BTreeSet<_>>();
197    if state.app_keys_provenance_version != PROTOCOL_APP_KEYS_PROVENANCE_VERSION {
198        state.verified_app_keys_owners = exact_verified_owners.clone();
199    } else {
200        state
201            .verified_app_keys_owners
202            .extend(exact_verified_owners.iter().copied());
203    }
204    let excess = state
205        .processed_private_invite_response_ids
206        .len()
207        .saturating_sub(PROCESSED_PRIVATE_INVITE_RESPONSE_LIMIT);
208    if excess > 0 {
209        state.processed_private_invite_response_ids.drain(0..excess);
210    }
211}
212
213/// Verifies the exact signed AppKeys evidence accepted for direct-chat setup.
214/// Profile indexes and reconstructed device lists must never substitute for it.
215pub fn app_keys_event_is_acceptable_for_owner(
216    owner: PublicKey,
217    event: &Event,
218    now_secs: u64,
219) -> bool {
220    let device_tags = event
221        .tags
222        .iter()
223        .filter(|tag| tag.as_slice().first().map(String::as_str) == Some("device"))
224        .collect::<Vec<_>>();
225    event.pubkey == owner
226        && event.created_at.as_secs()
227            <= now_secs.saturating_add(INVITE_OWNER_APP_KEYS_MAX_FUTURE_SKEW_SECS)
228        && serde_json::to_vec(event)
229            .is_ok_and(|bytes| bytes.len() <= INVITE_OWNER_APP_KEYS_MAX_EVENT_BYTES)
230        && device_tags.len() <= INVITE_OWNER_APP_KEYS_MAX_DEVICES
231        && device_tags.iter().all(|tag| {
232            let values = tag.as_slice();
233            values.len() >= 3 && values[2].parse::<u64>().is_ok()
234        })
235        && AppKeys::from_event(event).is_ok()
236}