Skip to main content

coven_storage/
invitation.rs

1use crate::{CloudProvider, StorageConfig, StorageError, StorageFailure};
2use coven_crypto::{SecretBytes, SecretText};
3use coven_format::code_fields::{FieldReader, FieldWriter};
4use serde::{Deserialize, Serialize};
5
6/// Provider information carried inside coven's encrypted invite code. Native
7/// share tokens admit the recipient; they never identify grants for revocation.
8#[derive(Clone, Serialize, Deserialize)]
9#[serde(try_from = "RecordedInvitation")]
10pub struct StorageInvitation {
11    location: StorageConfig,
12    pub(crate) acceptance: InvitationAcceptance,
13    shared_with: Option<crate::SharedWith>,
14}
15#[derive(Clone, Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub(crate) enum InvitationAcceptance {
18    Granted,
19    DropboxMount,
20    OneDriveShare { token: SecretText },
21    CloudKitShare { url: SecretText },
22}
23#[derive(Deserialize)]
24#[serde(deny_unknown_fields)]
25struct RecordedInvitation {
26    location: StorageConfig,
27    acceptance: InvitationAcceptance,
28    shared_with: Option<crate::SharedWith>,
29}
30impl TryFrom<RecordedInvitation> for StorageInvitation {
31    type Error = StorageError;
32    fn try_from(value: RecordedInvitation) -> Result<Self, Self::Error> {
33        let invitation = Self::new(value.location, value.acceptance)?;
34        Ok(Self { shared_with: value.shared_with, ..invitation })
35    }
36}
37impl std::fmt::Debug for StorageInvitation {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.debug_struct("StorageInvitation")
40            .field("provider", &self.location.provider())
41            .finish_non_exhaustive()
42    }
43}
44impl StorageInvitation {
45    /// An already granted account location, or Dropbox's shared namespace to
46    /// mount. An S3 admin uses this after making the member's key in the console.
47    /// CloudKit instead needs the share URL returned by `grant_access`.
48    pub fn for_account(location: StorageConfig) -> Result<Self, StorageError> {
49        let acceptance = match location.provider() {
50            CloudProvider::Dropbox => InvitationAcceptance::DropboxMount,
51            CloudProvider::CloudKit => {
52                return Err(StorageFailure::InvalidConfiguration
53                    .with_source("CloudKit requires a share URL"))
54            }
55            _ => InvitationAcceptance::Granted,
56        };
57        Self::new(location, acceptance)
58    }
59    pub(crate) fn new(
60        location: StorageConfig,
61        acceptance: InvitationAcceptance,
62    ) -> Result<Self, StorageError> {
63        location.validate()?;
64        if matches!(
65            location,
66            StorageConfig::Dropbox { location: crate::DropboxLocation::AppFolder, .. }
67        ) {
68            return Err(StorageFailure::DropboxAppFolderNotShareable.into());
69        }
70        match (location.provider(), &acceptance) {
71            (CloudProvider::S3 | CloudProvider::OneDrive, InvitationAcceptance::Granted)
72            | (CloudProvider::Dropbox, InvitationAcceptance::DropboxMount) => {}
73            (CloudProvider::OneDrive, InvitationAcceptance::OneDriveShare { token })
74                if !token.as_str().is_empty() => {}
75            (CloudProvider::CloudKit, InvitationAcceptance::CloudKitShare { url }) => {
76                let url = url::Url::parse(url.as_str())
77                    .map_err(|error| StorageFailure::InvalidConfiguration.with_source(error))?;
78                if !crate::web_url::is_web_url(&url) || url.scheme() != "https" {
79                    return Err(StorageFailure::InvalidConfiguration
80                        .with_source("invalid CloudKit share URL"));
81                }
82            }
83            _ => {
84                return Err(StorageFailure::InvalidConfiguration
85                    .with_source("invitation does not match its provider"))
86            }
87        }
88        Ok(Self { location, acceptance, shared_with: None })
89    }
90    /// This invitation as shared with `account`, which a Dropbox or OneDrive
91    /// invite code carries so the joining device can check the sign-in it
92    /// holds is that account's (ยง13.2).
93    pub fn shared_with(self, account: crate::SharedWith) -> Self {
94        Self { shared_with: Some(account), ..self }
95    }
96    /// The account the folder was shared with, when the invitation records one.
97    pub fn account(&self) -> Option<&crate::SharedWith> {
98        self.shared_with.as_ref()
99    }
100    /// Nonsecret location used to construct the joining account's adapter.
101    pub fn location(&self) -> &StorageConfig {
102        &self.location
103    }
104    /// Encode as the database records a granted invitation, with bytes erased
105    /// on drop. An invite code packs it instead (format.md D13).
106    pub fn encode(&self) -> Result<SecretBytes, StorageError> {
107        crate::secret_json::encode(self)
108    }
109    /// Decode and validate an invitation the database recorded.
110    pub fn decode(bytes: &[u8]) -> Result<Self, StorageError> {
111        crate::secret_json::decode(bytes)
112    }
113    /// Pack the location, then how the recipient accepts it, into an invite
114    /// code's storage part (format.md D13). The location's provider fixes
115    /// which acceptance follows: nothing on S3, an optional share token on
116    /// OneDrive, the share URL on CloudKit; then, on Dropbox and OneDrive,
117    /// the account the folder was shared with.
118    pub(crate) fn pack(&self, out: &mut FieldWriter) -> Result<(), coven_format::Error> {
119        self.location.pack(out)?;
120        match &self.acceptance {
121            InvitationAcceptance::Granted
122                if self.location.provider() == CloudProvider::OneDrive =>
123            {
124                out.option(None::<&str>, FieldWriter::text)?
125            }
126            InvitationAcceptance::Granted | InvitationAcceptance::DropboxMount => (),
127            InvitationAcceptance::OneDriveShare { token } => {
128                out.option(Some(token.as_str()), FieldWriter::text)?
129            }
130            InvitationAcceptance::CloudKitShare { url } => out.text(url.as_str())?,
131        }
132        match &self.shared_with {
133            Some(account) => {
134                out.text(account.address())?;
135                out.option(account.id(), FieldWriter::text)
136            }
137            None => Ok(()),
138        }
139    }
140    /// Read an invitation packed by [`Self::pack`], checked as `new` checks one.
141    pub(crate) fn unpack(input: &mut FieldReader<'_>) -> Result<Self, StorageError> {
142        let location = StorageConfig::unpack(input)?;
143        let acceptance = match location.provider() {
144            CloudProvider::S3 => InvitationAcceptance::Granted,
145            CloudProvider::Dropbox => InvitationAcceptance::DropboxMount,
146            CloudProvider::OneDrive => {
147                match input.option(|input| input.secret_text("share token"))? {
148                    Some(token) => InvitationAcceptance::OneDriveShare { token },
149                    None => InvitationAcceptance::Granted,
150                }
151            }
152            CloudProvider::CloudKit => {
153                InvitationAcceptance::CloudKitShare { url: input.secret_text("share URL")? }
154            }
155        };
156        let invitation = Self::new(location, acceptance)?;
157        match invitation.location.provider() {
158            CloudProvider::Dropbox | CloudProvider::OneDrive => {
159                let address = input.text("shared-with account")?;
160                let id = input.option(|input| input.text("shared-with account id"))?;
161                let shared = crate::SharedWith::new(&address, id)?;
162                // One spelling per account, as for a location.
163                if shared.address() != address {
164                    return Err(StorageFailure::Encoding
165                        .with_source("shared-with account is not in normal form"));
166                }
167                Ok(invitation.shared_with(shared))
168            }
169            CloudProvider::S3 | CloudProvider::CloudKit => Ok(invitation),
170        }
171    }
172    pub(crate) fn check(&self, location: &StorageConfig) -> Result<(), StorageError> {
173        if !self.location.same_location(location) {
174            return Err(StorageFailure::InvitationMismatch.into());
175        }
176        Ok(())
177    }
178}
179
180#[cfg(test)]
181#[path = "invitation_tests.rs"]
182mod tests;