Skip to main content

coven_storage/
config.rs

1use coven_format::code_fields::{FieldReader, FieldWriter};
2use coven_format::Error as FieldError;
3use serde::{Deserialize, Serialize};
4
5/// A provider supported by coven (§20.2).
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
7pub enum CloudProvider {
8    /// S3, including compatible providers.
9    S3,
10    /// Dropbox.
11    Dropbox,
12    /// OneDrive.
13    OneDrive,
14    /// iCloud through coven-storage's native Apple-platform adapter.
15    CloudKit,
16}
17
18// `coven_sync_status.provider` holds a provider by its name (api.md E4).
19coven_foundation::column_names!(CloudProvider, "provider", {
20    S3 => "S3",
21    Dropbox => "Dropbox",
22    OneDrive => "OneDrive",
23    CloudKit => "CloudKit",
24});
25
26impl CloudProvider {
27    /// Instructions for cutting off a removed device's provider access (§14.2).
28    /// This depends on the provider kind, not on a connected account or request.
29    /// None on S3: the member's other devices share the key, which stays theirs.
30    pub fn sign_out(self) -> Option<crate::ProviderSignOut> {
31        match self {
32            Self::S3 => None,
33            Self::CloudKit => Some(crate::ProviderSignOut::RemoveFromAppleAccount),
34            provider => Some(crate::ProviderSignOut::RemoveAppAccess { provider }),
35        }
36    }
37
38    /// Whether a person signs in to it in a browser (OAuth): Dropbox and
39    /// OneDrive.
40    pub fn signs_in_with_oauth(self) -> bool {
41        matches!(self, Self::Dropbox | Self::OneDrive)
42    }
43}
44
45/// The store's location; credentials are kept separately in key custody.
46#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub enum StorageConfig {
49    /// An existing S3 bucket, which the store has to itself: coven can't
50    /// tell how far a member's key reaches, so it takes every key to reach
51    /// the whole bucket (§20.7). Paths start at the bucket's root.
52    S3 {
53        /// Bucket name.
54        bucket: String,
55        /// Signing region.
56        region: String,
57        /// None is AWS's own endpoint. Catalogued hosts (Appendix E.3) require https.
58        endpoint: Option<url::Url>,
59        /// A catalogued service's name or custom settings; either must agree
60        /// with a catalogued endpoint host. None selects by host:
61        /// storage.googleapis.com is GCS XML, hosts ending in
62        /// .r2.cloudflarestorage.com are R2, no endpoint or .amazonaws.com is
63        /// AWS, and setup detects any other endpoint's settings, recording
64        /// them as Custom. All run the setup checks.
65        profile: Option<crate::S3Profile>,
66    },
67    /// Dropbox's access and location, fixed when cloud storage is created.
68    Dropbox {
69        /// Required choice: not-shared App folder or a shared-capable namespace.
70        location: crate::DropboxLocation,
71        /// Signed-in member's display label; absent before setup. Never routes or authorizes.
72        account_label: Option<String>,
73        /// The shared folder's name and web address as the latest connection
74        /// read them; absent before setup and in the App folder (§20.2).
75        folder_label: Option<FolderLabel>,
76    },
77    /// A OneDrive folder; paths within it start with the store id.
78    OneDrive {
79        /// Drive containing the folder.
80        drive_id: String,
81        /// Folder shared with members' Microsoft accounts.
82        folder_id: String,
83        /// Signed-in member's display label; absent before setup. Never routes or authorizes.
84        account_label: Option<String>,
85        /// The folder's name and web address as the latest connection read
86        /// them; absent before setup (§20.2).
87        folder_label: Option<FolderLabel>,
88    },
89    /// The custom zone reached by the built-in CloudKit adapter.
90    CloudKit {
91        /// App's CloudKit container.
92        container: String,
93        /// Owner's CloudKit record name.
94        owner: String,
95        /// Custom zone containing the store.
96        zone: String,
97    },
98}
99
100/// A Dropbox shared folder's or a OneDrive folder's name and web address,
101/// as the member's account named them at this device's latest connection
102/// (§20.2). Display only: coven never reaches storage through them.
103#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105pub struct FolderLabel {
106    /// The provider's name for the folder.
107    pub name: String,
108    /// Where the folder opens in a browser: an https address.
109    pub web_url: url::Url,
110}
111
112impl FolderLabel {
113    /// The label a provider answered with; one this refuses is a protocol
114    /// failure.
115    pub(crate) fn answered(name: &str, web_url: &str) -> Result<Self, crate::StorageError> {
116        let web_url = url::Url::parse(web_url)
117            .map_err(|error| crate::StorageFailure::Protocol.with_source(error))?;
118        let label = Self { name: name.into(), web_url };
119        label.validate().map_err(|error| crate::StorageFailure::Protocol.with_source(error))?;
120        Ok(label)
121    }
122
123    /// Refuse an empty name or an address a browser shouldn't be sent to.
124    fn validate(&self) -> Result<(), crate::StorageError> {
125        if self.name.trim().is_empty() || self.name.chars().any(char::is_control) {
126            return Err(crate::StorageFailure::InvalidConfiguration
127                .with_source("empty or invalid folder name"));
128        }
129        if self.web_url.scheme() != "https" || !crate::web_url::is_web_url(&self.web_url) {
130            return Err(crate::StorageFailure::InvalidConfiguration
131                .with_source("a folder's web address must be https"));
132        }
133        Ok(())
134    }
135}
136
137impl StorageConfig {
138    /// Whether these settings reach the same location, ignoring display labels.
139    pub fn same_location(&self, other: &Self) -> bool {
140        match (self, other) {
141            (Self::Dropbox { location: a, .. }, Self::Dropbox { location: b, .. }) => a == b,
142            (
143                Self::OneDrive { drive_id: ad, folder_id: af, .. },
144                Self::OneDrive { drive_id: bd, folder_id: bf, .. },
145            ) => ad == bd && af == bf,
146            // These providers carry no account label.
147            (Self::S3 { .. }, Self::S3 { .. }) | (Self::CloudKit { .. }, Self::CloudKit { .. }) => {
148                self == other
149            }
150            _ => false,
151        }
152    }
153
154    /// Whether both are S3 locations naming the same bucket, at one
155    /// endpoint and region, whatever profile reaches it.
156    pub fn same_s3_bucket(&self, other: &Self) -> bool {
157        match (self, other) {
158            (
159                Self::S3 { bucket: ab, region: ar, endpoint: ae, .. },
160                Self::S3 { bucket: bb, region: br, endpoint: be, .. },
161            ) => ab == bb && ar == br && ae == be,
162            _ => false,
163        }
164    }
165
166    /// Whether every member reaches the whole location, so it holds one
167    /// store, which the location marker at its root names (§20.3): a
168    /// Dropbox shared folder, a OneDrive folder, or an S3 bucket. Nobody else
169    /// reaches the Dropbox App folder, and a CloudKit store's zone is its own.
170    pub fn holds_one_store(&self) -> bool {
171        match self {
172            Self::S3 { .. } | Self::OneDrive { .. } => true,
173            Self::Dropbox { location, .. } => match location {
174                crate::DropboxLocation::SharedFolder { .. } => true,
175                crate::DropboxLocation::AppFolder => false,
176            },
177            Self::CloudKit { .. } => false,
178        }
179    }
180
181    /// Access required to open this location.
182    pub fn oauth_access(&self) -> Option<crate::OAuthAccess> {
183        match self {
184            Self::Dropbox { location, .. } => Some(crate::OAuthAccess::Dropbox(location.access())),
185            Self::OneDrive { .. } => Some(crate::OAuthAccess::OneDrive),
186            Self::S3 { .. } | Self::CloudKit { .. } => None,
187        }
188    }
189    /// The provider of this location.
190    pub fn provider(&self) -> CloudProvider {
191        match self {
192            Self::S3 { .. } => CloudProvider::S3,
193            Self::Dropbox { .. } => CloudProvider::Dropbox,
194            Self::OneDrive { .. } => CloudProvider::OneDrive,
195            Self::CloudKit { .. } => CloudProvider::CloudKit,
196        }
197    }
198
199    /// Reject missing location information before making a request.
200    pub fn validate(&self) -> Result<(), crate::StorageError> {
201        let fields: Vec<&str> = match self {
202            Self::S3 { bucket, region, endpoint, profile } => {
203                if let Some(endpoint) = endpoint {
204                    if !crate::web_url::is_web_url(endpoint)
205                        || endpoint.query().is_some()
206                        || endpoint.fragment().is_some()
207                    {
208                        return Err(
209                            crate::StorageFailure::InvalidConfiguration.with_source("S3 endpoint")
210                        );
211                    }
212                }
213                crate::providers::check_s3_profile(endpoint.as_ref(), profile.as_ref())?;
214                vec![bucket, region]
215            }
216            Self::Dropbox {
217                location: crate::DropboxLocation::AppFolder,
218                folder_label: Some(_),
219                ..
220            } => {
221                return Err(crate::StorageFailure::InvalidConfiguration
222                    .with_source("the Dropbox App folder has no folder label"));
223            }
224            Self::Dropbox { location: crate::DropboxLocation::AppFolder, .. } => vec![],
225            Self::Dropbox {
226                location: crate::DropboxLocation::SharedFolder { namespace_id },
227                folder_label,
228                ..
229            } => {
230                if let Some(label) = folder_label {
231                    label.validate()?;
232                }
233                vec![namespace_id]
234            }
235            Self::OneDrive { drive_id, folder_id, folder_label, .. } => {
236                if let Some(label) = folder_label {
237                    label.validate()?;
238                }
239                vec![drive_id, folder_id]
240            }
241            Self::CloudKit { container, owner, zone } => vec![container, owner, zone],
242        };
243        if fields.iter().any(|value| value.trim().is_empty() || value.chars().any(char::is_control))
244        {
245            return Err(crate::StorageFailure::InvalidConfiguration
246                .with_source("empty or invalid location"));
247        }
248        Ok(())
249    }
250}
251
252// A location's fields in a code's storage part (format.md D13): the
253// provider's tag, then that provider's own fields.
254const S3: u8 = 0;
255const DROPBOX: u8 = 1;
256const ONEDRIVE: u8 = 2;
257const CLOUDKIT: u8 = 3;
258
259impl StorageConfig {
260    /// Pack this location's fields into a code's storage part.
261    pub(crate) fn pack(&self, out: &mut FieldWriter) -> Result<(), FieldError> {
262        match self {
263            Self::S3 { bucket, region, endpoint, profile } => {
264                out.u8(S3)?;
265                out.text(bucket)?;
266                out.text(region)?;
267                out.option(endpoint.as_ref(), |out, url| out.text(url.as_str()))?;
268                out.option(profile.as_ref(), |out, profile| profile.pack(out))
269            }
270            // A code carries no folder label (format.md D13).
271            Self::Dropbox { location, account_label, folder_label: _ } => {
272                out.u8(DROPBOX)?;
273                match location {
274                    crate::DropboxLocation::AppFolder => out.u8(0)?,
275                    crate::DropboxLocation::SharedFolder { namespace_id } => {
276                        out.u8(1)?;
277                        out.text(namespace_id)?;
278                    }
279                }
280                out.option(account_label.as_deref(), FieldWriter::text)
281            }
282            Self::OneDrive { drive_id, folder_id, account_label, folder_label: _ } => {
283                out.u8(ONEDRIVE)?;
284                out.text(drive_id)?;
285                out.text(folder_id)?;
286                out.option(account_label.as_deref(), FieldWriter::text)
287            }
288            Self::CloudKit { container, owner, zone } => {
289                out.u8(CLOUDKIT)?;
290                out.text(container)?;
291                out.text(owner)?;
292                out.text(zone)
293            }
294        }
295    }
296
297    /// Read a location packed by [`Self::pack`], checked as `validate` checks
298    /// one. A text written in a spelling `pack` never writes, such as an
299    /// endpoint URL that isn't canonical, is refused.
300    pub(crate) fn unpack(input: &mut FieldReader<'_>) -> Result<Self, crate::StorageError> {
301        let location = match input.u8()? {
302            S3 => Self::S3 {
303                bucket: input.text("bucket")?,
304                region: input.text("region")?,
305                endpoint: input
306                    .option(|input| input.text("endpoint"))?
307                    .map(|text| recorded_url(&text))
308                    .transpose()?,
309                profile: input.option(crate::S3Profile::unpack)?,
310            },
311            DROPBOX => Self::Dropbox {
312                location: match input.u8()? {
313                    0 => crate::DropboxLocation::AppFolder,
314                    1 => crate::DropboxLocation::SharedFolder {
315                        namespace_id: input.text("namespace id")?,
316                    },
317                    tag => {
318                        return Err(FieldError::UnknownTag { field: "Dropbox location", tag }.into())
319                    }
320                },
321                account_label: input.option(|input| input.text("account label"))?,
322                folder_label: None,
323            },
324            ONEDRIVE => Self::OneDrive {
325                drive_id: input.text("drive id")?,
326                folder_id: input.text("folder id")?,
327                account_label: input.option(|input| input.text("account label"))?,
328                folder_label: None,
329            },
330            CLOUDKIT => Self::CloudKit {
331                container: input.text("container")?,
332                owner: input.text("owner")?,
333                zone: input.text("zone")?,
334            },
335            tag => return Err(FieldError::UnknownTag { field: "provider", tag }.into()),
336        };
337        location.validate()?;
338        Ok(location)
339    }
340}
341
342/// An endpoint as `pack` writes it: the URL's own serialization, and no other.
343fn recorded_url(text: &str) -> Result<url::Url, crate::StorageError> {
344    let url = url::Url::parse(text)
345        .map_err(|error| crate::StorageFailure::Encoding.with_source(error))?;
346    if url.as_str() != text {
347        return Err(crate::StorageFailure::Encoding
348            .with_source("a recorded S3 endpoint is not in its canonical spelling"));
349    }
350    Ok(url)
351}
352
353#[cfg(test)]
354#[path = "config_tests.rs"]
355mod tests;