Skip to main content

coven_sync/
codes.rs

1//! Checked code metadata used by bootstrap (E10).
2
3use coven_format::codes::{InviteAdmits, InviteCode, PairingCode, RestoreCode};
4use coven_foundation::id_source::{MemberId, StoreId};
5use coven_storage::{
6    CloudProvider, InviteStorage, OAuthAccess, RestoreStorage, SharedWith, StorageConfig,
7};
8
9/// The three codes that can open a store on a new device.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum CodeKind {
12    /// This person's member id and current private pair, store id and
13    /// storage location, and on S3 perhaps their key.
14    Restore,
15    /// A one-time request carrying the chosen member id, initial key,
16    /// inviting writer and its published key-copy number; approval is required.
17    Invite,
18    /// A one-time request from the person's own new device, to a device of
19    /// theirs that shows the code; it holds no keys and approval is required.
20    Pairing,
21}
22
23/// Code metadata safe for presentation before opening the store.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub enum CodeInfo {
26    /// A restore code reveals no store name before loading.
27    Restore(CodeMetadata),
28    /// An invite carries the store's name captured when the admin made it
29    /// and whether it admits a new person or a member's new keys.
30    Invite(InviteInfo),
31    /// A pairing code reveals no name either, and holds no keys.
32    Pairing(PairingInfo),
33}
34
35impl CodeInfo {
36    /// The store id, member and provider facts carried by every kind of code.
37    pub fn metadata(&self) -> &CodeMetadata {
38        match self {
39            Self::Restore(metadata)
40            | Self::Invite(InviteInfo { metadata, .. })
41            | Self::Pairing(PairingInfo { metadata, .. }) => metadata,
42        }
43    }
44}
45
46/// What a pairing code tells before connecting (§13.2).
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct PairingInfo {
49    /// The person's own member id, and the sign-in the new device needs.
50    pub metadata: CodeMetadata,
51    /// When the pairing ends, by the showing device's clock, to the second:
52    /// the new device sends no first request after it.
53    pub expires_at: std::time::SystemTime,
54}
55
56/// What an invite code tells before connecting: as typed or scanned, and as a
57/// join under way saved it (§13.2).
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct InviteInfo {
60    /// The code's shared metadata, including the sign-in the join needs.
61    pub metadata: CodeMetadata,
62    /// The store name at invitation creation.
63    pub store_name: String,
64    /// The inviting admin's name, as their app gave it when it made the
65    /// invite, for the joining person's screens to say whom to tell the code
66    /// and whom they wait for (§13.2).
67    pub inviter: String,
68    /// Whether the invite admits a new person, whose join request carries the
69    /// name they type, or a member's new keys, whose carries none.
70    pub admits: InviteAdmits,
71    /// When the invite ends, by the inviting device's clock, to the second:
72    /// the joining device sends no first request after it (§13.2).
73    pub expires_at: std::time::SystemTime,
74    /// On Dropbox and OneDrive, the account the inviting device shared the
75    /// folder with: the app can name it before anything connects, and the
76    /// join refuses a sign-in to another account (§13.2). None on S3 and
77    /// CloudKit.
78    pub shared_with: Option<coven_storage::SharedWith>,
79}
80
81/// Store, member and provider facts shared by every code kind.
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct CodeMetadata {
84    /// The shared store's identity.
85    pub store_id: StoreId,
86    /// The stable member id every kind of code fixes: the restoring or
87    /// pairing person's own, or the one the invite's admin chose (§13).
88    pub member: MemberId,
89    /// The storage provider.
90    pub cloud_provider: CloudProvider,
91    /// The code's provider location and account label, without credentials or share tokens.
92    pub location: StorageConfig,
93    /// The sign-in required by this code; S3 and CloudKit do not use OAuth.
94    pub oauth_access: Option<OAuthAccess>,
95    /// Whether the code carries an S3 key, so the device asks for none: an S3
96    /// invite always does, and so does an S3 pairing's QR code. No restore
97    /// code a person sees does (§13.1).
98    pub carries_s3_key: bool,
99}
100
101/// A malformed code or one intended for the other operation.
102#[derive(Clone, Debug, thiserror::Error)]
103pub enum CodeError {
104    /// Encoding, checksum or provider payload validation failed.
105    #[error("invalid restore, invite or pairing code")]
106    Invalid,
107    /// A valid code names the other operation.
108    #[error("expected {expected:?} code, received {actual:?}")]
109    WrongKind {
110        /// The requested kind.
111        expected: CodeKind,
112        /// The actual kind.
113        actual: CodeKind,
114    },
115    /// A valid code names another store than the one it is used for: a
116    /// restore code for a store being restored in place, or an invite code
117    /// saved for another store's join.
118    #[error("code is for store {actual}, not {expected}")]
119    WrongStore {
120        /// The store the code is used for.
121        expected: StoreId,
122        /// The store the code names.
123        actual: StoreId,
124    },
125    /// A join's person is not the one its invite admits: a name for an
126    /// invite that admits a member's new keys, or none for a new person's.
127    #[error("invite admits {expected:?}, but the join is for {actual:?}")]
128    WrongJoiner {
129        /// Who the invite admits.
130        expected: InviteAdmits,
131        /// Who the join named.
132        actual: InviteAdmits,
133    },
134}
135
136impl CodeError {
137    /// A code naming `actual` can be used only for the `expected` store.
138    pub fn require_store(expected: StoreId, actual: StoreId) -> Result<(), Self> {
139        if actual == expected {
140            Ok(())
141        } else {
142            Err(Self::WrongStore { expected, actual })
143        }
144    }
145}
146
147/// Decode and validate the complete code before returning public metadata.
148pub fn decode_code_info(code: &str) -> Result<CodeInfo, CodeError> {
149    let (code, location, carries_s3_key, shared_with) = decode(code)?;
150    let metadata = |store_id, member| CodeMetadata {
151        store_id,
152        member,
153        cloud_provider: location.provider(),
154        oauth_access: location.oauth_access(),
155        location,
156        carries_s3_key,
157    };
158    Ok(match code {
159        DecodedCode::Restore(code) => CodeInfo::Restore(metadata(code.store, code.member)),
160        DecodedCode::Invite(code) => CodeInfo::Invite(InviteInfo {
161            metadata: metadata(code.store, code.member),
162            store_name: code.name,
163            inviter: code.inviter,
164            admits: code.admits,
165            expires_at: std::time::UNIX_EPOCH + std::time::Duration::from_secs(code.expires_at),
166            shared_with,
167        }),
168        DecodedCode::Pairing(code) => CodeInfo::Pairing(PairingInfo {
169            metadata: metadata(code.store, code.member),
170            expires_at: std::time::UNIX_EPOCH + std::time::Duration::from_secs(code.expires_at),
171        }),
172    })
173}
174
175/// A restore code's metadata, or `WrongKind` for an invite or pairing code
176/// and `Invalid` for one that doesn't decode.
177pub fn decode_restore_info(code: &str) -> Result<CodeMetadata, CodeError> {
178    match decode_code_info(code)? {
179        CodeInfo::Restore(metadata) => Ok(metadata),
180        CodeInfo::Invite(_) => wrong_kind(CodeKind::Restore, CodeKind::Invite),
181        CodeInfo::Pairing(_) => wrong_kind(CodeKind::Restore, CodeKind::Pairing),
182    }
183}
184
185/// What an invite code tells, read before any sign-in: the app signs in with
186/// its `metadata.oauth_access`, then calls `join_with_invite`. Refuses the
187/// code as that call would: `WrongKind` for a restore or pairing code,
188/// `Invalid` for one that doesn't decode.
189pub fn decode_invite_info(code: &str) -> Result<InviteInfo, CodeError> {
190    match decode_code_info(code)? {
191        CodeInfo::Invite(info) => Ok(info),
192        CodeInfo::Restore(_) => wrong_kind(CodeKind::Invite, CodeKind::Restore),
193        CodeInfo::Pairing(_) => wrong_kind(CodeKind::Invite, CodeKind::Pairing),
194    }
195}
196
197/// What a pairing code tells, read before any sign-in: the app signs in with
198/// its `metadata.oauth_access`, then calls `join_with_pairing`. Refuses the
199/// code as that call would: `WrongKind` for a restore or invite code,
200/// `Invalid` for one that doesn't decode.
201pub fn decode_pairing_info(code: &str) -> Result<PairingInfo, CodeError> {
202    match decode_code_info(code)? {
203        CodeInfo::Pairing(info) => Ok(info),
204        CodeInfo::Restore(_) => wrong_kind(CodeKind::Pairing, CodeKind::Restore),
205        CodeInfo::Invite(_) => wrong_kind(CodeKind::Pairing, CodeKind::Invite),
206    }
207}
208
209/// Decode a restore code for bootstrap, preserving a
210/// valid wrong-kind distinction. Its storage part has already been validated.
211pub fn read_restore_code(code: &str) -> Result<RestoreCode, CodeError> {
212    decode_restore(code).map(|(code, _)| code)
213}
214
215/// The sign-in a restore of `store` in place from `code` needs, `None` on S3
216/// and CloudKit, read before any sign-in: the app signs in with it, then
217/// calls `CovenBuilder::restore_device`. Refuses the code as that call
218/// would: `WrongKind` for an invite or pairing code, `WrongStore` for
219/// another store's restore code, `Invalid` for one that doesn't decode.
220pub fn restore_sign_in(store: StoreId, code: &str) -> Result<Option<OAuthAccess>, CodeError> {
221    let (code, location) = decode_restore(code)?;
222    CodeError::require_store(store, code.store)?;
223    Ok(location.oauth_access())
224}
225
226/// A restore code and the storage location it names, or `WrongKind` for
227/// another kind of code.
228fn decode_restore(code: &str) -> Result<(RestoreCode, StorageConfig), CodeError> {
229    match decode(code)? {
230        (DecodedCode::Restore(code), location, ..) => Ok((code, location)),
231        (DecodedCode::Invite(_), ..) => wrong_kind(CodeKind::Restore, CodeKind::Invite),
232        (DecodedCode::Pairing(_), ..) => wrong_kind(CodeKind::Restore, CodeKind::Pairing),
233    }
234}
235
236/// Decode an invitation for the joining side after validating provider admission.
237pub fn read_invite_code(code: &str) -> Result<InviteCode, CodeError> {
238    match decode(code)?.0 {
239        DecodedCode::Invite(code) => Ok(code),
240        DecodedCode::Restore(_) => wrong_kind(CodeKind::Invite, CodeKind::Restore),
241        DecodedCode::Pairing(_) => wrong_kind(CodeKind::Invite, CodeKind::Pairing),
242    }
243}
244
245/// Decode a pairing code for the new device after validating provider admission.
246pub fn read_pairing_code(code: &str) -> Result<PairingCode, CodeError> {
247    match decode(code)?.0 {
248        DecodedCode::Pairing(code) => Ok(code),
249        DecodedCode::Restore(_) => wrong_kind(CodeKind::Pairing, CodeKind::Restore),
250        DecodedCode::Invite(_) => wrong_kind(CodeKind::Pairing, CodeKind::Invite),
251    }
252}
253
254fn wrong_kind<T>(expected: CodeKind, actual: CodeKind) -> Result<T, CodeError> {
255    Err(CodeError::WrongKind { expected, actual })
256}
257
258enum DecodedCode {
259    Restore(RestoreCode),
260    Invite(InviteCode),
261    Pairing(PairingCode),
262}
263
264#[expect(
265    clippy::map_err_ignore,
266    reason = "a code that does not decode is Invalid, whichever field failed"
267)]
268fn decode(text: &str) -> Result<(DecodedCode, StorageConfig, bool, Option<SharedWith>), CodeError> {
269    if text.starts_with(RestoreCode::TEXT_PREFIX) {
270        let code = RestoreCode::from_text(text).map_err(|_| CodeError::Invalid)?;
271        let storage =
272            RestoreStorage::decode(code.storage.as_bytes()).map_err(|_| CodeError::Invalid)?;
273        let carries_s3_key = storage.s3_key.is_some();
274        Ok((DecodedCode::Restore(code), storage.location, carries_s3_key, None))
275    } else if text.starts_with(InviteCode::TEXT_PREFIX) {
276        let code = InviteCode::from_text(text).map_err(|_| CodeError::Invalid)?;
277        // Decoding checks that an S3 invite, and only one, carries a whole key.
278        let (invitation, carries_s3_key) =
279            match InviteStorage::decode(code.storage.as_bytes()).map_err(|_| CodeError::Invalid)? {
280                InviteStorage::Account(invitation) => (invitation, false),
281                InviteStorage::S3 { invitation, .. } => (invitation, true),
282            };
283        Ok((
284            DecodedCode::Invite(code),
285            invitation.location().clone(),
286            carries_s3_key,
287            invitation.account().cloned(),
288        ))
289    } else if text.starts_with(PairingCode::TEXT_PREFIX) {
290        let code = PairingCode::from_text(text).map_err(|_| CodeError::Invalid)?;
291        let storage =
292            RestoreStorage::decode(code.storage.as_bytes()).map_err(|_| CodeError::Invalid)?;
293        let carries_s3_key = storage.s3_key.is_some();
294        Ok((DecodedCode::Pairing(code), storage.location, carries_s3_key, None))
295    } else {
296        Err(CodeError::Invalid)
297    }
298}
299
300#[cfg(test)]
301#[path = "codes_tests.rs"]
302mod tests;