|
| 1 | +use libsql::{params, Builder}; |
| 2 | +use libsql_sys::{Cipher, EncryptionConfig}; |
| 3 | + |
| 4 | +#[tokio::test] |
| 5 | +#[cfg(feature = "encryption")] |
| 6 | +async fn test_encryption() { |
| 7 | + let tempdir = std::env::temp_dir(); |
| 8 | + let encrypted_path = tempdir.join("encrypted.db"); |
| 9 | + let base_path = tempdir.join("base.db"); |
| 10 | + |
| 11 | + // lets create an encrypted database |
| 12 | + { |
| 13 | + let mut db_builder = Builder::new_local(&encrypted_path); |
| 14 | + db_builder = db_builder.encryption_config(EncryptionConfig { |
| 15 | + cipher: Cipher::Aes256Cbc, |
| 16 | + encryption_key: "s3cR3t".into(), |
| 17 | + }); |
| 18 | + let db = db_builder.build().await.unwrap(); |
| 19 | + |
| 20 | + let conn = db.connect().unwrap(); |
| 21 | + conn.execute("CREATE TABLE IF NOT EXISTS messages (text TEXT)", ()) |
| 22 | + .await |
| 23 | + .unwrap(); |
| 24 | + let params = params!["the only winning move is not to play"]; |
| 25 | + conn.execute("INSERT INTO messages (text) VALUES (?)", params) |
| 26 | + .await |
| 27 | + .unwrap(); |
| 28 | + } |
| 29 | + |
| 30 | + // lets test encryption with ATTACH |
| 31 | + { |
| 32 | + let db = Builder::new_local(&base_path).build().await.unwrap(); |
| 33 | + let conn = db.connect().unwrap(); |
| 34 | + let attach_stmt = format!( |
| 35 | + "ATTACH DATABASE '{}' AS encrypted KEY 's3cR3t'", |
| 36 | + tempdir.join("encrypted.db").display() |
| 37 | + ); |
| 38 | + conn.execute(&attach_stmt, ()).await.unwrap(); |
| 39 | + let mut attached_results = conn |
| 40 | + .query("SELECT * FROM encrypted.messages", ()) |
| 41 | + .await |
| 42 | + .unwrap(); |
| 43 | + let row = attached_results.next().await.unwrap().unwrap(); |
| 44 | + let text: String = row.get(0).unwrap(); |
| 45 | + assert_eq!(text, "the only winning move is not to play"); |
| 46 | + } |
| 47 | + |
| 48 | + { |
| 49 | + let _ = std::fs::remove_file(&encrypted_path); |
| 50 | + let _ = std::fs::remove_file(&base_path); |
| 51 | + } |
| 52 | +} |
0 commit comments