ctb_storage/models/
sync.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Data structures and cryptographic models for client-to-server data backup.
21
22#[expect(unused_imports, reason = "imported module dependencies")]
23use crate::utilities::*;
24
25use crate::anyhow::{Result, anyhow, bail};
26use base64::Engine;
27use serde::{Deserialize, Serialize};
28
29use crate::blind_signatures::{client_blind, client_finalize};
30use crate::https::{ClientOptions, async_client};
31
32// --- Client DTOs ---
33
34#[derive(Serialize)]
35struct TokenIssueRequest {
36    blinded_elements: Vec<String>,
37}
38
39#[derive(Deserialize)]
40struct TokenIssueResponse {
41    evaluations: Vec<String>,
42}
43
44#[derive(Serialize)]
45struct SyncStartRequest {
46    serial_hex: String,
47    token_tag_hex: String,
48}
49
50#[derive(Deserialize)]
51struct SyncStartResponse {
52    session_id: String,
53    upload_allowance: usize,
54}
55
56#[derive(Serialize)]
57struct ReserveIdsRequest {
58    graph_id: u128,
59}
60
61#[derive(Deserialize)]
62struct ReserveIdsResponse {
63    start_id: u64,
64    end_id: u64,
65}
66
67#[derive(Serialize)]
68struct UploadChunkRequest {
69    chunk_hash: String,
70    chunk_data_hex: String,
71}
72
73#[derive(Serialize, Deserialize, Debug, Clone)]
74pub struct IdRange {
75    pub start_id: u64,
76    pub end_id: u64,
77    pub next_id: u64,
78}
79
80// --- Client APIs ---
81
82/// Replenish local blind tokens by authenticating with the server and issuing a batch of signed tokens.
83pub async fn replenish_tokens(
84    server_url: &str,
85    user_session_token: &str,
86    count: usize,
87) -> Result<()> {
88    if count == 0 {
89        return Ok(());
90    }
91
92    let user_id = ipcb!(storage)
93        .validate_session_b(user_session_token)?
94        .ok_or_else(|| anyhow!("Unauthorized session token"))?;
95
96    let mut serials = Vec::with_capacity(count);
97    let mut blinded_elements = Vec::with_capacity(count);
98    let mut client_states = Vec::with_capacity(count);
99
100    for _ in 0..count {
101        let mut serial = [0u8; 32];
102        rand::RngCore::fill_bytes(&mut rand::rng(), &mut serial);
103        let (blinded, state) = client_blind(&serial)?;
104
105        serials.push(serial.to_vec());
106        blinded_elements
107            .push(base64::engine::general_purpose::STANDARD.encode(blinded));
108        client_states.push(state);
109    }
110
111    // Call /api/tokens/issue on server
112    let client = async_client(ClientOptions::default())?;
113    let url = format!("{server_url}/api/tokens/issue");
114
115    let resp = client
116        .inner
117        .post(&url)
118        .header("Cookie", format!("session={user_session_token}"))
119        .json(&TokenIssueRequest { blinded_elements })
120        .send()
121        .await?;
122
123    if !resp.status().is_success() {
124        bail!("Server token issuance failed: status {}", resp.status());
125    }
126
127    let body: TokenIssueResponse = resp.json().await?;
128
129    // Finalize tokens
130    for i in 0..count {
131        let serial = serials
132            .get(i)
133            .ok_or_else(|| anyhow!("Serial out of bounds"))?;
134        let state = client_states
135            .get(i)
136            .ok_or_else(|| anyhow!("State out of bounds"))?;
137        let eval_str = body
138            .evaluations
139            .get(i)
140            .ok_or_else(|| anyhow!("Evaluation out of bounds"))?;
141        let eval_bytes =
142            base64::engine::general_purpose::STANDARD.decode(eval_str)?;
143
144        let token_tag = client_finalize(serial, state, &eval_bytes)?;
145
146        // Save unspent token locally
147        let serial_hex = bin2hex(serial);
148        let tag_hex = bin2hex(token_tag);
149        #[expect(
150            clippy::expect_used,
151            reason = "Loop index i (usize) is guaranteed to fit in u64"
152        )]
153        let key_val = u64::try_from(i).expect("usize index i fits in u64");
154        ipcb!(storage).save_local_token_b(
155            user_id,
156            key_val,
157            &format!("{serial_hex}:{tag_hex}"),
158        )?;
159    }
160
161    Ok(())
162}
163
164/// Spend one local token to initiate an anonymous sync session with the server.
165pub async fn start_sync_session(
166    server_url: &str,
167    user_id: u64,
168) -> Result<String> {
169    // 1. Fetch any available local token
170    let tokens = ipcb!(storage).get_local_tokens_b(user_id)?;
171    let (key, token_str) = tokens.first().ok_or_else(|| {
172        anyhow!("No local sync tokens available. Please purchase a subscription/replenish tokens.")
173    })?;
174
175    // Format: serial_hex:tag_hex
176    let parts: Vec<&str> = token_str.split(':').collect();
177    let serial_hex = parts
178        .first()
179        .ok_or_else(|| anyhow!("Missing serial"))?
180        .to_string();
181    let token_tag_hex = parts
182        .get(1)
183        .ok_or_else(|| anyhow!("Missing tag"))?
184        .to_string();
185
186    // 2. Call /api/sync/start
187    let client = async_client(ClientOptions::default())?;
188    let url = format!("{server_url}/api/sync/start");
189
190    let resp = client
191        .inner
192        .post(&url)
193        .json(&SyncStartRequest {
194            serial_hex,
195            token_tag_hex,
196        })
197        .send()
198        .await?;
199
200    if !resp.status().is_success() {
201        bail!(
202            "Failed to start sync session on server: status {}",
203            resp.status()
204        );
205    }
206
207    // 3. Remove spent token locally
208    ipcb!(storage).delete_local_token_b(user_id, *key)?;
209
210    let body: SyncStartResponse = resp.json().await?;
211    Ok(body.session_id)
212}
213
214/// Proactively reserve a block of 10,000 IDs from the server.
215pub async fn reserve_ids_remote(
216    user_id: u64,
217    server_url: &str,
218    session_id: &str,
219    graph_id: u128,
220) -> Result<IdRange> {
221    let client = async_client(ClientOptions::default())?;
222    let url = format!("{server_url}/api/sync/reserve-ids");
223
224    let resp = client
225        .inner
226        .post(&url)
227        .header("Authorization", format!("Bearer {session_id}"))
228        .json(&ReserveIdsRequest { graph_id })
229        .send()
230        .await?;
231
232    if !resp.status().is_success() {
233        bail!("Failed to reserve IDs: status {}", resp.status());
234    }
235
236    let body: ReserveIdsResponse = resp.json().await?;
237
238    let range = IdRange {
239        start_id: body.start_id,
240        end_id: body.end_id,
241        next_id: body.start_id,
242    };
243
244    // Save locally
245    let json_bytes = serde_json::to_vec(&range)?;
246    ipcb!(storage).save_local_id_range_b(user_id, graph_id, json_bytes)?;
247
248    Ok(range)
249}
250
251/// Allocate a node ID locally, requesting a new range from the server proactively if remaining count drops below 3,000.
252pub async fn allocate_local_id(
253    user_id: u64,
254    graph_id: u128,
255    server_url: &str,
256    session_id: Option<&str>,
257) -> Result<u128> {
258    let mut range: Option<IdRange> = ipcb!(storage)
259        .get_local_id_range_b(user_id, graph_id)?
260        .and_then(|bytes| serde_json::from_slice(&bytes).ok());
261
262    let current_range = if let Some(r) = range.as_mut() {
263        if r.next_id > r.end_id {
264            // Out of IDs! Must fetch synchronously
265            let Some(sid) = session_id else {
266                return Err(anyhow!(
267                    "No local IDs remaining and no active session to reserve more."
268                ));
269            };
270            let new_range =
271                reserve_ids_remote(user_id, server_url, sid, graph_id).await?;
272            r.start_id = new_range.start_id;
273            r.end_id = new_range.end_id;
274            r.next_id = new_range.start_id;
275        }
276        r
277    } else {
278        // First time requesting range, must fetch synchronously
279        let Some(sid) = session_id else {
280            return Err(anyhow!(
281                "No local ID range initialized for graph {graph_id} and no active session."
282            ));
283        };
284        let new_range =
285            reserve_ids_remote(user_id, server_url, sid, graph_id).await?;
286        range = Some(new_range);
287        range
288            .as_mut()
289            .ok_or_else(|| anyhow!("Failed to initialize range"))?
290    };
291
292    let allocated_id = current_range.next_id;
293    current_range.next_id = current_range.next_id.saturating_add(1);
294
295    // Proactive background reservation if remaining count falls below 3,000
296    let remaining = if current_range.end_id >= current_range.next_id {
297        current_range
298            .end_id
299            .saturating_sub(current_range.next_id)
300            .saturating_add(1)
301    } else {
302        0
303    };
304    if remaining < 3000 {
305        if let Some(sid) = session_id {
306            let sid = sid.to_string();
307            let server_url = server_url.to_string();
308            tokio::spawn(async move {
309                let _ =
310                    reserve_ids_remote(user_id, &server_url, &sid, graph_id)
311                        .await;
312            });
313        }
314    }
315
316    // Save updated range locally
317    let json_bytes = serde_json::to_vec(&current_range)?;
318    ipcb!(storage).save_local_id_range_b(user_id, graph_id, json_bytes)?;
319
320    Ok(u128::from(allocated_id))
321}
322
323/// Slices local node data into 32KB chunks and uploads them.
324pub async fn upload_graph_chunk(
325    server_url: &str,
326    session_id: &str,
327    chunk_hash: &str,
328    chunk_data: &[u8],
329) -> Result<()> {
330    let client = async_client(ClientOptions::default())?;
331    let url = format!("{server_url}/api/sync/chunks");
332
333    let chunk_data_hex = bin2hex(chunk_data);
334    let resp = client
335        .inner
336        .post(&url)
337        .header("Authorization", format!("Bearer {session_id}"))
338        .json(&UploadChunkRequest {
339            chunk_hash: chunk_hash.to_string(),
340            chunk_data_hex,
341        })
342        .send()
343        .await?;
344
345    if !resp.status().is_success() {
346        bail!("Failed to upload chunk: status {}", resp.status());
347    }
348    Ok(())
349}
350
351#[derive(Serialize, Deserialize, Debug, Clone)]
352pub struct ApiRegisterRequest {
353    pub username: String,
354    pub uuid: Vec<u8>,
355    pub auth: Option<String>,
356    pub key_encryption_key_params: Option<Vec<u8>>,
357    pub wrapped_dek: Option<Vec<u8>>,
358    pub display_name: Option<Vec<u8>>,
359}
360
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub enum RemoteRegisterResult {
363    Success,
364    Conflict,
365    Offline,
366}
367
368use std::collections::HashMap;
369use std::sync::Mutex;
370static MOCK_REGISTER_RESULTS: Mutex<
371    Option<HashMap<String, RemoteRegisterResult>>,
372> = Mutex::new(None);
373
374pub fn set_mock_register_result(result: Option<RemoteRegisterResult>) {
375    if let Some(test_name) = ctb_utilities::testing::try_get_current_test_name()
376    {
377        if let Ok(mut lock) = MOCK_REGISTER_RESULTS.lock() {
378            let map = lock.get_or_insert_with(HashMap::new);
379            if let Some(res) = result {
380                map.insert(test_name, res);
381            } else {
382                map.remove(&test_name);
383            }
384        }
385    }
386}
387
388pub async fn register_on_server(
389    user_id: u64,
390    server_url: &str,
391) -> Result<RemoteRegisterResult> {
392    if ctb_utilities::testing::is_in_test() {
393        if let Some(test_name) =
394            ctb_utilities::testing::try_get_current_test_name()
395        {
396            if let Ok(lock) = MOCK_REGISTER_RESULTS.lock() {
397                if let Some(ref map) = *lock {
398                    if let Some(&mocked) = map.get(&test_name) {
399                        return Ok(mocked);
400                    }
401                }
402            }
403        }
404        // If we are in test mode and no mock outcome has been configured for this test,
405        // default to Offline to prevent any outgoing network/DNS requests.
406        return Ok(RemoteRegisterResult::Offline);
407    }
408
409    let dto = ipcb!(storage)
410        .get_user_by_id_b(user_id)?
411        .ok_or_else(|| anyhow!("User not found for registration"))?;
412
413    let req_body = ApiRegisterRequest {
414        username: dto.username,
415        uuid: dto.uuid,
416        auth: dto.auth,
417        key_encryption_key_params: dto.key_encryption_key_params,
418        wrapped_dek: dto.wrapped_dek,
419        display_name: dto.display_name,
420    };
421
422    let client = async_client(ClientOptions::default())?;
423    let url = format!("{}/api/user/register", server_url.trim_end_matches('/'));
424
425    let resp_res = client.inner.post(&url).json(&req_body).send().await;
426
427    let resp = match resp_res {
428        Ok(r) => r,
429        Err(e) => {
430            log!(format!("register_on_server: network offline or error: {e}"));
431            return Ok(RemoteRegisterResult::Offline);
432        }
433    };
434
435    let status_code = resp.status().as_u16();
436    if status_code == 201 || resp.status().is_success() {
437        Ok(RemoteRegisterResult::Success)
438    } else if status_code == 409 {
439        Ok(RemoteRegisterResult::Conflict)
440    } else {
441        log!(format!(
442            "register_on_server: server returned error status: {status_code}"
443        ));
444        Ok(RemoteRegisterResult::Offline)
445    }
446}