Skip to main content

coven/
bootstrap_pairing.rs

1//! A new device asking one of the person's devices to pair it: the request it
2//! sends with a pair kept only in memory, the wait for the handover, and the
3//! restore it continues as once the handover opens (§13.2).
4
5use super::*;
6use coven_format::codes::PairingCode;
7use coven_storage::Storage;
8use coven_sync::{ApprovalWaits, JoinPoll, PairingAsk, PairingCheck, RetryWaits, SequenceState};
9
10/// Ask one of the person's devices, which shows `code`, to pair this device,
11/// and restore from what it hands over, returning the open store (`None` when
12/// the pairing ended before its handover opened). A restore's rules hold from
13/// its record on; before it, cancelling through `control`, dropping or
14/// failing the call removes the installation, whether or not the request was
15/// sent, since approval binds nothing in history (§13.2).
16///
17/// S3 requires a key: the one the QR code carries, or else `s3_credentials`,
18/// never both. A store whose unfinished installation holds a join's saved
19/// code or a restore's record is refused with `StoreLockError::BootstrapPending`
20/// before anything changes (§13.4).
21pub async fn join_with_pairing(
22    builder: CovenBuilder,
23    code: &str,
24    s3_credentials: Option<S3Credentials>,
25    device_name: &str,
26    on_status: impl Fn(BootstrapStatus),
27    control: &JoinControl,
28) -> Result<Option<CovenHandle>, BootstrapError> {
29    let cancel = control.cancel.subscribe();
30    check_cancel(&cancel)?;
31    let code = coven_sync::read_pairing_code(code)?;
32    let storage = RestoreStorage::decode(code.storage.as_bytes()).map_err(SyncError::from)?;
33    let (data, sign_in) = restore_connection(&builder, storage, s3_credentials)?;
34    let sign_in = sign_in.map_or(SignInCustody::None, SignInCustody::Session);
35    Box::pin(bootstrap_device(
36        builder,
37        Start::Pair(Pair {
38            code,
39            data,
40            sign_in,
41            name: device_name.into(),
42            held: control.often.subscribe(),
43            parks: control.parks.clone(),
44        }),
45        on_status,
46        &cancel,
47    ))
48    .await
49}
50
51/// How a call begins: with the request it carries out, or a pairing, which
52/// first asks for the member's keys and then continues as a restore.
53pub(super) enum Start {
54    Request(BootstrapRequest),
55    Pair(Pair),
56}
57
58impl From<BootstrapRequest> for Start {
59    fn from(request: BootstrapRequest) -> Self {
60        Self::Request(request)
61    }
62}
63
64impl Start {
65    pub(super) fn store(&self) -> StoreId {
66        match self {
67            Self::Request(BootstrapRequest::Restore { code, .. }) => code.store,
68            Self::Request(BootstrapRequest::Join { code, .. }) => code.store,
69            Self::Pair(pair) => pair.store(),
70        }
71    }
72}
73
74/// What a pairing sends its request with and waits for the handover on.
75pub(super) struct Pair {
76    code: PairingCode,
77    data: ConnectionCredentials,
78    sign_in: SignInCustody,
79    name: String,
80    /// The intervals the app asks the pairing to check at.
81    held: HeldIntervals,
82    parks: Parks,
83}
84
85impl Pair {
86    pub(super) fn store(&self) -> StoreId {
87        self.code.store
88    }
89}
90
91/// Send the pairing's request, wait for the handover and open it: the restore
92/// it hands over to, which loads, checks the pair, records itself and
93/// registers the device. `None` when the pairing ended first: the showing
94/// device declined, closed or lost it, it expired, or it was refused. The
95/// installation's database opens for the persisted waits between checks and
96/// closes again before the restore opens it.
97pub(super) async fn handed_over(
98    builder: &mut CovenBuilder,
99    pending: &BootstrapStore,
100    pair: Pair,
101    status: &impl Fn(BootstrapStatus),
102    cancel: &watch::Receiver<bool>,
103) -> Result<Option<BootstrapRequest>, BootstrapError> {
104    let Pair { code, data, sign_in, name, held, parks } = pair;
105    check_cancel(cancel)?;
106    let directory = pending.directory();
107    let device = directory.settings().map_err(CovenError::from)?.device_id;
108    let ask = PairingAsk::new(&code, device, &name)?;
109    let clock = builder.clock.clone();
110    // No first request goes out once the pairing has expired.
111    if !ask.open_at(clock.now()) {
112        return Ok(None);
113    }
114    let provider = data.location.provider();
115    let database = open_installation(builder.database(directory)?, status).await?;
116    let asking = async {
117        status(BootstrapStatus::Connecting);
118        let waits = Arc::new(
119            RetryWaits::open(database.clone(), clock.clone()).await.map_err(CovenError::from)?,
120        );
121        let state = Arc::new(SequenceState::new());
122        let mut connecting = data.clone();
123        let storage: Arc<dyn Storage> =
124            connect_storage(builder, &mut connecting, &sign_in, device, &state, &waits).await?;
125        if !ask.publish(storage.as_ref()).await? {
126            return Ok(None);
127        }
128        status(BootstrapStatus::WaitingForApproval { confirmation: ask.confirmation() });
129        let approval = ApprovalWaits::new(database.clone(), waits, clock.clone());
130        let _running = parks.running();
131        let mut poll = JoinPoll::new(approval.clone(), held, parks.clone());
132        loop {
133            poll.due().await?;
134            match ask.check(storage.as_ref(), clock.now()).await? {
135                PairingCheck::Waiting => approval.waiting().await?,
136                PairingCheck::Ended => {
137                    approval.settled().await?;
138                    return Ok(None);
139                }
140                PairingCheck::Handover(handover) => {
141                    approval.settled().await?;
142                    return Ok(Some(ask.open(&handover)?));
143                }
144            }
145        }
146    };
147    let mut cancellation = cancel.clone();
148    let opened = tokio::select! {
149        biased;
150        _ = cancelled(&mut cancellation) => Err(BootstrapError::Cancelled),
151        result = asking => result,
152    };
153    let opened = combine(sign_in.refused(provider, opened), close_database(&database).await)?;
154    let Some((member, member_keys)) = opened else {
155        return Ok(None);
156    };
157    let s3_key = match &data.credentials {
158        StorageCredentials::S3(key) => Some(key.clone()),
159        _ => None,
160    };
161    let storage = RestoreStorage { location: data.location.clone(), s3_key }
162        .encode()
163        .map_err(SyncError::from)?;
164    Ok(Some(BootstrapRequest::Restore {
165        code: RestoreCode { store: code.store, member, member_keys, storage },
166        data,
167        sign_in,
168        name,
169    }))
170}