Skip to main content

coven_sync/
joining_identity.rs

1//! Fixed joining keys and request bytes, sealed locally using the scanned invite.
2
3use crate::request_at::{Placed, RequestAt};
4use crate::{Joiner, SyncError};
5use coven_crypto::{
6    CircleKey, ConfirmationNumber, EncryptionKey, InviteSecret, MemberIdentity, MemberKeys,
7    ObjectHasher,
8};
9use coven_format::invite_end::InviteEnd;
10use coven_format::{
11    admin::NewCircle,
12    codes::InviteCode,
13    objects::{JoinRequest, JoiningCircle},
14    sealed_key::{CopyBox, KeyCopyPrefix},
15    sealed_single::{SingleChunkObject, SingleChunkPrefix},
16    sealed_slot::SlotObjectPrefix,
17    Object,
18};
19use coven_foundation::files::StoreDirAccess;
20use coven_foundation::files::{AtomicFile, StoreDir, StoreFile};
21use coven_foundation::id_source::{CircleId, DeviceId, IdSource, KeyId};
22use coven_storage::{ObjectPath, Storage, StorageFailure};
23use zeroize::Zeroizing;
24
25/// The request as it is stored at `path`: sealed with the invite secret's
26/// request key and signed by the pair it names (§13.2).
27pub fn sealed_join_request(
28    secret: &InviteSecret,
29    path: &ObjectPath,
30    request: &JoinRequest,
31    signer: &MemberKeys,
32) -> Result<Vec<u8>, SyncError> {
33    let prefix = SingleChunkPrefix::JoinRequest;
34    let plain = Object::JoinRequest(request.clone()).encode()?;
35    let chunk = secret.join_request_key().seal_object_chunk(
36        path.as_str(),
37        &prefix.encode()?,
38        0,
39        0,
40        &plain,
41    )?;
42    let mut hash = ObjectHasher::new();
43    hash.update(&prefix.encode_chunk(&chunk)?);
44    Ok(SingleChunkObject::JoinRequest {
45        chunk: &chunk,
46        signature: signer.sign_object(path.as_str(), &hash.finish()),
47    }
48    .encode()?)
49}
50
51/// The request stored at `path` as `sealed_join_request` sealed it, opened
52/// with the invite secret's request key and checked as signed by the pair
53/// it names, before the caller compares what it says; with its plaintext.
54/// `None` when the chunk holds another kind of object (§13.2).
55pub(crate) fn opened_join_request(
56    secret: &InviteSecret,
57    path: &ObjectPath,
58    bytes: &[u8],
59) -> Result<Option<(JoinRequest, Vec<u8>)>, SyncError> {
60    let envelope = SingleChunkObject::decode(bytes)?;
61    let SingleChunkObject::JoinRequest { chunk, signature } = &envelope;
62    let plain = secret.join_request_key().open_object_chunk(
63        path.as_str(),
64        &envelope.prefix().encode()?,
65        0,
66        0,
67        chunk,
68    )?;
69    let Object::JoinRequest(request) = Object::decode(&plain)? else {
70        return Ok(None);
71    };
72    let mut hash = ObjectHasher::new();
73    hash.update(&envelope.signed_bytes()?);
74    request.keys.signing.verify_object(path.as_str(), &hash.finish(), signature)?;
75    Ok(Some((request, plain)))
76}
77
78/// What the app says of the circle its joining person's request makes: the
79/// admission will make it, with the person as its only member (§13.2).
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct CircleTerms {
82    /// The circle's name, which the person's profile will find it by.
83    pub name: String,
84    /// The version of the app's newest breaking migration, zero if none:
85    /// the circle's base (§15.5).
86    pub breaking_version: u32,
87}
88
89/// An unpublished member identity and its immutable request. The member id
90/// is the one the invite fixes; the keys are this device's fresh pair. The
91/// only durable local copy is encrypted with the invite secret, bound to the
92/// complete code. No member keys or provider credentials enter final custody
93/// while waiting. One join holds it, from preparing or resuming the request
94/// until the join ends.
95pub struct JoiningIdentity {
96    /// The store's bootstrap file, which keeps the sealed request and how far
97    /// the join has come.
98    file: AtomicFile,
99    identity: MemberIdentity,
100    request: Vec<u8>,
101    path: ObjectPath,
102    state: JoinStage,
103    /// What seals the saved request for the code it was made for.
104    sealing: Sealing,
105    /// The name the device gave itself in its request.
106    device_name: String,
107    /// Who the request is for, and the new person's name it carries.
108    joiner: Joiner,
109    /// The circle the request makes, whose key's only copy is its own box.
110    circle: JoiningCircle,
111    inviting_writer: DeviceId,
112    read_through: u64,
113    /// When the invite ends, in seconds since the Unix epoch: no first
114    /// request is sent after it.
115    expires_at: u64,
116    /// The number the admin compares before approving.
117    confirmation: ConfirmationNumber,
118}
119
120/// How far the join has come, as its saved request records it.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122enum JoinStage {
123    /// Not sent, and the invite's share not accepted: a cancel has nothing
124    /// to take back.
125    Unsent,
126    /// Not sent, and the provider's acceptance of the invite's share may be
127    /// in the joining account: a retry sends it, and a cancel takes the
128    /// acceptance back first (§13.2).
129    Accepted,
130    /// It may have been sent: on restart an absent request is final.
131    Sent,
132    /// Its copies opened this member's keys, in the admission that carries
133    /// them: the approving device's admission is in history (§13.2).
134    Opened,
135    /// The join decided to end without a store, and is deleting what it
136    /// kept: whatever call finds it finishes the deletion, without
137    /// connecting (§13.4).
138    Ended,
139}
140
141impl JoinStage {
142    fn byte(self) -> u8 {
143        match self {
144            Self::Unsent => 0,
145            Self::Accepted => 1,
146            Self::Sent => 2,
147            Self::Opened => 3,
148            Self::Ended => 4,
149        }
150    }
151
152    fn from_byte(byte: u8) -> Option<Self> {
153        match byte {
154            0 => Some(Self::Unsent),
155            1 => Some(Self::Accepted),
156            2 => Some(Self::Sent),
157            3 => Some(Self::Opened),
158            4 => Some(Self::Ended),
159            _ => None,
160        }
161    }
162}
163
164/// The invite secret's key and the complete code that seal the saved
165/// request, so it opens only with the code it was made for.
166struct Sealing {
167    key: EncryptionKey,
168    binding: Zeroizing<Vec<u8>>,
169    path: String,
170}
171
172impl Sealing {
173    fn new(code: &InviteCode) -> Result<Self, SyncError> {
174        Ok(Self {
175            key: code.secret.join_request_key(),
176            binding: code.to_bytes()?,
177            path: local_path(code),
178        })
179    }
180}
181
182impl JoiningIdentity {
183    /// Restore a fixed request or prepare it before any provider mutation.
184    /// A new request names `device`, the joining installation's id, for the
185    /// approval to register, `name`, the new person's name: given when
186    /// the invite admits a new person, absent when it admits a member's new
187    /// keys, as the code says, and the circle `circle` describes, with ids
188    /// from `ids`. A changed invite, device name, name or circle name cannot
189    /// silently reuse another request.
190    pub fn prepare(
191        directory: &StoreDir,
192        code: &InviteCode,
193        device: DeviceId,
194        device_name: &str,
195        name: Option<String>,
196        circle: &CircleTerms,
197        ids: &dyn IdSource,
198    ) -> Result<Self, SyncError> {
199        let joiner = match name {
200            Some(name) => Joiner::NewPerson { name },
201            None => Joiner::MemberKeys,
202        };
203        if joiner.admits() != code.admits {
204            return Err(crate::CodeError::WrongJoiner {
205                expected: code.admits,
206                actual: joiner.admits(),
207            }
208            .into());
209        }
210        match Self::saved(directory, code)? {
211            Some(saved)
212                if saved.device_name != device_name
213                    || saved.joiner != joiner
214                    || saved.circle.circle.name != circle.name =>
215            {
216                Err(SyncError::InvitationChanged)
217            }
218            Some(saved) => Ok(saved),
219            None => Self::create(directory, code, device, device_name, joiner, circle, ids),
220        }
221    }
222
223    /// `prepare` with a circle named "Circle" at base zero and random ids, for
224    /// a test whose join doesn't care about its circle.
225    #[cfg(any(test, feature = "test-utils"))]
226    pub fn prepare_for_test(
227        directory: &StoreDir,
228        code: &InviteCode,
229        device: DeviceId,
230        device_name: &str,
231        name: Option<String>,
232    ) -> Result<Self, SyncError> {
233        let circle = CircleTerms { name: "Circle".into(), breaking_version: 0 };
234        Self::prepare(
235            directory,
236            code,
237            device,
238            device_name,
239            name,
240            &circle,
241            &coven_foundation::id_source::UuidIds,
242        )
243    }
244
245    /// Continue a join from its saved request, with the device name and
246    /// person that request carries (§13.2). A join's code is saved only after its
247    /// request, so a missing request is damaged local state.
248    pub fn resume(directory: &StoreDir, code: &InviteCode) -> Result<Self, SyncError> {
249        Self::saved(directory, code)?.ok_or_else(|| coven_database::DbError::DamagedDatabase.into())
250    }
251
252    /// The request this directory keeps for `code`, opened with the code's
253    /// secret and checked against it.
254    #[expect(
255        clippy::map_err_ignore,
256        reason = "a request for the member's own device is no invite's, so the invitation changed"
257    )]
258    fn saved(directory: &StoreDir, code: &InviteCode) -> Result<Option<Self>, SyncError> {
259        crate::CodeError::require_store(directory.id(), code.store)?;
260        let file = directory.owned_file(StoreFile::Bootstrap);
261        let sealing = Sealing::new(code)?;
262        let path = code.request_path();
263        let Some(sealed) = file.read_optional()? else {
264            return Ok(None);
265        };
266        let bytes = Zeroizing::new(sealing.key.open_object_chunk(
267            &sealing.path,
268            &sealing.binding,
269            0,
270            0,
271            &sealed,
272        )?);
273        let state = bytes
274            .first()
275            .copied()
276            .and_then(JoinStage::from_byte)
277            .ok_or(coven_database::DbError::DamagedDatabase)?;
278        let key_length = bytes.get(1..5).ok_or(coven_database::DbError::DamagedDatabase)?;
279        let key_length = u32::from_be_bytes(key_length.try_into().expect("four bytes")) as usize;
280        let end = 5usize.checked_add(key_length).ok_or(coven_database::DbError::DamagedDatabase)?;
281        let identity = MemberIdentity::new(
282            code.member,
283            MemberKeys::from_secret_bytes(
284                bytes.get(5..end).ok_or(coven_database::DbError::DamagedDatabase)?,
285            )?,
286        );
287        let keys = identity.keys().public_keys();
288        let request = bytes.get(end..).ok_or(coven_database::DbError::DamagedDatabase)?.to_vec();
289        let (opened, _) = opened_join_request(&code.secret, &path, &request)?
290            .ok_or(coven_database::DbError::DamagedDatabase)?;
291        if opened.invite != code.invite || opened.member != code.member || opened.keys != keys {
292            return Err(SyncError::InvitationChanged);
293        }
294        // A request for the member's own device is no invite's, so the
295        // invitation changed; an invite's always names its circle.
296        let circle = opened.joiner.circle().cloned().ok_or(SyncError::InvitationChanged)?;
297        Ok(Some(Self {
298            file,
299            confirmation: ConfirmationNumber::of(code.invite, &keys),
300            identity,
301            request,
302            path,
303            state,
304            sealing,
305            device_name: opened.device_name,
306            joiner: opened.joiner.try_into().map_err(|_| SyncError::InvitationChanged)?,
307            circle,
308            inviting_writer: code.inviting_writer,
309            read_through: code.read_through,
310            expires_at: code.expires_at,
311        }))
312    }
313
314    fn create(
315        directory: &StoreDir,
316        code: &InviteCode,
317        device: DeviceId,
318        device_name: &str,
319        joiner: Joiner,
320        terms: &CircleTerms,
321        ids: &dyn IdSource,
322    ) -> Result<Self, SyncError> {
323        let path = code.request_path();
324        // The request repeats the id the invite fixed and names this
325        // device's fresh pair, which signs it, and this installation (D8).
326        let identity = MemberIdentity::generate(code.member)?;
327        let circle = joining_circle(
328            code.store,
329            code.member,
330            &identity.keys().public_keys().sealing,
331            terms,
332            ids,
333        )?;
334        let request = sealed_join_request(
335            &code.secret,
336            &path,
337            &JoinRequest {
338                invite: code.invite,
339                member: code.member,
340                keys: identity.keys().public_keys(),
341                device,
342                device_name: device_name.into(),
343                joiner: joiner.clone().requesting(circle.clone()),
344            },
345            identity.keys(),
346        )?;
347        let identity = Self {
348            file: directory.owned_file(StoreFile::Bootstrap),
349            confirmation: ConfirmationNumber::of(code.invite, &identity.keys().public_keys()),
350            identity,
351            request,
352            path,
353            state: JoinStage::Unsent,
354            sealing: Sealing::new(code)?,
355            device_name: device_name.into(),
356            joiner,
357            circle,
358            inviting_writer: code.inviting_writer,
359            read_through: code.read_through,
360            expires_at: code.expires_at,
361        };
362        identity.save()?;
363        Ok(identity)
364    }
365
366    /// The invite's member id with this device's pair, for composing the
367    /// unpublished member custody.
368    pub fn identity(&self) -> MemberIdentity {
369        self.identity.clone()
370    }
371
372    /// The inviting device: only its admission admits this request (§13.2).
373    pub fn approver(&self) -> DeviceId {
374        self.inviting_writer
375    }
376
377    /// The inviting device's applied slot when it made the invite: copies for
378    /// this request can only follow it (§13.2).
379    pub fn read_through(&self) -> u64 {
380        self.read_through
381    }
382
383    /// The name the device gave itself in its request, which its admission
384    /// registers it with.
385    pub fn device_name(&self) -> &str {
386        &self.device_name
387    }
388
389    /// The name of the circle the request makes.
390    pub fn circle_name(&self) -> &str {
391        &self.circle.circle.name
392    }
393
394    /// The circle the request makes, with the key's copy it carries.
395    #[cfg(any(test, feature = "test-utils"))]
396    pub fn circle(&self) -> &JoiningCircle {
397        &self.circle
398    }
399
400    /// Who the request is for. A new person's name is kept here until the
401    /// join publishes the store (§13.2).
402    pub fn joiner(&self) -> &Joiner {
403        &self.joiner
404    }
405
406    /// The number the admin compares before approving; the admin's device
407    /// computes it from the same keys (format.md D11).
408    pub fn confirmation(&self) -> ConfirmationNumber {
409        self.confirmation
410    }
411
412    /// The request's path, named by its invite.
413    pub fn path(&self) -> &ObjectPath {
414        &self.path
415    }
416
417    /// Whether publication may already have happened before an interruption.
418    pub fn attempted(&self) -> bool {
419        matches!(self.state, JoinStage::Sent | JoinStage::Opened)
420    }
421
422    /// Whether the invite's share may have been accepted for the joining
423    /// account while the request is unsent: a cancel takes it back before
424    /// it removes the join (§13.2).
425    pub fn accepted(&self) -> bool {
426        self.state == JoinStage::Accepted
427    }
428
429    /// Whether the join already decided to end, and only its deletion is
430    /// left (§13.4).
431    pub fn ended(&self) -> bool {
432        self.state == JoinStage::Ended
433    }
434
435    /// Whether this member's keys have opened, in this call or an earlier
436    /// one: the admission carrying them is in history, and the join never
437    /// reports waiting for approval again (§13.2, E10).
438    pub fn opened(&self) -> bool {
439        self.state == JoinStage::Opened
440    }
441
442    /// Record, before accepting the invite's share, that the acceptance may
443    /// be in the joining account, so a cancel before sending, in this call
444    /// or after a restart, takes it back (§13.2). A join already accepted,
445    /// or one that may have sent, is past this.
446    pub fn record_acceptance(&mut self) -> Result<(), SyncError> {
447        match self.state {
448            JoinStage::Unsent => self.record(JoinStage::Accepted),
449            JoinStage::Accepted | JoinStage::Sent | JoinStage::Opened | JoinStage::Ended => Ok(()),
450        }
451    }
452
453    /// Record possible publication before issuing it. On restart a request
454    /// that is absent with nothing in its place is sent again; an ended
455    /// invite's marker in its place ends the join (`resend`).
456    pub fn record_attempt(&mut self) -> Result<(), SyncError> {
457        self.record(JoinStage::Sent)
458    }
459
460    /// The provider refused the request, so it was never published: a
461    /// retry sends it again, and a cancel takes back the acceptance that
462    /// came before it (§13.2).
463    pub fn record_refusal(&mut self) -> Result<(), SyncError> {
464        self.record(JoinStage::Accepted)
465    }
466
467    /// This member's copies opened its keys, in its admission. Recorded
468    /// before the join reports loading, so a resumed join knows it was
469    /// approved before its first check (§13.2, E10).
470    pub(crate) fn record_opened(&mut self) -> Result<(), SyncError> {
471        self.record(JoinStage::Opened)
472    }
473
474    fn record(&mut self, state: JoinStage) -> Result<(), SyncError> {
475        self.state = state;
476        self.save()
477    }
478
479    fn save(&self) -> Result<(), SyncError> {
480        let keys = self.identity.keys().to_secret_bytes();
481        let mut plain =
482            Zeroizing::new(Vec::with_capacity(5 + keys.as_bytes().len() + self.request.len()));
483        plain.push(self.state.byte());
484        plain.extend_from_slice(&(keys.as_bytes().len() as u32).to_be_bytes());
485        plain.extend_from_slice(keys.as_bytes());
486        plain.extend_from_slice(&self.request);
487        let sealed = self.sealing.key.seal_object_chunk(
488            &self.sealing.path,
489            &self.sealing.binding,
490            0,
491            0,
492            &plain,
493        )?;
494        self.file.replace(&sealed)?;
495        Ok(())
496    }
497
498    /// The request and where it goes, for the storage work it shares with a
499    /// pairing's.
500    fn at(&self) -> RequestAt<'_> {
501        RequestAt { path: &self.path, request: &self.request, showing: self.inviting_writer }
502    }
503
504    /// Publish the recorded immutable request. An occupied path must hold
505    /// exactly these bytes (§19.3). `false`, sending nothing, once the
506    /// inviting device is gone for good: an admin's device has ended its
507    /// requests, and none would ever be answered (§13.2).
508    pub async fn publish(&self, storage: &dyn Storage) -> Result<bool, SyncError> {
509        let at = self.at();
510        if at.showing_gone(storage).await? {
511            return Ok(false);
512        }
513        match at.place(storage).await? {
514            Placed::Ours => Ok(true),
515            // The invite ended before the request was sent, and its marker
516            // holds the path (§13.2).
517            Placed::Other(found) if InviteEnd::decode(&found).is_ok() => Ok(false),
518            Placed::Other(_) => Err(SyncError::InvitationChanged),
519        }
520    }
521
522    /// Send the request again when nothing is in its place: the call that
523    /// recorded the send stopped before the create reached storage. Any end
524    /// of the invite leaves its marker at the path, which the create finds
525    /// taken, so a declined or approved invite is never revived; a request
526    /// that is there already is left alone. What the join concludes is for
527    /// the check that follows, not for this send (§13.2).
528    pub(crate) async fn resend(&self, storage: &dyn Storage) -> Result<(), SyncError> {
529        match storage.read(&self.path).await {
530            Ok(_) => Ok(()),
531            Err(error) if error.failure() == StorageFailure::NotFound => {
532                self.publish(storage).await.map(drop)
533            }
534            Err(error) => Err(error.into()),
535        }
536    }
537
538    /// Whether this request is still in storage: an ended invite's marker
539    /// in its place, or nothing, means it is gone. A request beside its
540    /// inviting device's gone marker is deleted, and is gone too
541    /// (`RequestAt::pending`).
542    pub(crate) async fn pending(&self, storage: &dyn Storage) -> Result<bool, SyncError> {
543        self.at().pending(storage).await
544    }
545
546    /// Whether the invite still lets a first request be sent at `now`.
547    pub(crate) fn open_at(&self, now: std::time::SystemTime) -> bool {
548        now.duration_since(std::time::UNIX_EPOCH)
549            .map_or(true, |since| since.as_secs() < self.expires_at)
550    }
551}
552
553/// The circle `member`'s join request makes in `store`: its id, key and the
554/// key's only copy, sealed to the member's own new `sealing` key before the
555/// key is dropped (§13.2, D11). The saved request holds the box and nothing
556/// else holds the key.
557pub(crate) fn joining_circle(
558    store: coven_foundation::id_source::StoreId,
559    member: coven_foundation::id_source::MemberId,
560    sealing: &coven_crypto::SealingKey,
561    terms: &CircleTerms,
562    ids: &dyn IdSource,
563) -> Result<JoiningCircle, SyncError> {
564    let circle = CircleId(ids.new_id());
565    let key_id = KeyId(ids.new_id());
566    let key = CircleKey::generate(circle, key_id)?;
567    let routing = KeyCopyPrefix {
568        audience: coven_merge::Audience::Circle(circle),
569        key: key_id,
570        member,
571        sealing: *sealing,
572    };
573    let binding = SlotObjectPrefix::own_binding(store, &routing)?;
574    let sealed = coven_crypto::seal_own_circle_key(&key, &routing.sealing, &binding)?;
575    Ok(JoiningCircle {
576        circle: NewCircle {
577            circle,
578            name: terms.name.clone(),
579            breaking_version: terms.breaking_version,
580            key: key_id,
581            key_hash: key.hash(),
582        },
583        copy: CopyBox { routing, sealed },
584    })
585}
586
587/// The circle a join request of `member` with the sealing key `sealing` would
588/// make in `store`, named "Circle" at base zero, for a test that seals a
589/// request itself.
590#[cfg(any(test, feature = "test-utils"))]
591pub fn test_joining_circle(
592    store: coven_foundation::id_source::StoreId,
593    member: coven_foundation::id_source::MemberId,
594    sealing: &coven_crypto::SealingKey,
595    ids: &dyn IdSource,
596) -> Result<JoiningCircle, SyncError> {
597    joining_circle(
598        store,
599        member,
600        sealing,
601        &CircleTerms { name: "Circle".into(), breaking_version: 0 },
602        ids,
603    )
604}
605
606/// The admission of `member` with `keys` that a join request would make, for
607/// a test that admits a member without a join: the circle it makes, named
608/// `name`, and the member's own copy of its key.
609#[cfg(any(test, feature = "test-utils"))]
610#[expect(clippy::too_many_arguments, reason = "an admission's every field")]
611pub fn admitting(
612    store: coven_foundation::id_source::StoreId,
613    member: coven_foundation::id_source::MemberId,
614    keys: coven_crypto::MemberPublicKeys,
615    role: coven_format::admin::MemberRole,
616    access: coven_format::MemberAccess,
617    device: DeviceId,
618    device_name: &str,
619    ids: &dyn IdSource,
620) -> Result<(coven_format::admin::StoreChange, CopyBox), SyncError> {
621    let terms = CircleTerms { name: format!("circle of {member}"), breaking_version: 0 };
622    let JoiningCircle { circle, copy } = joining_circle(store, member, &keys.sealing, &terms, ids)?;
623    Ok((
624        coven_format::admin::StoreChange::AdmitMember {
625            member,
626            keys,
627            role,
628            access,
629            device,
630            device_name: device_name.into(),
631            person: format!("person {member}"),
632            circle,
633        },
634        copy,
635    ))
636}
637
638/// Record that the join with `code` ends without a store, before anything it
639/// kept is deleted: a call that stops part way through the deletion finds the
640/// record and finishes it without connecting. Nothing saved is nothing to
641/// record.
642pub fn record_ending(directory: &StoreDir, code: &InviteCode) -> Result<(), SyncError> {
643    match JoiningIdentity::saved(directory, code)? {
644        Some(mut saved) => saved.record(JoinStage::Ended),
645        None => Ok(()),
646    }
647}
648
649/// Whether the request kept for `code` was recorded as ended
650/// (`record_ending`).
651pub fn ended_for(directory: &StoreDir, code: &InviteCode) -> Result<bool, SyncError> {
652    Ok(JoiningIdentity::saved(directory, code)?.is_some_and(|saved| saved.ended()))
653}
654
655fn local_path(code: &InviteCode) -> String {
656    format!("coven/local-join/{}/{}", code.store, code.invite)
657}