solo-storage 0.11.5

Solo: SQLite + SQLCipher persistence layer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// SPDX-License-Identifier: Apache-2.0

//! Per-tenant SQLCipher backup + restore (v0.8.0 P6).
//!
//! These build on the existing `crate::backup` online-backup primitive
//! (which uses SQLite's `Backup::run_to_completion`) but operate on a
//! whole tenant + emit admin-audit rows. The CLI / HTTP front-ends
//! drive these — daemon-side hot backup uses the writer-actor's
//! `WriteCommand::Backup` path, not this one.
//!
//! ## Backup
//!
//! `backup_tenant` writes
//! `<out>/.solo-backup.<tenant>.<RFC3339-ts>.db` using the SQLite
//! online backup API (page-level snapshot, safe against an active
//! writer). On success the destination file is encrypted with the same
//! key as the source. Verifies the output by re-opening it with the
//! same key and running `PRAGMA integrity_check`.
//!
//! ## Restore
//!
//! `restore_tenant` opens the supplied path with the destination
//! tenant's key — a wrong key fails immediately with a clear error
//! (rather than a corrupt restore). Refuses to overwrite an existing
//! tenant DB unless `force == true`. Performs an atomic
//! write-and-rename to swap the file under the destination path.

use std::path::{Path, PathBuf};

use rusqlite::Connection;
use solo_core::{Error, Result, TenantId};

use crate::audit::{AuditOperation, AuditResult, insert_audit_admin_row};
use crate::backup::backup_database;
use crate::init::open_sqlcipher;
use crate::key_material::KeyMaterial;

/// Outcome of `backup_tenant`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackupReport {
    /// Final path the backup file was written to.
    pub path: PathBuf,
    /// Bytes written to that path.
    pub bytes_written: u64,
    /// Did `PRAGMA integrity_check` against the backup file return
    /// `'ok'`? Always `true` on `Ok` returns — a `false` here would
    /// have been surfaced as `Err`. Field is kept for callers that
    /// want to log it explicitly.
    pub integrity_ok: bool,
    /// `audit_id` of the row written to
    /// `tenants_index.db::audit_events_admin` (`operation='tenant.backup'`).
    pub audit_admin_row_id: i64,
}

/// Outcome of `restore_tenant`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestoreReport {
    /// Path the restore was sourced from.
    pub from: PathBuf,
    /// Bytes copied into the destination.
    pub bytes_restored: u64,
    /// `audit_id` of the row written to
    /// `tenants_index.db::audit_events_admin` (`operation='tenant.restore'`).
    pub audit_admin_row_id: i64,
}

