Skip to main content

coven_storage/
provider_check.rs

1use crate::{
2    ByteRange, ObjectPath, ObjectPrefix, Storage, StorageCheck, StorageCheckError, StorageError,
3    StorageFailure,
4};
5
6/// How a provider check ended when nothing failed.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum CheckEnd {
9    /// Every step passed.
10    Passed,
11    /// The caller stopped the check between two of its steps; the test
12    /// object, if the check made it, is deleted.
13    Stopped,
14}
15
16/// Check a candidate provider before reserving or publishing setup state.
17/// The storage owner supplies a fresh path and sealed bytes: at least three,
18/// and within the single-request limit, because the conditional replacement
19/// it checks is one request.
20/// This calls the provider without committing credentials or local settings.
21/// Cleanup runs even after a lost create reply; a preexisting path is left intact.
22/// The caller must await cleanup even if its app waiter is cancelled.
23/// During setup the connection sends rate-limited requests again (ยง20.8),
24/// so a refusal fails the check only once the setup call's minute is spent.
25/// Before each step the check asks `stopped`, and once it answers true the
26/// check sends no further step: it deletes its test object and ends
27/// `Stopped`.
28pub async fn check_provider(
29    storage: &crate::StorageConnection<impl crate::ProviderOps + ?Sized>,
30    path: &ObjectPath,
31    encrypted_bytes: &[u8],
32    stopped: impl Fn() -> bool,
33) -> Result<CheckEnd, StorageCheckError> {
34    let end = encrypted_bytes
35        .len()
36        .checked_sub(1)
37        .ok_or(StorageError::Failure(StorageFailure::InvalidRange))?;
38    let range = ByteRange::new(1, end as u64)?;
39    if stopped() {
40        return Ok(CheckEnd::Stopped);
41    }
42    let created = match storage.create(path, encrypted_bytes).await {
43        Err(source) if source.failure() == StorageFailure::AlreadyExists => {
44            return Err(StorageCheckError::ProviderCheck { check: StorageCheck::Create, source })
45        }
46        created => created,
47    };
48    let mut check = StorageCheck::Create;
49    let result = async {
50        created?;
51        if stopped() {
52            return Ok(CheckEnd::Stopped);
53        }
54        check = StorageCheck::CreateOnce;
55        match storage.create(path, encrypted_bytes).await {
56            Err(error) if error.own_failure() == Some(StorageFailure::AlreadyExists) => {}
57            Err(error) => return Err(error),
58            Ok(_) => {
59                return Err(
60                    StorageFailure::Protocol.with_source("provider accepted a second create")
61                )
62            }
63        }
64        if stopped() {
65            return Ok(CheckEnd::Stopped);
66        }
67        check = StorageCheck::Read;
68        if storage.read(path).await? != encrypted_bytes {
69            return Err(StorageFailure::Protocol.with_source("whole read disagrees with upload"));
70        }
71        if stopped() {
72            return Ok(CheckEnd::Stopped);
73        }
74        check = StorageCheck::ReadRange;
75        if storage.read_range(path, range).await? != encrypted_bytes[1..end] {
76            return Err(StorageFailure::Protocol.with_source("range read disagrees with upload"));
77        }
78        if stopped() {
79            return Ok(CheckEnd::Stopped);
80        }
81        check = StorageCheck::ConditionalReplace;
82        let previous = storage.status(path).await?.ok_or(StorageFailure::NotFound)?;
83        let replacement = encrypted_bytes.iter().map(|byte| byte ^ 0x80).collect::<Vec<_>>();
84        storage.replace_object(&previous, &replacement).await?;
85        match storage.replace_object(&previous, encrypted_bytes).await {
86            Err(error) if error.failure() == StorageFailure::Conflict => {}
87            Err(error) => return Err(error),
88            Ok(()) => {
89                return Err(
90                    StorageFailure::Protocol.with_source("provider accepted a stale replacement")
91                )
92            }
93        }
94        if storage.read(path).await? != replacement {
95            return Err(StorageFailure::Protocol
96                .with_source("conditional replacement changed the wrong bytes"));
97        }
98        if stopped() {
99            return Ok(CheckEnd::Stopped);
100        }
101        check = StorageCheck::List;
102        if storage
103            .list(&ObjectPrefix::all(path.store()))
104            .await?
105            .iter()
106            .any(|object| &object.path == path && object.size != encrypted_bytes.len() as u64)
107        {
108            return Err(
109                StorageFailure::Protocol.with_source("test object has wrong size in listing")
110            );
111        }
112        Ok(CheckEnd::Passed)
113    }
114    .await;
115    let cleanup = async {
116        storage.delete(path).await?;
117        match storage.read(path).await {
118            Err(error) if error.failure() == StorageFailure::NotFound => Ok(()),
119            Err(error) => Err(error),
120            Ok(_) => {
121                Err(StorageFailure::Protocol.with_source("deleted test object is still readable"))
122            }
123        }
124    }
125    .await;
126    // A check that passed or stopped, and failed only to delete its object,
127    // failed deleting.
128    if result.is_ok() && cleanup.is_err() {
129        check = StorageCheck::Delete;
130    }
131    crate::transfer::with_cleanup(result, cleanup)
132        .map_err(|source| StorageCheckError::ProviderCheck { check, source })
133}
134
135#[cfg(test)]
136#[path = "provider_check_tests.rs"]
137mod tests;