Skip to main content

coven_sync/
pairing_ask.rs

1//! The new device's side of a pairing's request: the pair it asks with, the
2//! request sealed with the code's secret, and the checks of the request's
3//! path (§13.2). Nothing here is written to disk or the keychain: the pair
4//! lives as long as the call that made it.
5
6use crate::request_at::{Placed, RequestAt};
7use crate::SyncError;
8use coven_crypto::{ConfirmationNumber, MemberKeys};
9use coven_format::{
10    codes::PairingCode,
11    handover::Handover,
12    invite_end::InviteEnd,
13    objects::{JoinRequest, Joiner},
14    sealed_single::SingleChunkObject,
15};
16use coven_foundation::id_source::{DeviceId, MemberId};
17use coven_storage::{ObjectPath, Storage, StorageFailure};
18use std::time::SystemTime;
19
20/// What a check of the request's path finds.
21#[derive(Debug, PartialEq, Eq)]
22pub enum PairingCheck {
23    /// A request is at the path, this device's or another, or this device's
24    /// has just been sent again.
25    Waiting,
26    /// The showing device's approval put its handover in the request's place.
27    Handover(Handover),
28    /// The marker or the showing device's gone marker is there, or nothing is
29    /// and the pairing has expired: the pairing has ended.
30    Ended,
31}
32
33/// A request for a pairing and the pair it asks with.
34pub struct PairingAsk {
35    keys: MemberKeys,
36    member: MemberId,
37    path: ObjectPath,
38    request: Vec<u8>,
39    showing: DeviceId,
40    expires_at: u64,
41    confirmation: ConfirmationNumber,
42}
43
44impl PairingAsk {
45    /// A request for the pairing `code` shows, from the installation
46    /// `device`, with a pair made here for the handover to be sealed to.
47    pub fn new(code: &PairingCode, device: DeviceId, device_name: &str) -> Result<Self, SyncError> {
48        let keys = MemberKeys::generate()?;
49        let path = code.request_path();
50        let public = keys.public_keys();
51        let request = crate::sealed_join_request(
52            &code.secret,
53            &path,
54            &JoinRequest {
55                invite: code.pairing,
56                member: code.member,
57                keys: public,
58                device,
59                device_name: device_name.into(),
60                joiner: Joiner::OwnDevice,
61            },
62            &keys,
63        )?;
64        Ok(Self {
65            confirmation: ConfirmationNumber::of(code.pairing, &public),
66            keys,
67            member: code.member,
68            path,
69            request,
70            showing: code.showing,
71            expires_at: code.expires_at,
72        })
73    }
74
75    /// The number the person compares on the showing device before approving.
76    pub fn confirmation(&self) -> ConfirmationNumber {
77        self.confirmation
78    }
79
80    /// Whether the pairing still lets a first request be sent at `now`.
81    pub fn open_at(&self, now: SystemTime) -> bool {
82        now.duration_since(SystemTime::UNIX_EPOCH)
83            .map_or(true, |since| since.as_secs() < self.expires_at)
84    }
85
86    fn at(&self) -> RequestAt<'_> {
87        RequestAt { path: &self.path, request: &self.request, showing: self.showing }
88    }
89
90    /// Send the request. `false`, sending nothing, when the pairing has
91    /// ended already: the showing device is gone for good, or its marker holds
92    /// the path. A path taken by anything else fails with `InvitationChanged`.
93    pub async fn publish(&self, storage: &dyn Storage) -> Result<bool, SyncError> {
94        let at = self.at();
95        if at.showing_gone(storage).await? {
96            return Ok(false);
97        }
98        match at.place(storage).await? {
99            Placed::Ours => Ok(true),
100            Placed::Other(found) if InviteEnd::decode(&found).is_ok() => Ok(false),
101            Placed::Other(_) => Err(SyncError::InvitationChanged),
102        }
103    }
104
105    /// Look at the request's path at `now`. The showing device's gone marker
106    /// ends the pairing whatever the path holds. Otherwise the handover
107    /// wins, a request waits and the marker ends it; and nothing, because the
108    /// showing device is between its delete and its create or this device's
109    /// own create never arrived, is answered by sending the same request
110    /// again while the pairing is open, and ends the pairing once it is not.
111    pub async fn check(
112        &self,
113        storage: &dyn Storage,
114        now: SystemTime,
115    ) -> Result<PairingCheck, SyncError> {
116        let at = self.at();
117        if at.showing_gone(storage).await? {
118            // A request that reached storage after an admin's device listed
119            // the showing device's requests is deleted (`RequestAt::pending`).
120            at.pending(storage).await?;
121            return Ok(PairingCheck::Ended);
122        }
123        let found = match storage.read(&self.path).await {
124            Ok(found) => found,
125            Err(error) if error.failure() == StorageFailure::NotFound => {
126                if !self.open_at(now) {
127                    return Ok(PairingCheck::Ended);
128                }
129                match at.place(storage).await? {
130                    Placed::Ours => return Ok(PairingCheck::Waiting),
131                    Placed::Other(found) => found,
132                }
133            }
134            Err(error) => return Err(error.into()),
135        };
136        if let Ok(handover) = Handover::decode(&found) {
137            return Ok(PairingCheck::Handover(handover));
138        }
139        if InviteEnd::decode(&found).is_ok() {
140            return Ok(PairingCheck::Ended);
141        }
142        // This device's request, or another sealed for the same path: a
143        // request the showing device has not answered.
144        SingleChunkObject::decode(&found)?;
145        Ok(PairingCheck::Waiting)
146    }
147
148    /// Open the handover with the pair this device asked with. It must carry
149    /// the pairing's member; whether its pair is that member's current one is
150    /// for loading to check (§13.2).
151    pub fn open(&self, handover: &Handover) -> Result<(MemberId, MemberKeys), SyncError> {
152        let (member, keys) = handover.open(&self.path, &self.keys)?;
153        if member != self.member {
154            return Err(SyncError::InvitationChanged);
155        }
156        Ok((member, keys))
157    }
158}