ctb_io_webui/controllers/
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 synchronization and replication HTTP route handlers.
21
22use axum::http::HeaderMap;
23use axum::{
24    Json,
25    extract::{Path, State},
26    http::StatusCode,
27    response::IntoResponse,
28};
29use base64::Engine;
30use ctb_formats_hexdump::hex2bin;
31use ctb_utilities::{__ctb_ipc_ctx, __ctb_ipcb_get, ipcb};
32use serde::{Deserialize, Serialize};
33use std::collections::HashMap;
34use std::sync::{Mutex, OnceLock};
35use std::time::{Instant, SystemTime, UNIX_EPOCH};
36
37use crate::AppState;
38use crate::session_auth::AuthenticatedUser;
39use crate::utilities::feature;
40use ctb_utilities::blind_signatures::{
41    generate_server_key, server_evaluate, server_verify,
42};
43
44// --- In-memory Sync Session Storage ---
45
46pub struct SyncSession {
47    pub upload_allowance: usize,
48    pub expiry: Instant,
49}
50
51static SYNC_SESSIONS: OnceLock<Mutex<HashMap<String, SyncSession>>> =
52    OnceLock::new();
53
54fn sync_sessions() -> &'static Mutex<HashMap<String, SyncSession>> {
55    SYNC_SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
56}
57
58// Helper to extract bearer token
59fn get_bearer_token(headers: &HeaderMap) -> Result<String, StatusCode> {
60    let auth_header = headers
61        .get("Authorization")
62        .and_then(|h| h.to_str().ok())
63        .ok_or(StatusCode::UNAUTHORIZED)?;
64
65    let token = auth_header
66        .strip_prefix("Bearer ")
67        .ok_or(StatusCode::UNAUTHORIZED)?;
68
69    Ok(token.to_string())
70}
71
72// Helper to validate bearer session token
73fn validate_sync_session(session_id: &str) -> Result<usize, StatusCode> {
74    let mut sessions = sync_sessions()
75        .lock()
76        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
77    let now = Instant::now();
78
79    // Evict expired
80    sessions.retain(|_, s| s.expiry > now);
81
82    if let Some(session) = sessions.get(session_id) {
83        Ok(session.upload_allowance)
84    } else {
85        Err(StatusCode::UNAUTHORIZED)
86    }
87}
88
89// Helper to deduct uploaded bytes from sync session allowance
90fn deduct_allowance(
91    session_id: &str,
92    bytes_count: usize,
93) -> Result<(), StatusCode> {
94    let mut sessions = sync_sessions()
95        .lock()
96        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
97    if let Some(session) = sessions.get_mut(session_id) {
98        if session.upload_allowance >= bytes_count {
99            session.upload_allowance =
100                session.upload_allowance.saturating_sub(bytes_count);
101            Ok(())
102        } else {
103            Err(StatusCode::PAYLOAD_TOO_LARGE)
104        }
105    } else {
106        Err(StatusCode::UNAUTHORIZED)
107    }
108}
109
110// --- Key Management ---
111
112fn get_or_create_voprf_key() -> Result<Vec<u8>, StatusCode> {
113    if let Ok(Some(key)) = ipcb!(storage).get_voprf_key_b() {
114        return Ok(key);
115    }
116    let key =
117        generate_server_key().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
118    let _ = ipcb!(storage).save_voprf_key_b(key.clone());
119    Ok(key)
120}
121
122// --- API Request/Response DTOs ---
123
124#[derive(Serialize, Deserialize, Debug, Clone)]
125pub struct TokenIssueRequest {
126    pub blinded_elements: Vec<String>, // Base64 encoded blinded RistrettoPoints
127}
128
129#[derive(Serialize, Deserialize, Debug, Clone)]
130pub struct TokenIssueResponse {
131    pub evaluations: Vec<String>, // Base64 encoded signed elements
132}
133
134#[derive(Serialize, Deserialize, Debug, Clone)]
135pub struct SyncStartRequest {
136    pub serial_hex: String,
137    pub token_tag_hex: String,
138}
139
140#[derive(Serialize, Deserialize, Debug, Clone)]
141pub struct SyncStartResponse {
142    pub session_id: String,
143    pub upload_allowance: usize,
144}
145
146#[derive(Serialize, Deserialize, Debug, Clone)]
147pub struct ReserveIdsRequest {
148    pub graph_id: u128,
149}
150
151#[derive(Serialize, Deserialize, Debug, Clone)]
152pub struct ReserveIdsResponse {
153    pub start_id: u64,
154    pub end_id: u64,
155}
156
157#[derive(Serialize, Deserialize, Debug, Clone)]
158pub struct UploadChunkRequest {
159    pub chunk_hash: String,
160    pub chunk_data_hex: String,
161}
162
163// --- Handlers ---
164
165/// POST /api/tokens/issue (Authenticated)
166/// Signs a batch of blinded elements for a subscribed user.
167pub async fn post_tokens_issue(
168    State(_state): State<AppState>,
169    user: AuthenticatedUser,
170    Json(payload): Json<TokenIssueRequest>,
171) -> Result<impl IntoResponse, StatusCode> {
172    if !feature("login") || !feature("provide_sync_server") {
173        return Err(StatusCode::NOT_FOUND);
174    }
175
176    let u = user.user.lock().await;
177    let user_id = u.local_id();
178
179    // 1. Verify subscription
180    // Reason for fallback: system clock time prior to UNIX epoch defaults timestamp to 0 seconds
181    let now = SystemTime::now()
182        .duration_since(UNIX_EPOCH)
183        .unwrap_or_default()
184        .as_secs();
185    let mut dto = ipcb!(storage)
186        .get_user_by_id_b(user_id)
187        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
188        .ok_or(StatusCode::NOT_FOUND)?;
189
190    // Reason for fallback: user DTO missing subscription_expiry defaults expiry to 0 timestamp
191    let expiry = dto.subscription_expiry.unwrap_or(0);
192    if expiry <= now {
193        return Err(StatusCode::PAYMENT_REQUIRED);
194    }
195
196    // 2. Verify quota
197    // Reason for fallback: user DTO missing token_quota defaults quota to 0
198    let quota = dto.token_quota.unwrap_or(0);
199    let count = payload.blinded_elements.len();
200    if count == 0 {
201        return Err(StatusCode::BAD_REQUEST);
202    }
203    // Reason for fallback: blinded elements vector length u64 conversion overflow defaults count to 0
204    let count_u64 = u64::try_from(count).unwrap_or(0);
205    if quota < count_u64 {
206        return Err(StatusCode::FORBIDDEN);
207    }
208
209    // 3. Sign blinded elements
210    let server_key = get_or_create_voprf_key()?;
211    let mut evaluations = Vec::with_capacity(count);
212
213    for blinded_b64 in payload.blinded_elements {
214        let blinded_bytes = base64::engine::general_purpose::STANDARD
215            .decode(blinded_b64)
216            .map_err(|_| StatusCode::BAD_REQUEST)?;
217
218        let signed_bytes = server_evaluate(&server_key, &blinded_bytes)
219            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
220
221        evaluations.push(
222            base64::engine::general_purpose::STANDARD.encode(signed_bytes),
223        );
224    }
225
226    // 4. Update quota
227    dto.token_quota = Some(quota.saturating_sub(count_u64));
228    ipcb!(storage)
229        .update_user_b(dto)
230        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
231
232    Ok(Json(TokenIssueResponse { evaluations }))
233}
234
235/// POST /api/sync/start (Anonymous / Token-Spent)
236/// Validates a single-use blind token and opens a sync session.
237pub async fn post_sync_start(
238    State(_state): State<AppState>,
239    Json(payload): Json<SyncStartRequest>,
240) -> Result<impl IntoResponse, StatusCode> {
241    if !feature("provide_sync_server") {
242        return Err(StatusCode::NOT_FOUND);
243    }
244
245    let serial =
246        hex2bin(&payload.serial_hex).map_err(|_| StatusCode::BAD_REQUEST)?;
247    let tag =
248        hex2bin(&payload.token_tag_hex).map_err(|_| StatusCode::BAD_REQUEST)?;
249
250    // 1. Check double-spend
251    if ipcb!(storage)
252        .is_token_spent_b(&payload.serial_hex)
253        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
254    {
255        return Err(StatusCode::CONFLICT);
256    }
257
258    // 2. Verify token signature
259    let server_key = get_or_create_voprf_key()?;
260    let is_valid = server_verify(&server_key, &serial, &tag)
261        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
262
263    if !is_valid {
264        return Err(StatusCode::UNAUTHORIZED);
265    }
266
267    // 3. Mark token as spent
268    ipcb!(storage)
269        .spend_token_b(&payload.serial_hex)
270        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
271
272    // 4. Create sync session (15 mins lifespan, 1MB upload allowance)
273    let session_id = crate::Uuid::new_v4().to_string();
274    {
275        let mut sessions = sync_sessions()
276            .lock()
277            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
278        sessions.insert(
279            session_id.clone(),
280            SyncSession {
281                upload_allowance: 1024 * 1024, // 1MB
282                expiry: Instant::now()
283                    .checked_add(std::time::Duration::from_secs(15 * 60))
284                    // Reason for fallback: Instant addition overflow falls back to current Instant
285                    .unwrap_or_else(Instant::now),
286            },
287        );
288    }
289
290    Ok(Json(SyncStartResponse {
291        session_id,
292        upload_allowance: 1024 * 1024,
293    }))
294}
295
296/// POST /api/sync/reserve-ids (Anonymous / Session-based)
297/// Reserves a range of 10,000 IDs for a graph.
298pub async fn post_reserve_ids(
299    State(_state): State<AppState>,
300    headers: HeaderMap,
301    Json(payload): Json<ReserveIdsRequest>,
302) -> Result<impl IntoResponse, StatusCode> {
303    if !feature("provide_sync_server") {
304        return Err(StatusCode::NOT_FOUND);
305    }
306
307    let session_id = get_bearer_token(&headers)?;
308    let _ = validate_sync_session(&session_id)?;
309
310    let start_id = ipcb!(storage)
311        .allocate_next_remote_range_b(payload.graph_id)
312        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
313
314    let end_id = start_id.saturating_add(10000).saturating_sub(1);
315
316    Ok(Json(ReserveIdsResponse { start_id, end_id }))
317}
318
319/// POST /api/sync/chunks (Anonymous / Session-based)
320/// Uploads an encrypted chunk.
321pub async fn post_upload_chunks(
322    State(_state): State<AppState>,
323    headers: HeaderMap,
324    Json(payload): Json<UploadChunkRequest>,
325) -> Result<impl IntoResponse, StatusCode> {
326    if !feature("provide_sync_server") {
327        return Err(StatusCode::NOT_FOUND);
328    }
329
330    let session_id = get_bearer_token(&headers)?;
331    let _ = validate_sync_session(&session_id)?;
332
333    let chunk_data = hex2bin(&payload.chunk_data_hex)
334        .map_err(|_| StatusCode::BAD_REQUEST)?;
335    let size = chunk_data.len();
336
337    // Enforce quota deduction
338    deduct_allowance(&session_id, size)?;
339
340    // Save chunk to database with expiry timestamp (2 months from now)
341    // Reason for fallback: system clock time prior to UNIX epoch defaults timestamp to 0 seconds
342    let now = SystemTime::now()
343        .duration_since(UNIX_EPOCH)
344        .unwrap_or_default()
345        .as_secs();
346    let expiry = now.saturating_add(60 * 24 * 60 * 60); // 60 days
347    ipcb!(storage)
348        .save_sync_chunk_b(&payload.chunk_hash, chunk_data, expiry)
349        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
350
351    Ok(StatusCode::OK)
352}
353
354/// GET /api/sync/chunks/{hash} (Anonymous / Session-based)
355/// Downloads an encrypted chunk.
356pub async fn get_download_chunks(
357    State(_state): State<AppState>,
358    headers: HeaderMap,
359    Path(chunk_hash): Path<String>,
360) -> Result<impl IntoResponse, StatusCode> {
361    if !feature("provide_sync_server") {
362        return Err(StatusCode::NOT_FOUND);
363    }
364
365    let session_id = get_bearer_token(&headers)?;
366    let _ = validate_sync_session(&session_id)?;
367
368    if let Ok(Some(chunk_data)) = ipcb!(storage).get_sync_chunk_b(&chunk_hash) {
369        Ok(chunk_data)
370    } else {
371        Err(StatusCode::NOT_FOUND)
372    }
373}
374
375#[cfg(test)]
376#[allow(
377    clippy::panic,
378    clippy::expect_used,
379    clippy::unwrap_used,
380    clippy::unwrap_in_result,
381    clippy::panic_in_result_fn,
382    clippy::indexing_slicing,
383    clippy::arithmetic_side_effects,
384    reason = "Standard repository test boilerplate"
385)]
386mod tests {
387    use super::*;
388    use crate::bin2hex;
389    use crate::test_helpers::TestApp;
390    use axum::http::Method;
391    use base64::Engine;
392    use ctb_utilities::blind_signatures::{client_blind, client_finalize};
393    use serde_json::json;
394
395    #[crate::ctb_test("tokio")]
396    async fn test_sync_controller_endpoints() {
397        use crate::json::maybe_value::MaybeValue;
398        use crate::pc_settings::PcSettings;
399
400        let old_settings = PcSettings::load().unwrap_or_default();
401        struct SettingsRestoreGuard(PcSettings);
402        impl Drop for SettingsRestoreGuard {
403            fn drop(&mut self) {
404                self.0.save().unwrap();
405            }
406        }
407        let _guard = SettingsRestoreGuard(old_settings.clone());
408
409        let mut settings = old_settings.clone();
410        settings.feature_provide_sync_server = MaybeValue::Value(true);
411        settings.save().unwrap();
412
413        let app = TestApp::default();
414
415        let mut rng = rand::rng();
416        let graph_id =
417            (rand::RngCore::next_u32(&mut rng) % 100000).saturating_add(1000);
418
419        // 1. Register & Login test user
420        let (cookie, _lock) = app.register_and_login("testuser").await.unwrap();
421
422        // 2. Fetch user ID from database
423        let user_id = ipcb!(storage)
424            .get_user_by_name_b("testuser")
425            .unwrap()
426            .expect("User not found")
427            .id;
428
429        // 3. Post to /home/subscribe to subscribe the user
430        let (status, _body) = app
431            .request(
432                Method::POST,
433                "/home/subscribe",
434                None,
435                Some(&cookie),
436                None,
437                Some(&json!({
438                    "_payment_type": "card",
439                })),
440            )
441            .await;
442        assert!(
443            status == StatusCode::OK
444                || status == StatusCode::FOUND
445                || status == StatusCode::SEE_OTHER
446        );
447
448        // Verify quota is updated
449        let quota = ipcb!(storage)
450            .get_user_by_id_b(user_id)
451            .unwrap()
452            .unwrap()
453            .token_quota
454            .unwrap_or(0);
455        assert_eq!(quota, 100);
456
457        // 4. Client blinds a VOPRF token
458        let mut serial = [0u8; 32];
459        rand::RngCore::fill_bytes(&mut rand::rng(), &mut serial);
460        let (blinded_element, client_state) = client_blind(&serial).unwrap();
461        let blinded_b64 =
462            base64::engine::general_purpose::STANDARD.encode(blinded_element);
463
464        // 5. POST to /api/tokens/issue to get the token signed
465        let mut json_headers = HeaderMap::new();
466        json_headers
467            .insert("Content-Type", "application/json".parse().unwrap());
468
469        let (status, body) = app
470            .request(
471                Method::POST,
472                "/api/tokens/issue",
473                Some(json_headers.clone()),
474                Some(&cookie),
475                Some(
476                    serde_json::to_vec(&json!({
477                        "blinded_elements": vec![blinded_b64],
478                    }))
479                    .unwrap(),
480                ),
481                None::<&()>,
482            )
483            .await;
484        assert_eq!(status, StatusCode::OK);
485
486        let resp: TokenIssueResponse = serde_json::from_str(&body).unwrap();
487        assert_eq!(resp.evaluations.len(), 1);
488
489        // Verify quota decremented
490        let new_quota = ipcb!(storage)
491            .get_user_by_id_b(user_id)
492            .unwrap()
493            .unwrap()
494            .token_quota
495            .unwrap_or(0);
496        assert_eq!(new_quota, 99);
497
498        // 6. Client unblinds the evaluation
499        let eval_bytes = base64::engine::general_purpose::STANDARD
500            .decode(&resp.evaluations[0])
501            .unwrap();
502        let token_tag =
503            client_finalize(&serial, &client_state, &eval_bytes).unwrap();
504
505        // 7. POST /api/sync/start (anonymous, token-spent)
506        let serial_hex = bin2hex(serial);
507        let token_tag_hex = bin2hex(token_tag);
508
509        let (status, body) = app
510            .request(
511                Method::POST,
512                "/api/sync/start",
513                Some(json_headers.clone()),
514                None,
515                Some(
516                    serde_json::to_vec(&json!({
517                        "serial_hex": serial_hex,
518                        "token_tag_hex": token_tag_hex,
519                    }))
520                    .unwrap(),
521                ),
522                None::<&()>,
523            )
524            .await;
525        assert_eq!(status, StatusCode::OK);
526
527        let start_resp: SyncStartResponse =
528            serde_json::from_str(&body).unwrap();
529        let session_id = start_resp.session_id;
530
531        // Double spend should fail
532        let (status, _) = app
533            .request(
534                Method::POST,
535                "/api/sync/start",
536                Some(json_headers.clone()),
537                None,
538                Some(
539                    serde_json::to_vec(&json!({
540                        "serial_hex": serial_hex,
541                        "token_tag_hex": token_tag_hex,
542                    }))
543                    .unwrap(),
544                ),
545                None::<&()>,
546            )
547            .await;
548        assert_eq!(status, StatusCode::CONFLICT);
549
550        // 8. POST /api/sync/reserve-ids using the bearer token
551        let mut headers = HeaderMap::new();
552        headers.insert(
553            "Authorization",
554            format!("Bearer {session_id}").parse().unwrap(),
555        );
556        headers.insert("Content-Type", "application/json".parse().unwrap());
557
558        let (status, body) = app
559            .request(
560                Method::POST,
561                "/api/sync/reserve-ids",
562                Some(headers.clone()),
563                None,
564                Some(
565                    serde_json::to_vec(&json!({
566                        "graph_id": graph_id,
567                    }))
568                    .unwrap(),
569                ),
570                None::<&()>,
571            )
572            .await;
573        assert_eq!(status, StatusCode::OK);
574
575        let ids_resp: ReserveIdsResponse = serde_json::from_str(&body).unwrap();
576        assert_eq!(ids_resp.start_id, 1);
577        assert_eq!(ids_resp.end_id, 10000);
578
579        // 9. POST /api/sync/chunks
580        let chunk_data = vec![65u8; 100]; // string "A"s
581        let chunk_data_hex = bin2hex(&chunk_data);
582
583        let (status, _) = app
584            .request(
585                Method::POST,
586                "/api/sync/chunks",
587                Some(headers.clone()),
588                None,
589                Some(
590                    serde_json::to_vec(&json!({
591                        "chunk_hash": "testchunk123",
592                        "chunk_data_hex": chunk_data_hex,
593                    }))
594                    .unwrap(),
595                ),
596                None::<&()>,
597            )
598            .await;
599        assert_eq!(status, StatusCode::OK);
600
601        // 10. GET /api/sync/chunks/testchunk123
602        let (status, body) = app
603            .request(
604                Method::GET,
605                "/api/sync/chunks/testchunk123",
606                Some(headers.clone()),
607                None,
608                None,
609                None::<&()>,
610            )
611            .await;
612        assert_eq!(status, StatusCode::OK);
613        assert_eq!(body, String::from_utf8(chunk_data).unwrap());
614    }
615
616    #[crate::ctb_test("tokio")]
617    async fn disabled_sync_routes_return_not_found() {
618        use crate::json::maybe_value::MaybeValue;
619        use crate::pc_settings::PcSettings;
620
621        let old_settings = PcSettings::load().unwrap_or_default();
622        struct SettingsRestoreGuard(PcSettings);
623        impl Drop for SettingsRestoreGuard {
624            fn drop(&mut self) {
625                self.0.save().unwrap();
626            }
627        }
628        let _guard = SettingsRestoreGuard(old_settings.clone());
629
630        let mut settings = old_settings.clone();
631        settings.feature_provide_sync_server = MaybeValue::Value(false);
632        settings.save().unwrap();
633
634        let app = TestApp::new();
635        let mut headers = HeaderMap::new();
636        headers.insert("Content-Type", "application/json".parse().unwrap());
637
638        // 1. POST /api/sync/start
639        let (status, _) = app
640            .request(
641                Method::POST,
642                "/api/sync/start",
643                Some(headers.clone()),
644                None,
645                Some(
646                    serde_json::to_vec(&json!({
647                        "serial_hex": "00",
648                        "token_tag_hex": "00",
649                    }))
650                    .unwrap(),
651                ),
652                None::<&()>,
653            )
654            .await;
655        assert_eq!(status, StatusCode::NOT_FOUND);
656
657        // 2. POST /api/sync/reserve-ids
658        let (status, _) = app
659            .request(
660                Method::POST,
661                "/api/sync/reserve-ids",
662                Some(headers.clone()),
663                None,
664                Some(
665                    serde_json::to_vec(&json!({
666                        "graph_id": 123u128,
667                    }))
668                    .unwrap(),
669                ),
670                None::<&()>,
671            )
672            .await;
673        assert_eq!(status, StatusCode::NOT_FOUND);
674
675        // 3. POST /api/sync/chunks
676        let (status, _) = app
677            .request(
678                Method::POST,
679                "/api/sync/chunks",
680                Some(headers.clone()),
681                None,
682                Some(
683                    serde_json::to_vec(&json!({
684                        "chunk_hash": "test",
685                        "chunk_data_hex": "00",
686                    }))
687                    .unwrap(),
688                ),
689                None::<&()>,
690            )
691            .await;
692        assert_eq!(status, StatusCode::NOT_FOUND);
693
694        // 4. GET /api/sync/chunks/test
695        let (status, _) = app
696            .request(
697                Method::GET,
698                "/api/sync/chunks/test",
699                None,
700                None,
701                None,
702                None::<&()>,
703            )
704            .await;
705        assert_eq!(status, StatusCode::NOT_FOUND);
706    }
707}