1use crate::io::docs::LocalDocuments;
2use crate::io::server::Server;
3use std::collections::HashSet;
4
5use crate::Lb;
6use crate::model::crypto::{AESKey, DecryptedDocument, EncryptedDocument};
7use crate::model::errors::{LbErrKind, LbResult};
8use crate::model::file_like::FileLike;
9use crate::model::file_metadata::{DocumentHmac, FileType};
10use crate::model::filename::DocumentType;
11use crate::model::secret_filename::HmacSha256;
12use crate::model::tree_like::TreeLike;
13use crate::model::{compression_service, symkey, validate};
14use hmac::{Mac, NewMac};
15use uuid::Uuid;
16
17use super::events::Actor;
18
19impl<S: Server, D: LocalDocuments> Lb<S, D> {
20 #[instrument(level = "debug", skip(self), err(Debug))]
21 pub async fn read_document(
22 &self, id: Uuid, user_activity: bool,
23 ) -> LbResult<DecryptedDocument> {
24 let (_, doc) = self.read_document_with_hmac(id, user_activity).await?;
25 Ok(doc)
26 }
27
28 #[instrument(level = "debug", skip(self, content), err(Debug))]
29 pub async fn write_document(&self, id: Uuid, content: &[u8]) -> LbResult<()> {
30 let (id, key) = {
32 let tx = self.ro_tx().await;
33 let db = tx.db();
34 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
35 let id = match tree.find(&id)?.file_type() {
36 FileType::Document | FileType::Folder => id,
37 FileType::Link { target } => target,
38 };
39 validate::is_document(tree.find(&id)?)?;
40 (id, tree.decrypt_key(&id, &self.keychain)?)
41 };
42
43 let (hmac, encrypted) = compress_encrypt_document(&key, content)?;
45 let encrypted_size = encrypted.value.len();
46 let pending = self.docs.insert_pending(id, hmac, &encrypted).await?;
47
48 {
50 let mut tx = self.begin_tx().await;
51 let db = tx.db();
52 let mut tree = (&db.base_metadata)
53 .to_staged(&mut db.local_metadata)
54 .to_lazy();
55 pending.promote().await?;
56 tree.overwrite_document_hmac(&id, Some(hmac), Some(encrypted_size), &self.keychain)?;
57 tx.end();
58 }
59
60 self.events.doc_written(id, Actor::User(None));
61
62 Ok(())
63 }
64
65 #[instrument(level = "debug", skip(self), err(Debug))]
66 pub async fn read_document_with_hmac(
67 &self, id: Uuid, user_activity: bool,
68 ) -> LbResult<(Option<DocumentHmac>, DecryptedDocument)> {
69 let mut retried = false;
71 let info: Option<(DocumentHmac, AESKey, Option<EncryptedDocument>)> = loop {
72 let tx = self.ro_tx().await;
73 let db = tx.db();
74 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
75
76 let file = tree.find(&id)?;
77 validate::is_document(file)?;
78 let hmac = file.document_hmac().copied();
79
80 if tree.calculate_deleted(&id)? {
81 return Err(LbErrKind::FileNonexistent.into());
82 }
83
84 match hmac {
85 Some(hmac) => {
86 let key = tree.decrypt_key(&id, &self.keychain)?;
87 let local_blob = self.docs.maybe_get(id, hmac).await?;
88 if local_blob.is_none() && !retried {
89 drop(tx);
90 self.begin_tx().await.end();
92 retried = true;
93 continue;
94 }
95 break Some((hmac, key, local_blob));
96 }
97 None => break None,
98 }
99 };
100
101 let (hmac, doc) = match info {
104 None => (None, vec![]),
105 Some((hmac, key, local_blob)) => {
106 let encrypted = match local_blob {
107 Some(blob) => blob,
108 None => self.fetch_doc(id, hmac).await?,
110 };
111 let doc = decrypt_decompress_document(&key, &encrypted)?;
112 (Some(hmac), doc)
113 }
114 };
115
116 Ok((hmac, doc))
117 }
118
119 #[instrument(level = "debug", skip(self, content), err(Debug))]
120 pub async fn safe_write(
121 &self, id: Uuid, old_hmac: Option<DocumentHmac>, content: &[u8], origin: Option<Uuid>,
122 ) -> LbResult<DocumentHmac> {
123 let (target_id, key) = {
125 let tx = self.ro_tx().await;
126 let db = tx.db();
127 let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
128 let file = tree.find(&id)?;
129 if file.document_hmac() != old_hmac.as_ref() {
130 return Err(LbErrKind::ReReadRequired.into());
131 }
132 let target_id = match file.file_type() {
133 FileType::Document | FileType::Folder => id,
134 FileType::Link { target } => target,
135 };
136 validate::is_document(tree.find(&target_id)?)?;
137 (target_id, tree.decrypt_key(&target_id, &self.keychain)?)
138 };
139
140 let (hmac, encrypted) = compress_encrypt_document(&key, content)?;
142 let encrypted_size = encrypted.value.len();
143 let pending = self
144 .docs
145 .insert_pending(target_id, hmac, &encrypted)
146 .await?;
147
148 {
150 let mut tx = self.begin_tx().await;
151 let db = tx.db();
152 let mut tree = (&db.base_metadata)
153 .to_staged(&mut db.local_metadata)
154 .to_lazy();
155 pending.promote().await?;
156 if tree.find(&id)?.document_hmac() != old_hmac.as_ref() {
157 return Err(LbErrKind::ReReadRequired.into());
158 }
159 tree.overwrite_document_hmac(
160 &target_id,
161 Some(hmac),
162 Some(encrypted_size),
163 &self.keychain,
164 )?;
165 tx.end();
166 }
167
168 self.events.doc_written(target_id, Actor::User(origin));
169
170 Ok(hmac)
171 }
172
173 #[instrument(level = "debug", skip(self, base, ours), err(Debug))]
178 pub async fn write_from_base(
179 &self, id: Uuid, base: &[u8], ours: Vec<u8>, origin: Option<Uuid>,
180 ) -> LbResult<(Option<DocumentHmac>, bool)> {
181 let name = self.get_file_by_id(id).await?.name;
182 loop {
183 let (hmac, theirs) = self.read_document_with_hmac(id, false).await?;
184 if theirs == ours || ours == base {
185 return Ok((hmac, false));
186 }
187 let moved = theirs != base;
188 let merged;
189 let content = if moved {
190 merged = DocumentType::from_file_name_using_extension(&name)
191 .merge(base, &ours, &theirs)
192 .ok_or(LbErrKind::ReReadRequired)?;
193 &merged
194 } else {
195 &ours
196 };
197 match self.safe_write(id, hmac, content, origin).await {
198 Ok(hmac) => return Ok((Some(hmac), moved)),
199 Err(err) if err.kind == LbErrKind::ReReadRequired => continue,
201 Err(err) => return Err(err),
202 }
203 }
204 }
205
206 pub(crate) async fn cleanup(&self) -> LbResult<()> {
207 let tx = self.ro_tx().await;
208 let db = tx.db();
209
210 let tree = db.base_metadata.stage(&db.local_metadata);
211
212 let base_files = tree.base.all_files()?.into_iter();
213 let local_files = tree.staged.all_files()?.into_iter();
214
215 let file_hmacs = base_files
216 .chain(local_files)
217 .filter_map(|f| f.document_hmac().map(|hmac| (*f.id(), *hmac)))
218 .collect::<HashSet<_>>();
219
220 self.docs.retain(file_hmacs).await?;
221
222 drop(tx);
223
224 Ok(())
225 }
226}
227
228pub(crate) fn document_hmac(key: &AESKey, content: &[u8]) -> LbResult<DocumentHmac> {
230 let mut mac = HmacSha256::new_from_slice(key)
231 .map_err(|err| LbErrKind::Unexpected(format!("hmac creation error: {err:?}")))?;
232 mac.update(content);
233 Ok(mac.finalize().into_bytes().into())
234}
235
236pub(crate) fn compress_encrypt_document(
237 key: &AESKey, content: &[u8],
238) -> LbResult<(DocumentHmac, EncryptedDocument)> {
239 let hmac = document_hmac(key, content)?;
240 let compressed = compression_service::compress(content)?;
241 let encrypted = symkey::encrypt(key, &compressed)?;
242 Ok((hmac, encrypted))
243}
244
245fn decrypt_decompress_document(
246 key: &AESKey, encrypted: &EncryptedDocument,
247) -> LbResult<DecryptedDocument> {
248 let compressed = symkey::decrypt(key, encrypted)?;
249 let doc = compression_service::decompress(&compressed)?;
250 Ok(doc)
251}