Skip to main content

coven_sync/
sequence_pairings.rs

1//! The pairing on the device that shows its code: its journal row, the pass
2//! that looks for the request and puts the handover or the marker in its
3//! place, and the steps of a write that start, approve, decline and end it
4//! (§13.2).
5//!
6//! A pairing is an invite to the showing device's own member whose approval
7//! hands over the member's private pair. It claims no slot and records no
8//! provider access, so nothing here starts another operation: the row alone
9//! is the pairing, and the object at the request's one path is its storage.
10
11use super::sequence_invites::{
12    decode_request, kept_until, seconds, Expected, Opened, RequestChecks,
13};
14use super::{SequenceSync, Session};
15use crate::sequence_sync::OperationState;
16use crate::{AddDevice, AddDeviceEnd, AddDeviceId, AddDeviceRequest, AddDeviceStatus, SyncError};
17use coven_crypto::{InviteSecret, MemberIdentity, SecretText};
18use coven_database::{
19    operation_kind, DbError, Journal, NewOperation, OperationId, OperationRecord, SqlContext,
20};
21use coven_format::{codes::PairingCode, handover::Handover};
22use coven_foundation::id_source::{DeviceId, IdSource, InviteId, MemberId};
23use coven_storage::{CloudProvider, ObjectPath, RestoreStorage, S3Credentials, StorageFailure};
24use serde::{Deserialize, Serialize};
25use std::time::{Duration, SystemTime};
26
27/// How long a pairing lives after it is made, by the showing device's clock
28/// (§13.2).
29pub(crate) const LIFETIME: Duration = Duration::from_secs(30 * 60);
30
31/// Where a pairing is, as its journal row encodes it.
32#[derive(Debug, Serialize, Deserialize)]
33pub(crate) enum PairingState {
34    /// The code is shown. The request, once read and checked, waits for the
35    /// app: its exact plaintext.
36    Waiting { request: Option<Vec<u8>> },
37    /// This checked request is approved: `handover` is the object, sealed in
38    /// the approving write, that takes the request's place.
39    Approving { request: Vec<u8>, handover: Vec<u8> },
40    /// The handover is in the request's place, waiting for history to show
41    /// the new device registered.
42    HandedOver { request: Vec<u8> },
43    /// The pairing ended, and the app is shown how: the marker goes in the
44    /// place of the request or the handover.
45    Ending { how: AddDeviceEnd },
46    /// The app closed the screen: the marker goes in the place of the request
47    /// or the handover, and then the row is finished.
48    Forgetting,
49    /// The marker is in place; the app reads how the pairing ended until it
50    /// closes the screen.
51    Ended { how: AddDeviceEnd },
52}
53
54/// A pairing's journal row.
55#[derive(Debug, Serialize, Deserialize)]
56pub(crate) struct PairingWork {
57    id: InviteId,
58    /// The device that made the pairing, under which its request lives. A
59    /// reset carries the pairing to an installation with another id, which
60    /// ends the request where it is (§13.2, §19.3).
61    device: DeviceId,
62    /// The showing device's member, whose pair the handover carries.
63    member: MemberId,
64    secret: SecretText,
65    expires_at: SystemTime,
66    /// The code the app shows as a QR code, and the one it shares as text:
67    /// the same on every provider but S3, where only the first holds the key.
68    qr_code: SecretText,
69    shared_code: SecretText,
70    state: PairingState,
71}
72
73impl OperationState for PairingWork {}
74
75impl PairingWork {
76    pub(crate) fn read(record: &OperationRecord) -> Result<Self, SyncError> {
77        Ok(serde_json::from_slice(&record.data)?)
78    }
79
80    fn secret(&self) -> Result<InviteSecret, SyncError> {
81        Ok(InviteSecret::from_bytes(serde_json::from_str(self.secret.as_str())?))
82    }
83
84    fn path(&self, store: coven_foundation::id_source::StoreId) -> ObjectPath {
85        ObjectPath::join_request(store, self.device, self.id)
86    }
87
88    /// Whether the pairing ends at its expiry: it waits for its request or
89    /// the app, or has been approved.
90    fn expires(&self) -> bool {
91        matches!(
92            self.state,
93            PairingState::Waiting { .. }
94                | PairingState::Approving { .. }
95                | PairingState::HandedOver { .. }
96        )
97    }
98
99    pub(crate) fn expired(&self, now: SystemTime) -> bool {
100        self.expires() && now >= self.expires_at
101    }
102
103    /// End the pairing for `how`.
104    fn end(&mut self, how: AddDeviceEnd) {
105        self.state = PairingState::Ending { how };
106    }
107
108    /// The app closed the screen, or the installation was reset: the marker
109    /// goes in and the row is finished.
110    pub(crate) fn forget(&mut self) {
111        self.state = PairingState::Forgetting;
112    }
113
114    /// The pairing's expiry, while it can still end by it.
115    pub(crate) fn expiry(&self) -> Option<SystemTime> {
116        self.expires().then_some(self.expires_at)
117    }
118
119    /// End the pairing as its expiry does.
120    pub(crate) fn expire(&mut self) {
121        self.end(AddDeviceEnd::Expired);
122    }
123}
124
125/// Make a pairing, as a step of a write (§13.2). The write checks that this
126/// device is registered and its member active in the slots this device has
127/// applied, fixes a fresh secret and the codes, and journals the pairing,
128/// with or without storage. On S3 `key`, the key this device connects with,
129/// goes in the QR code and not in the shared one; an S3 pairing without it
130/// fails with `InvalidConfiguration`. The pairing expires `LIFETIME` after
131/// `now`.
132pub(crate) fn make_pairing(
133    sql: &SqlContext<'_, '_>,
134    device: DeviceId,
135    held: &MemberIdentity,
136    ids: &dyn IdSource,
137    now: SystemTime,
138    location: &coven_storage::StorageConfig,
139    key: Option<S3Credentials>,
140) -> Result<AddDevice, SyncError> {
141    let expires_at = now.checked_add(LIFETIME).ok_or(
142        StorageFailure::InvalidConfiguration
143            .with_source("the clock cannot represent the pairing's expiry"),
144    )?;
145    let secret = InviteSecret::generate()?;
146    let secret = SecretText::new(serde_json::to_string(secret.to_secret_bytes().as_bytes())?);
147    let id = InviteId(ids.new_id());
148    sql.journal_step(|journal| {
149        let applied = journal.store_state()?;
150        let member = crate::sequence_sync::registered(&applied, device, held)?;
151        let store = applied.store.as_ref().ok_or(SyncError::NoStorage)?;
152        let code = |storage: RestoreStorage| -> Result<SecretText, SyncError> {
153            let text = PairingCode {
154                store: store.id,
155                expires_at: seconds(expires_at)?,
156                pairing: id,
157                member,
158                secret: InviteSecret::from_bytes(serde_json::from_str(secret.as_str())?),
159                showing: device,
160                storage: storage.encode()?,
161            }
162            .to_text()?;
163            Ok(SecretText::new(text.to_string()))
164        };
165        let shared_code = code(RestoreStorage::location_only(location.clone()))?;
166        let qr_code = if location.provider() == CloudProvider::S3 {
167            let key = key.ok_or_else(|| {
168                StorageFailure::InvalidConfiguration
169                    .with_source("this device holds no S3 key to give")
170            })?;
171            code(RestoreStorage { location: location.clone(), s3_key: Some(key) })?
172        } else {
173            SecretText::new(shared_code.as_str().to_owned())
174        };
175        let work = PairingWork {
176            id,
177            device,
178            member,
179            secret: SecretText::new(secret.as_str().to_owned()),
180            expires_at,
181            qr_code: SecretText::new(qr_code.as_str().to_owned()),
182            shared_code: SecretText::new(shared_code.as_str().to_owned()),
183            state: PairingState::Waiting { request: None },
184        };
185        journal.start_operation(&NewOperation {
186            kind: operation_kind::PAIRING.into(),
187            data: serde_json::to_vec(&work)?,
188            started_by: "add_device".into(),
189            pauses_writes: false,
190        })?;
191        Ok(AddDevice {
192            id: id.into(),
193            qr_code: qr_code.as_str().to_owned(),
194            shared_code: shared_code.as_str().to_owned(),
195            expires_at,
196        })
197    })
198}
199
200/// Approve exactly this checked request, as a step of a write (§13.2), with
201/// or without storage: `request` is the one the app was shown. The step
202/// compares its record with the request the pairing holds and seals the
203/// member's current private pair, as `held` has it, to that request's
204/// sealing key only when they are the same; a different request is refused,
205/// never sealed to. The handover's bytes are fixed here, so a retry of the
206/// pass that puts it in the request's place creates the same object. A
207/// request the pairing no longer shows, and a pairing whose lifetime ended
208/// by `now`, fail the step with `InvitationChanged`.
209pub(crate) fn approve_request(
210    sql: &SqlContext<'_, '_>,
211    store: coven_foundation::id_source::StoreId,
212    now: SystemTime,
213    held: &MemberIdentity,
214    request: &AddDeviceRequest,
215) -> Result<OperationId, SyncError> {
216    sql.journal_step(|journal| {
217        let (record, mut work) = pairing_record(journal, request.pairing.into())?;
218        if work.expired(now) {
219            return Err(SyncError::InvitationChanged);
220        }
221        let PairingState::Waiting { request: Some(stored) } = &work.state else {
222            return Err(SyncError::InvitationChanged);
223        };
224        if *stored != request.record {
225            return Err(SyncError::InvitationChanged);
226        }
227        let stored = stored.clone();
228        let applied = journal.store_state()?;
229        let current = applied
230            .active_member(&work.member)
231            .ok_or(SyncError::Removed(coven_database::Removal::Member))?
232            .keys;
233        let selected =
234            held.activate(&current).ok_or(SyncError::MemberKeysReplaced { member: work.member })?;
235        let sealing = decode_request(&stored)?.keys.sealing;
236        let handover =
237            Handover::seal(work.member, selected.keys(), &sealing, &work.path(store))?.encode();
238        work.state = PairingState::Approving { request: stored, handover };
239        journal.advance_operation(&work.update(&record)?)?;
240        Ok(record.id)
241    })
242}
243
244/// Decline exactly this checked request, as a step of a write: the pairing
245/// ends as declined. A request the pairing no longer shows, an approved
246/// pairing, and one whose lifetime ended by `now`, fail the step with
247/// `InvitationChanged`.
248pub(crate) fn decline_request(
249    sql: &SqlContext<'_, '_>,
250    now: SystemTime,
251    request: &AddDeviceRequest,
252) -> Result<OperationId, SyncError> {
253    sql.journal_step(|journal| {
254        let (record, mut work) = pairing_record(journal, request.pairing.into())?;
255        if work.expired(now) {
256            return Err(SyncError::InvitationChanged);
257        }
258        match &work.state {
259            PairingState::Waiting { request: Some(stored) } if *stored == request.record => (),
260            _ => return Err(SyncError::InvitationChanged),
261        }
262        work.end(AddDeviceEnd::Declined);
263        journal.advance_operation(&work.update(&record)?)?;
264        Ok(record.id)
265    })
266}
267
268/// The screen showing the pairing's code closed, as a step of a write: the
269/// pairing ends at whatever stage it is, approved included, and is forgotten
270/// once the marker is in the request's or handover's place. A pairing that
271/// has ended is forgotten as it is; one already forgotten changes nothing.
272pub(crate) fn end_add_device(
273    sql: &SqlContext<'_, '_>,
274    pairing: AddDeviceId,
275) -> Result<Option<OperationId>, SyncError> {
276    sql.journal_step(|journal| {
277        let (record, mut work) = match pairing_record(journal, pairing.into()) {
278            Ok(found) => found,
279            Err(SyncError::InvitationChanged) => return Ok(None),
280            Err(error) => return Err(error),
281        };
282        match work.state {
283            PairingState::Forgetting => return Ok(None),
284            // The marker is in place already: nothing is left to do.
285            PairingState::Ended { .. } => journal.finish_operation(record.id)?,
286            _ => {
287                work.state = PairingState::Forgetting;
288                journal.advance_operation(&work.update(&record)?)?;
289            }
290        }
291        Ok(Some(record.id))
292    })
293}
294
295/// The pairing's journal row and its state, as the write sees them; a
296/// finished or unknown pairing fails with `InvitationChanged`.
297fn pairing_record(
298    journal: &Journal<'_>,
299    pairing: InviteId,
300) -> Result<(OperationRecord, PairingWork), SyncError> {
301    for record in journal.operations(operation_kind::PAIRING)? {
302        let work = PairingWork::read(&record)?;
303        if work.id == pairing {
304            return Ok((record, work));
305        }
306    }
307    Err(SyncError::InvitationChanged)
308}
309
310impl PairingWork {
311    /// Where the pairing is for the app, or `None` once the app has closed
312    /// the screen: the pairing is forgotten even while its marker is on its way.
313    fn status(&self) -> Result<Option<AddDeviceStatus>, SyncError> {
314        let present = |bytes: &[u8]| -> Result<AddDeviceRequest, SyncError> {
315            let request = decode_request(bytes)?;
316            Ok(AddDeviceRequest {
317                pairing: self.id.into(),
318                device_name: request.device_name,
319                confirmation: coven_crypto::ConfirmationNumber::of(self.id, &request.keys),
320                record: bytes.to_vec(),
321            })
322        };
323        Ok(Some(match &self.state {
324            PairingState::Waiting { request } => {
325                AddDeviceStatus::Waiting { request: request.as_deref().map(present).transpose()? }
326            }
327            PairingState::Approving { request, .. } | PairingState::HandedOver { request } => {
328                AddDeviceStatus::Approved { request: present(request)? }
329            }
330            PairingState::Ending { how } | PairingState::Ended { how } => {
331                AddDeviceStatus::Ended(how.clone())
332            }
333            PairingState::Forgetting => return Ok(None),
334        }))
335    }
336}
337
338/// The status of `pairing`, from `records`, the journal's pairing rows
339/// (`operation_kind::PAIRING`), which a one-shot read or a live query reads.
340/// `None` for a pairing this device never made or has forgotten (E10).
341#[expect(
342    clippy::map_err_ignore,
343    reason = "a stored request that does not decode is a damaged journal row, whichever field failed"
344)]
345pub fn pairing_status(
346    records: &[OperationRecord],
347    pairing: AddDeviceId,
348) -> Result<Option<AddDeviceStatus>, DbError> {
349    for record in records {
350        let work: PairingWork =
351            serde_json::from_slice(&record.data).map_err(DbError::StateEncoding)?;
352        if work.id == InviteId::from(pairing) {
353            return work.status().map_err(|_| DbError::DamagedDatabase);
354        }
355    }
356    Ok(None)
357}
358
359/// Opening the store ends every pairing a closed handle or a crash left: no
360/// screen shows one now. Each is forgotten once its marker is in place, and
361/// one that had ended already is forgotten at once, all in one transaction
362/// (§13.2).
363pub async fn pairings_opened(database: &coven_database::StoreDatabase) -> Result<(), DbError> {
364    database
365        .settle_operations(operation_kind::PAIRING, |records| {
366            let mut updates = Vec::new();
367            let mut finished = Vec::new();
368            for record in records {
369                let mut work: PairingWork =
370                    serde_json::from_slice(&record.data).map_err(DbError::StateEncoding)?;
371                match work.state {
372                    PairingState::Forgetting => (),
373                    PairingState::Ended { .. } => finished.push(record.id),
374                    _ => {
375                        work.state = PairingState::Forgetting;
376                        updates.push(record.next_step(
377                            serde_json::to_vec(&work).map_err(DbError::StateEncoding)?,
378                        )?);
379                    }
380                }
381            }
382            Ok((updates, finished, ()))
383        })
384        .await
385}
386
387impl SequenceSync {
388    /// Advance this device's pairings in a pass: look for each one's request,
389    /// put the handover or the marker in its place, and register the new
390    /// device as added. Every pass looks at every pairing; a pairing has no
391    /// doubling wait (§13.2).
392    pub(crate) async fn resume_pairings(&self, session: &Session) -> Result<(), SyncError> {
393        for record in self.database.operations().await? {
394            if record.kind != operation_kind::PAIRING {
395                continue;
396            }
397            self.run_pairing(session, record.id).await?;
398            self.state.check()?;
399        }
400        Ok(())
401    }
402
403    /// One pairing's attempt. Its failure is the pairing's pending record,
404    /// saved only while the row is at the step the attempt read: the app or
405    /// the expiry may have moved the pairing on, or forgotten it, since, and
406    /// the failure then belongs to a step it has left. A failure that read no
407    /// row fails the pass.
408    async fn run_pairing(&self, session: &Session, id: OperationId) -> Result<(), SyncError> {
409        let mut step = None;
410        let Err(error) = self.advance_pairing(session, id, &mut step).await else {
411            return Ok(());
412        };
413        let Some(step) = step else { return Err(error) };
414        match self.database.operation(id).await? {
415            Some(row) if row.last_step == step => self.record_pairing_error(id, step, &error).await,
416            _ => Ok(()),
417        }
418    }
419
420    /// Advance the pairing as far as it goes now. `step` follows the step of
421    /// the row this attempt last read, which a failure belongs to.
422    async fn advance_pairing(
423        &self,
424        session: &Session,
425        id: OperationId,
426        step: &mut Option<u32>,
427    ) -> Result<(), SyncError> {
428        loop {
429            let record = self
430                .database
431                .operation(id)
432                .await?
433                .ok_or(coven_database::DbError::OperationChanged(id))?;
434            *step = Some(record.last_step);
435            let mut work = PairingWork::read(&record)?;
436            let path = work.path(self.store());
437            if work.expired(self.clock.now()) {
438                work.expire();
439                self.database.advance_operation(work.update(&record)?).await?;
440                continue;
441            }
442            match &work.state {
443                PairingState::Waiting { request: None } => {
444                    let bytes = match self.storage.read(&path).await {
445                        Ok(bytes) => bytes,
446                        Err(error) if error.failure() == StorageFailure::NotFound => {
447                            return self.found_nothing(id, record.last_step).await;
448                        }
449                        Err(error) => return Err(error.into()),
450                    };
451                    let secret = work.secret()?;
452                    let checks = RequestChecks {
453                        path: &path,
454                        secret: &secret,
455                        id: work.id,
456                        member: work.member,
457                        expected: Expected::OwnDevice,
458                    };
459                    match checks.open(&session.history.state, &bytes)? {
460                        // A checked request waits for the app's decision:
461                        // someone who saw the code may have sent it first.
462                        Opened::Checked(request) => {
463                            work.state = PairingState::Waiting { request: Some(request) };
464                            self.database.advance_operation(work.update(&record)?).await?;
465                            return Ok(());
466                        }
467                        // No attempt can pass it, and no other request can
468                        // reach the one path while it is there: the pairing
469                        // ends, as a decline ends it.
470                        Opened::Refused(refusal) => {
471                            tracing::warn!(?id, %refusal, "a pairing's request failed its checks");
472                            work.end(AddDeviceEnd::Refused);
473                            self.database.advance_operation(work.update(&record)?).await?;
474                        }
475                    }
476                }
477                PairingState::Waiting { request: Some(_) } => {
478                    return self.found_nothing(id, record.last_step).await;
479                }
480                PairingState::Approving { request, handover } => {
481                    self.place_handover(&path, handover).await?;
482                    let request = request.clone();
483                    work.state = PairingState::HandedOver { request };
484                    self.database.advance_operation(work.update(&record)?).await?;
485                }
486                PairingState::HandedOver { request } => {
487                    // The handover stays until history shows the device the
488                    // request named registered under this member, as an
489                    // add-device entry by that member does.
490                    let request = decode_request(request)?;
491                    let registered = session
492                        .history
493                        .state
494                        .devices
495                        .get(&request.device)
496                        .is_some_and(|device| device.member == work.member);
497                    if !registered {
498                        return self.found_nothing(id, record.last_step).await;
499                    }
500                    work.end(AddDeviceEnd::Added {
501                        device: request.device,
502                        name: request.device_name,
503                    });
504                    self.database.advance_operation(work.update(&record)?).await?;
505                }
506                PairingState::Ending { .. } | PairingState::Forgetting => {
507                    // The marker goes once a new device can no longer send a
508                    // first request (`put_marker`).
509                    let kept_until = kept_until(seconds(work.expires_at)?)?;
510                    self.put_marker(&path, kept_until).await?;
511                    let removal = coven_database::ObjectRemoval {
512                        path: path.as_str().to_owned(),
513                        after: kept_until,
514                    };
515                    match work.state {
516                        PairingState::Ending { how } => {
517                            work.state = PairingState::Ended { how };
518                            self.database
519                                .advance_operation_with_removal(work.update(&record)?, removal)
520                                .await?;
521                        }
522                        _ => {
523                            self.database
524                                .finish_operation_with_removal(id, Vec::new(), removal, None)
525                                .await?;
526                        }
527                    }
528                    return Ok(());
529                }
530                PairingState::Ended { .. } => return Ok(()),
531            }
532        }
533    }
534
535    /// The attempt found nothing to change: whatever it failed at before has
536    /// succeeded, so the pairing's pending record at this step ends.
537    async fn found_nothing(&self, id: OperationId, step: u32) -> Result<(), SyncError> {
538        self.database.clear_operation_pending_at(id, step).await?;
539        Ok(())
540    }
541
542    /// Put the approved `handover` in the place of the request: delete the
543    /// request, then create the handover, which is created once; a request
544    /// that arrives in between is deleted again. The handover found already,
545    /// from an earlier attempt, is done.
546    async fn place_handover(&self, path: &ObjectPath, handover: &[u8]) -> Result<(), SyncError> {
547        loop {
548            match self.storage.read(path).await {
549                Ok(found) if found == handover => return Ok(()),
550                Ok(_) => self.storage.delete_if_present(path).await?,
551                Err(error) if error.failure() == StorageFailure::NotFound => {
552                    match self.storage.create(path, handover).await {
553                        Ok(_) => return Ok(()),
554                        Err(error) if error.failure() == StorageFailure::AlreadyExists => (),
555                        Err(error) => return Err(error.into()),
556                    }
557                }
558                Err(error) => return Err(error.into()),
559            }
560        }
561    }
562}
563
564#[cfg(test)]
565#[path = "sequence_pairings_tests.rs"]
566mod tests;