/// Online-encrypted backup of one tenant's SQLCipher DB.
///
/// Returns the absolute path of the written file, the bytes written,
/// and the admin-audit row id. The output is `<out>/.solo-backup.<tenant>.<ts>.db`
/// where `<ts>` is `chrono::Utc::now().format("%Y%m%dT%H%M%SZ")` (an
/// RFC3339-ish form safe for filesystem paths on every OS).
///
/// `out` must be an existing directory. Errors with `Error::Storage`
/// if it isn't.
pub fn backup_tenant(
    tenant_id: &TenantId,
    db_path: &Path,
    out: &Path,
    key: &KeyMaterial,
    data_dir: &Path,
) -> Result<BackupReport> {
    if !out.is_dir() {
        return Err(Error::invalid_input(format!(
            "backup output directory does not exist: {}",
            out.display()
        )));
    }
    if !db_path.is_file() {
        return Err(Error::not_found(format!(
            "tenant DB to back up not found: {}",
            db_path.display()
        )));
    }

    let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
    let filename = format!(".solo-backup.{tenant_id}.{stamp}.db");
    let target = out.join(&filename);

    // Defense in depth: refuse to write the backup over the source.
    // `backup_database` enforces this internally too, but doing the
    // check up-front gives the operator a cleaner error message before
    // any I/O.
    if crate::backup::paths_refer_to_same_file(db_path, &target) {
        return Err(Error::invalid_input(format!(
            "backup target {} resolves to the source DB; refusing",
            target.display()
        )));
    }
    // Refuse to overwrite. `--force`-style overwrite is the caller's
    // problem (the CLI subcommand asks the operator before passing a
    // path that already exists).
    if target.exists() {
        return Err(Error::conflict(format!(
            "backup target {} already exists; choose a different out dir or remove the file first",
            target.display()
        )));
    }

    backup_database(db_path, &target, key)?;

    // Verify: open the backup with the source's key + integrity_check.
    let verify_conn = open_sqlcipher(&target, key)?;
    verify_integrity(&verify_conn).inspect_err(|_e| {
        // Drop the corrupt backup file so the operator isn't tempted
        // to restore from it later. Best-effort.
        let _ = std::fs::remove_file(&target);
    })?;
    drop(verify_conn);

    let bytes_written = std::fs::metadata(&target)
        .map_err(|e| Error::storage(format!("stat backup file {}: {e}", target.display())))?
        .len();

    // Admin-audit emit to tenants_index.db::audit_events_admin.
    let now_ms = chrono::Utc::now().timestamp_millis();
    let admin_path = data_dir.join(crate::tenants::TENANTS_INDEX_FILENAME);
    let admin_conn = open_sqlcipher(&admin_path, key)?;
    let details = serde_json::json!({
        "path": target.display().to_string(),
        "bytes": bytes_written,
    });
    let audit_admin_row_id = insert_audit_admin_row(
        &admin_conn,
        now_ms,
        None,
        AuditOperation::TenantBackup,
        Some(tenant_id.as_str()),
        AuditResult::Ok,
        Some(&details),
    )?;

    Ok(BackupReport {
        path: target,
        bytes_written,
        integrity_ok: true,
        audit_admin_row_id,
    })
}

/// Restore one tenant's SQLCipher DB from a backup file produced by
/// `backup_tenant` (or any other SQLCipher backup encrypted with the
/// destination tenant's key).
///
/// `dest_db_path` is the live path that the tenant DB resolves to
/// inside the data dir. On success it's overwritten atomically (write
/// to `<dest>.new`, fsync, rename). On wrong-key / integrity failure
/// the destination is left untouched.
///
/// `force == true` allows overwriting an existing destination file.
/// `force == false` refuses with `Error::Conflict`.
pub fn restore_tenant(
    tenant_id: &TenantId,
    from: &Path,
    dest_db_path: &Path,
    key: &KeyMaterial,
    data_dir: &Path,
    force: bool,
) -> Result<RestoreReport> {
    if !from.is_file() {
        return Err(Error::not_found(format!(
            "restore source not found: {}",
            from.display()
        )));
    }

    // Key check: open the source with the destination tenant's key.
    // `open_sqlcipher`'s `PRAGMA journal_mode = wal` forces decryption
    // so a wrong key surfaces here, BEFORE any swap.
    let src_conn = open_sqlcipher(from, key).map_err(|_| {
        Error::invalid_input(format!(
            "restore: source {} fails to decrypt under the destination tenant's key; \
             refusing to restore",
            from.display()
        ))
    })?;
    verify_integrity(&src_conn)?;
    drop(src_conn);

    if dest_db_path.exists() && !force {
        return Err(Error::conflict(format!(
            "destination {} exists; pass --confirm to overwrite",
            dest_db_path.display()
        )));
    }

    // Write to `<dest>.new`, fsync, rename. SQLite's online backup
    // gives us a clean point-in-time copy regardless of source state
    // (page-level snapshot). For the restore swap we just want
    // atomicity of the file replacement.
    let staging = staging_path(dest_db_path);
    if staging.exists() {
        std::fs::remove_file(&staging).map_err(|e| {
            Error::storage(format!(
                "remove pre-existing staging file {}: {e}",
                staging.display()
            ))
        })?;
    }
    std::fs::copy(from, &staging).map_err(|e| {
        Error::storage(format!(
            "copy {}{}: {e}",
            from.display(),
            staging.display()
        ))
    })?;
    // fsync the staging file so it's durable on disk before we swap.
    // On Windows, `sync_all` requires the file be opened with write
    // access (FILE_GENERIC_WRITE for FlushFileBuffers). Open
    // `read=true, write=true` rather than `append=true` so we don't
    // mutate the staging contents — `sync_all` only flushes the
    // existing buffer.
    {
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&staging)
            .map_err(|e| Error::storage(format!("open staging for fsync: {e}")))?;
        f.sync_all()
            .map_err(|e| Error::storage(format!("fsync staging: {e}")))?;
    }

    // The atomic-rename. On Windows the `rename` over an existing
    // file would fail; remove the existing destination first.
    #[cfg(windows)]
    {
        if dest_db_path.exists() {
            std::fs::remove_file(dest_db_path).map_err(|e| {
                Error::storage(format!(
                    "remove dest {} before swap: {e}",
                    dest_db_path.display()
                ))
            })?;
        }
    }
    std::fs::rename(&staging, dest_db_path).map_err(|e| {
        Error::storage(format!(
            "rename {}{}: {e}",
            staging.display(),
            dest_db_path.display()
        ))
    })?;

    let bytes_restored = std::fs::metadata(dest_db_path)
        .map_err(|e| Error::storage(format!("stat dest after restore: {e}")))?
        .len();

    // Admin-audit emit.
    let now_ms = chrono::Utc::now().timestamp_millis();
    let admin_path = data_dir.join(crate::tenants::TENANTS_INDEX_FILENAME);
    let admin_conn = open_sqlcipher(&admin_path, key)?;
    let details = serde_json::json!({
        "from": from.display().to_string(),
        "bytes_restored": bytes_restored,
    });
    let audit_admin_row_id = insert_audit_admin_row(
        &admin_conn,
        now_ms,
        None,
        AuditOperation::TenantRestore,
        Some(tenant_id.as_str()),
        AuditResult::Ok,
        Some(&details),
    )?;

    Ok(RestoreReport {
        from: from.to_path_buf(),
        bytes_restored,
        audit_admin_row_id,
    })
}

