Skip to main content

coven_crypto/custody/
mod.rs

1//! Where this device keeps its opened keys and its member's two key pairs (E1).
2
3use crate::{MaterialError, MemberIdentity, SecretBytes, StoreKeyring};
4use coven_foundation::files::StoreFile;
5use std::sync::Arc;
6
7mod app_secrets;
8#[cfg(any(target_os = "android", test, feature = "in-memory-keychain"))]
9mod block_store;
10#[cfg(target_os = "android")]
11mod block_store_jni;
12#[cfg(any(test, feature = "in-memory-keychain"))]
13mod block_store_test_utils;
14mod error;
15mod key_session;
16mod keychain;
17mod memory;
18mod passphrase;
19mod person_entries;
20mod platform;
21mod store_custody;
22
23pub use error::{KeyError, KeychainError};
24pub use key_session::KeySession;
25pub use keychain::{Keychain, KeyringCustody, StoreKeychain};
26pub use memory::InMemoryCustody;
27pub use passphrase::{Passphrase, PassphraseCustody};
28pub use person_entries::{PersonEntries, PersonRestoreCode, RestoreCodeChange};
29pub use store_custody::{IdentityError, StoreCustody};
30
31mod sealed {
32    pub trait Sealed {}
33}
34
35/// What custody keeps: the store keys or the member's identity. Sealed: coven
36/// alone says how each is named and encoded.
37pub trait KeyMaterial: sealed::Sealed + Clone + Send + Sync + 'static {
38    /// The keychain entry and passphrase file entry it is kept under.
39    const ENTRY: &'static str;
40    /// The store file a passphrase custody seals it in.
41    const FILE: StoreFile;
42    /// Encode it for custody.
43    fn to_secret_bytes(&self) -> SecretBytes;
44    /// Decode what `to_secret_bytes` encoded.
45    fn from_secret_bytes(bytes: &[u8]) -> Result<Self, MaterialError>;
46}
47
48impl sealed::Sealed for StoreKeyring {}
49impl sealed::Sealed for MemberIdentity {}
50
51impl KeyMaterial for StoreKeyring {
52    const ENTRY: &'static str = "store-keys";
53    const FILE: StoreFile = StoreFile::StoreKeys;
54    fn to_secret_bytes(&self) -> SecretBytes {
55        Self::to_secret_bytes(self)
56    }
57    fn from_secret_bytes(bytes: &[u8]) -> Result<Self, MaterialError> {
58        Self::from_secret_bytes(bytes)
59    }
60}
61
62impl KeyMaterial for MemberIdentity {
63    const ENTRY: &'static str = "member-keys";
64    const FILE: StoreFile = StoreFile::MemberKeys;
65    fn to_secret_bytes(&self) -> SecretBytes {
66        Self::to_secret_bytes(self)
67    }
68    fn from_secret_bytes(bytes: &[u8]) -> Result<Self, MaterialError> {
69        Self::from_secret_bytes(bytes)
70    }
71}
72
73/// The app's own store for key material this device holds (E1).
74pub trait Custody<T: KeyMaterial>: Send + Sync {
75    /// Called once at open; `None` when this device has never held `T`.
76    /// Retain the unlocked persistence capability until close.
77    fn unlock(&self) -> Result<Option<T>, KeyError>;
78    /// Keeps `material`, replacing what was kept.
79    fn persist(&self, material: &T) -> Result<(), KeyError>;
80    /// Removes what was kept; succeeds if nothing was kept.
81    fn forget(&self) -> Result<(), KeyError>;
82    /// Erase held memory after users finish; performs no persistence or IO.
83    fn close(&self);
84}
85
86/// Where this device keeps `T` (E1).
87pub enum CustodyChoice<T: KeyMaterial> {
88    /// The OS keychain under the service registered at startup.
89    Keyring,
90    /// A file sealed with a key derived from this passphrase.
91    Passphrase(Passphrase),
92    /// Starts empty; holds only this handle's session: what opening, creation,
93    /// restore or join puts there.
94    InMemory,
95    /// The app's own store for `T`.
96    Custom(Arc<dyn Custody<T>>),
97}
98
99impl<T: KeyMaterial> std::fmt::Debug for CustodyChoice<T> {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str(match self {
102            Self::Keyring => "CustodyChoice::Keyring",
103            Self::Passphrase(_) => "CustodyChoice::Passphrase([REDACTED])",
104            Self::InMemory => "CustodyChoice::InMemory",
105            Self::Custom(_) => "CustodyChoice::Custom(..)",
106        })
107    }
108}
109
110impl<T: KeyMaterial> Custody<T> for InMemoryCustody<T> {
111    fn unlock(&self) -> Result<Option<T>, KeyError> {
112        Ok(self.read())
113    }
114    fn persist(&self, material: &T) -> Result<(), KeyError> {
115        self.write(material);
116        Ok(())
117    }
118    fn forget(&self) -> Result<(), KeyError> {
119        self.remove();
120        Ok(())
121    }
122    fn close(&self) {
123        self.remove();
124    }
125}
126
127impl<T: KeyMaterial> Custody<T> for PassphraseCustody<T> {
128    fn unlock(&self) -> Result<Option<T>, KeyError> {
129        self.read(T::ENTRY)?
130            .map(|bytes| T::from_secret_bytes(bytes.as_bytes()).map_err(KeyError::from))
131            .transpose()
132    }
133    fn persist(&self, material: &T) -> Result<(), KeyError> {
134        self.write(T::ENTRY, material.to_secret_bytes().as_bytes())
135    }
136    fn forget(&self) -> Result<(), KeyError> {
137        self.remove()
138    }
139    fn close(&self) {
140        self.release();
141    }
142}
143
144impl<T: KeyMaterial> Custody<T> for KeyringCustody<T> {
145    fn unlock(&self) -> Result<Option<T>, KeyError> {
146        self.read(T::ENTRY)?
147            .map(|bytes| T::from_secret_bytes(bytes.as_bytes()).map_err(KeyError::from))
148            .transpose()
149    }
150    fn persist(&self, material: &T) -> Result<(), KeyError> {
151        self.write(T::ENTRY, material.to_secret_bytes().as_bytes())
152    }
153    fn forget(&self) -> Result<(), KeyError> {
154        self.remove(T::ENTRY)
155    }
156    fn close(&self) {}
157}
158
159#[cfg(test)]
160#[path = "mod_tests.rs"]
161mod tests;