/// Run `PRAGMA integrity_check` and bubble a clean error if it doesn't
/// return exactly `'ok'`.
fn verify_integrity(conn: &Connection) -> Result<()> {
    let result: String = conn
        .query_row("PRAGMA integrity_check", [], |r| r.get(0))
        .map_err(|e| Error::storage(format!("PRAGMA integrity_check: {e}")))?;
    if result != "ok" {
        return Err(Error::storage(format!(
            "integrity_check failed: {result}"
        )));
    }
    Ok(())
}

/// Build the `<dest>.new` staging path. Lives in the same parent dir
/// so the final `rename` is same-filesystem (atomic).
fn staging_path(dest: &Path) -> PathBuf {
    let mut fname = dest
        .file_name()
        .map(|s| s.to_os_string())
        .unwrap_or_default();
    fname.push(".new");
    match dest.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.join(fname),
        _ => PathBuf::from(fname),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn staging_path_is_sibling_of_dest() {
        use std::path::PathBuf;
        let dest = PathBuf::from("C:/data/tenants/default.db");
        let staged = staging_path(&dest);
        let staged_str = staged.to_string_lossy().replace('\\', "/");
        assert!(
            staged_str.ends_with("default.db.new"),
            "got `{}`",
            staged_str
        );
        // Same parent.
        assert_eq!(staged.parent(), dest.parent());
    }

    #[test]
    fn verify_integrity_accepts_fresh_in_memory_db() {
        let conn = Connection::open_in_memory().unwrap();
        // PRAGMA integrity_check on an empty DB returns 'ok'.
        verify_integrity(&conn).expect("empty DB must be integrity-ok");
    }

    #[test]
    fn backup_restore_round_trip_preserves_user_rows() {
        use crate::init::{InitParams, init};
        use rusqlite::params;
        use zeroize::Zeroizing;

        let tmp = tempfile::TempDir::new().unwrap();
        let data_dir = tmp.path().join("data");
        let out_dir = tmp.path().join("backups");
        std::fs::create_dir_all(&out_dir).unwrap();

        let pass = "round-trip backup test";
        let outcome = init(InitParams {
            data_dir: data_dir.clone(),
            passphrase: Zeroizing::new(pass.into()),
            force: false,
            embedder: crate::init::default_embedder(),
        })
        .unwrap();
        let cfg = crate::config::SoloConfig::read(&outcome.config_path).unwrap();
        let salt = cfg.salt_bytes().unwrap();
        let key = KeyMaterial::derive(pass, &salt).unwrap();

        // Seed an episode so we can verify the round-trip.
        {
            let conn = crate::init::open_sqlcipher(&outcome.db_path, &key).unwrap();
            let now = chrono::Utc::now().timestamp_millis();
            conn.execute(
                "INSERT INTO episodes (
                    memory_id, ts_ms, source_type, content,
                    encoding_context_json, confidence, strength, salience,
                    tier, created_at_ms, updated_at_ms
                 ) VALUES (?, ?, 'user_message', 'sentinel', '{}', 0.9, 0.5, 0.5,
                           'hot', ?, ?)",
                params!["01900000-0000-7000-8000-000000000001", now, now, now],
            )
            .unwrap();
        }

        let tenant_id = TenantId::default_tenant();
        let report = backup_tenant(
            &tenant_id,
            &outcome.db_path,
            &out_dir,
            &key,
            &data_dir,
        )
        .expect("backup_tenant");
        assert!(report.integrity_ok);
        assert!(report.path.is_file());

        // Take a hash of the seeded row's content before destruction so
        // we can verify the round-trip preserves *data*, not bytes
        // (SQLCipher salt/IV differ across freshly-written files).
        let hash_before: String = {
            let conn = crate::init::open_sqlcipher(&outcome.db_path, &key).unwrap();
            conn.query_row(
                "SELECT content FROM episodes WHERE memory_id = ?",
                params!["01900000-0000-7000-8000-000000000001"],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(hash_before, "sentinel");

        // Destroy the source.
        std::fs::remove_file(&outcome.db_path).unwrap();
        // Restore.
        let restore_report = restore_tenant(
            &tenant_id,
            &report.path,
            &outcome.db_path,
            &key,
            &data_dir,
            false,
        )
        .expect("restore_tenant");
        assert!(restore_report.bytes_restored > 0);

        // Round-trip verification.
        let hash_after: String = {
            let conn = crate::init::open_sqlcipher(&outcome.db_path, &key).unwrap();
            conn.query_row(
                "SELECT content FROM episodes WHERE memory_id = ?",
                params!["01900000-0000-7000-8000-000000000001"],
                |r| r.get(0),
            )
            .unwrap()
        };
        assert_eq!(hash_after, hash_before);

        // Admin audit rows: one for backup, one for restore.
        let admin = crate::init::open_sqlcipher(
            &data_dir.join(crate::tenants::TENANTS_INDEX_FILENAME),
            &key,
        )
        .unwrap();
        let n_backup: i64 = admin
            .query_row(
                "SELECT COUNT(*) FROM audit_events_admin WHERE operation = 'tenant.backup'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        let n_restore: i64 = admin
            .query_row(
                "SELECT COUNT(*) FROM audit_events_admin WHERE operation = 'tenant.restore'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(n_backup, 1);
        assert_eq!(n_restore, 1);
    }

    #[test]
    fn restore_refuses_wrong_key() {
        use crate::init::{InitParams, init};
        use zeroize::Zeroizing;

        let tmp = tempfile::TempDir::new().unwrap();
        let data_dir = tmp.path().join("data");
        let out_dir = tmp.path().join("backups");
        std::fs::create_dir_all(&out_dir).unwrap();

        // Init under one passphrase.
        let pass = "right passphrase";
        let outcome = init(InitParams {
            data_dir: data_dir.clone(),
            passphrase: Zeroizing::new(pass.into()),
            force: false,
            embedder: crate::init::default_embedder(),
        })
        .unwrap();
        let cfg = crate::config::SoloConfig::read(&outcome.config_path).unwrap();
        let salt = cfg.salt_bytes().unwrap();
        let key = KeyMaterial::derive(pass, &salt).unwrap();

        // Backup with the real key.
        let tenant_id = TenantId::default_tenant();
        let report = backup_tenant(
            &tenant_id,
            &outcome.db_path,
            &out_dir,
            &key,
            &data_dir,
        )
        .unwrap();

        // Try to restore with a wrong key.
        let wrong_key = KeyMaterial::derive("WRONG PASSPHRASE", &salt).unwrap();
        let err = restore_tenant(
            &tenant_id,
            &report.path,
            &outcome.db_path,
            &wrong_key,
            &data_dir,
            true,
        )
        .expect_err("wrong key must refuse");
        let msg = err.to_string();
        assert!(
            msg.contains("fails to decrypt") || msg.contains("key"),
            "got `{msg}`"
        );
    }

    #[test]
    fn restore_refuses_existing_destination_without_confirm() {
        use crate::init::{InitParams, init};
        use zeroize::Zeroizing;

        let tmp = tempfile::TempDir::new().unwrap();
        let data_dir = tmp.path().join("data");
        let out_dir = tmp.path().join("backups");
        std::fs::create_dir_all(&out_dir).unwrap();

        let pass = "existing-dest test";
        let outcome = init(InitParams {
            data_dir: data_dir.clone(),
            passphrase: Zeroizing::new(pass.into()),
            force: false,
            embedder: crate::init::default_embedder(),
        })
        .unwrap();
        let cfg = crate::config::SoloConfig::read(&outcome.config_path).unwrap();
        let salt = cfg.salt_bytes().unwrap();
        let key = KeyMaterial::derive(pass, &salt).unwrap();

        let tenant_id = TenantId::default_tenant();
        let report = backup_tenant(
            &tenant_id,
            &outcome.db_path,
            &out_dir,
            &key,
            &data_dir,
        )
        .unwrap();

        // Destination still exists (we didn't remove the source).
        let err = restore_tenant(
            &tenant_id,
            &report.path,
            &outcome.db_path,
            &key,
            &data_dir,
            false, // force=false
        )
        .expect_err("existing dest without confirm must refuse");
        let msg = err.to_string();
        assert!(msg.contains("destination") && msg.contains("exists"), "got `{msg}`");

        // With confirm=true it succeeds.
        let r = restore_tenant(
            &tenant_id,
            &report.path,
            &outcome.db_path,
            &key,
            &data_dir,
            true,
        )
        .expect("existing dest with confirm must succeed");
        assert!(r.bytes_restored > 0);
    }

    #[test]
    fn backup_to_missing_out_dir_errors_cleanly() {
        let tmp = tempfile::TempDir::new().unwrap();
        let data_dir = tmp.path().to_path_buf();
        let nonexistent = tmp.path().join("does-not-exist");
        let db_path = tmp.path().join("source.db");
        std::fs::write(&db_path, b"placeholder").unwrap();
        let tenant_id = TenantId::new("test").unwrap();
        let key = KeyMaterial::derive("p", &[0u8; 16]).unwrap();

        let err = backup_tenant(&tenant_id, &db_path, &nonexistent, &key, &data_dir)
            .expect_err("missing out dir must error");
        let msg = err.to_string();
        assert!(msg.contains("does not exist"), "got `{msg}`");
    }

    #[test]
    fn restore_refuses_missing_source() {
        let tmp = tempfile::TempDir::new().unwrap();
        let data_dir = tmp.path().to_path_buf();
        let from = tmp.path().join("does-not-exist.db");
        let dest = tmp.path().join("dest.db");
        let tenant_id = TenantId::new("test").unwrap();
        let key = KeyMaterial::derive("p", &[0u8; 16]).unwrap();

        let err = restore_tenant(&tenant_id, &from, &dest, &key, &data_dir, false)
            .expect_err("missing source must error");
        let msg = err.to_string();
        assert!(msg.contains("not found"), "got `{msg}`");
    }

}