-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathencryption.rs
More file actions
1534 lines (1361 loc) · 51.5 KB
/
encryption.rs
File metadata and controls
1534 lines (1361 loc) · 51.5 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::common::{
do_flush, run_query, run_query_on_row, ExecRows, TempDatabase, TempDatabaseBuilder,
};
use rand::{rng, RngCore};
use std::sync::Arc;
use turso_core::{
CipherMode, Database, DatabaseOpts, EncryptionKey, EncryptionOpts, OpenFlags, PlatformIO, Row,
IO,
};
const ENABLE_ENCRYPTION: bool = true;
fn run_non_4k_page_size_encryption_test(
tmp_db: &TempDatabase,
enable_mvcc: bool,
) -> anyhow::Result<()> {
let _ = env_logger::try_init();
let db_path = tmp_db.path.clone();
{
let conn = tmp_db.connect_limbo();
// Set page size to 8k (8192 bytes) and test encryption. Default page size is 4k.
run_query(tmp_db, &conn, "PRAGMA page_size = 8192;")?;
run_query(
tmp_db,
&conn,
"PRAGMA hexkey = 'b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327';",
)?;
run_query(tmp_db, &conn, "PRAGMA cipher = 'aegis256';")?;
if enable_mvcc {
run_query(tmp_db, &conn, "PRAGMA journal_mode = 'mvcc';")?;
}
run_query(
tmp_db,
&conn,
"CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
)?;
run_query(
tmp_db,
&conn,
"INSERT INTO test (value) VALUES ('Hello, World!')",
)?;
let mut row_count = 0;
run_query_on_row(tmp_db, &conn, "SELECT * FROM test", |row: &Row| {
assert_eq!(row.get::<i64>(0).unwrap(), 1);
assert_eq!(row.get::<String>(1).unwrap(), "Hello, World!");
row_count += 1;
})?;
assert_eq!(row_count, 1);
do_flush(&conn, tmp_db)?;
}
{
// Reopen the existing db with 8k page size and test encryption
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(
&uri,
DatabaseOpts::new().with_encryption(ENABLE_ENCRYPTION),
)?;
run_query_on_row(tmp_db, &conn, "SELECT * FROM test", |row: &Row| {
assert_eq!(row.get::<i64>(0).unwrap(), 1);
assert_eq!(row.get::<String>(1).unwrap(), "Hello, World!");
})?;
}
Ok(())
}
fn run_corruption_associated_data_bytes_test(
tmp_db: &TempDatabase,
enable_mvcc: bool,
) -> anyhow::Result<()> {
let _ = env_logger::try_init();
let db_path = tmp_db.path.clone();
{
let conn = tmp_db.connect_limbo();
run_query(
tmp_db,
&conn,
"PRAGMA hexkey = 'b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327';",
)?;
run_query(tmp_db, &conn, "PRAGMA cipher = 'aegis256';")?;
if enable_mvcc {
run_query(tmp_db, &conn, "PRAGMA journal_mode = 'mvcc';")?;
}
run_query(
tmp_db,
&conn,
"CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
)?;
run_query(
tmp_db,
&conn,
"INSERT INTO test (value) VALUES ('Test AD corruption')",
)?;
run_query(tmp_db, &conn, "PRAGMA wal_checkpoint(TRUNCATE);")?;
do_flush(&conn, tmp_db)?;
}
// test corruption at different positions in the header (the first 100 bytes)
let corruption_positions = [3, 7, 16, 30, 50, 70, 99];
for &corrupt_pos in &corruption_positions {
let test_tmp_db = TempDatabaseBuilder::new().build();
let test_db_path = test_tmp_db.path.clone();
std::fs::copy(&db_path, &test_db_path)?;
{
// corrupt one byte
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
let mut file = OpenOptions::new()
.read(true)
.write(true)
.open(&test_db_path)?;
file.seek(SeekFrom::Start(corrupt_pos as u64))?;
let mut original_byte = [0u8; 1];
file.read_exact(&mut original_byte)?;
// corrupt it by flipping all bits
let corrupted_byte = [!original_byte[0]];
file.seek(SeekFrom::Start(corrupt_pos as u64))?;
file.write_all(&corrupted_byte)?;
}
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
test_db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(
&uri,
DatabaseOpts::new().with_encryption(ENABLE_ENCRYPTION),
)
.expect("opening the corrupted DB should not fail at the URI level");
let result = run_query_on_row(tmp_db, &conn, "SELECT * FROM test", |_row: &Row| {});
assert!(
result.is_err(),
"should return error when accessing encrypted DB with corrupted associated data at position {corrupt_pos}",
);
}
Ok(())
}
// TODO: mvcc does not error here
#[turso_macros::test]
fn test_per_page_encryption(tmp_db: TempDatabase) -> anyhow::Result<()> {
let _ = env_logger::try_init();
let db_path = tmp_db.path.clone();
let opts = tmp_db.db_opts;
{
let conn = tmp_db.connect_limbo();
run_query(
&tmp_db,
&conn,
"PRAGMA hexkey = 'b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327';",
)?;
run_query(&tmp_db, &conn, "PRAGMA cipher = 'aegis256';")?;
run_query(
&tmp_db,
&conn,
"CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
)?;
run_query(
&tmp_db,
&conn,
"INSERT INTO test (value) VALUES ('Hello, World!')",
)?;
let mut row_count = 0;
run_query_on_row(&tmp_db, &conn, "SELECT * FROM test", |row: &Row| {
assert_eq!(row.get::<i64>(0).unwrap(), 1);
assert_eq!(row.get::<String>(1).unwrap(), "Hello, World!");
row_count += 1;
})?;
assert_eq!(row_count, 1);
do_flush(&conn, &tmp_db)?;
}
{
//test connecting to the encrypted db using correct URI
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(&uri, opts)?;
let mut row_count = 0;
run_query_on_row(&tmp_db, &conn, "SELECT * FROM test", |row: &Row| {
assert_eq!(row.get::<i64>(0).unwrap(), 1);
assert_eq!(row.get::<String>(1).unwrap(), "Hello, World!");
row_count += 1;
})?;
assert_eq!(row_count, 1);
}
{
//Try to create a table after reopening the encrypted db.
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(&uri, opts)?;
run_query(
&tmp_db,
&conn,
"CREATE TABLE test1 (id INTEGER PRIMARY KEY, value TEXT);",
)?;
do_flush(&conn, &tmp_db)?;
}
{
//Try to create a table after reopening the encrypted db.
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(&uri, opts)?;
run_query(
&tmp_db,
&conn,
"INSERT INTO test1 (value) VALUES ('Hello, World!')",
)?;
let mut row_count = 0;
run_query_on_row(&tmp_db, &conn, "SELECT * FROM test", |row: &Row| {
assert_eq!(row.get::<i64>(0).unwrap(), 1);
assert_eq!(row.get::<String>(1).unwrap(), "Hello, World!");
row_count += 1;
})?;
assert_eq!(row_count, 1);
do_flush(&conn, &tmp_db)?;
}
{
// test connecting to encrypted db using wrong key (key ends with 77, correct key ends with 27).
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76377",
db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(&uri, opts)?;
let result = run_query_on_row(&tmp_db, &conn, "SELECT * FROM test", |_row: &Row| {});
assert!(
result.is_err(),
"should return error when accessing encrypted DB with wrong key"
);
}
{
// test connecting to encrypted db using insufficient encryption parameters in URI.
let uri = format!("file:{}?cipher=aegis256", db_path.to_str().unwrap());
let result = turso_core::Connection::from_uri(&uri, opts);
assert!(
result.is_err(),
"should return error when accessing encrypted DB without passing hexkey in URI"
);
}
{
let uri = format!(
"file:{}?hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
db_path.to_str().unwrap()
);
let result = turso_core::Connection::from_uri(&uri, opts);
assert!(
result.is_err(),
"should return error when accessing encrypted DB without passing cipher in URI"
);
}
{
// test connecting to encrypted db without using URI.
let conn = tmp_db.connect_limbo();
let result = run_query_on_row(&tmp_db, &conn, "SELECT * FROM test", |_row: &Row| {});
assert!(
result.is_err(),
"should return error when accessing encrypted DB without using URI"
);
}
Ok(())
}
#[turso_macros::test]
fn test_non_4k_page_size_encryption(tmp_db: TempDatabase) -> anyhow::Result<()> {
run_non_4k_page_size_encryption_test(&tmp_db, false)
}
#[turso_macros::test]
fn test_non_4k_page_size_encryption_mvcc(tmp_db: TempDatabase) -> anyhow::Result<()> {
run_non_4k_page_size_encryption_test(&tmp_db, true)
}
#[turso_macros::test]
fn test_mvcc_rejects_late_encryption_pragmas(tmp_db: TempDatabase) -> anyhow::Result<()> {
let conn = tmp_db.connect_limbo();
run_query(&tmp_db, &conn, "PRAGMA journal_mode = 'mvcc';")?;
// Insert data before the (rejected) late encryption pragmas.
run_query(
&tmp_db,
&conn,
"CREATE TABLE pre (id INTEGER PRIMARY KEY, v TEXT);",
)?;
run_query(
&tmp_db,
&conn,
"INSERT INTO pre (v) VALUES ('before_late_pragma')",
)?;
let key_err = run_query(
&tmp_db,
&conn,
"PRAGMA hexkey = 'b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327';",
)
.unwrap_err();
assert!(
key_err
.to_string()
.contains("configure encryption before PRAGMA journal_mode='mvcc'"),
"unexpected error: {key_err:?}"
);
let cipher_err = run_query(&tmp_db, &conn, "PRAGMA cipher = 'aegis256';").unwrap_err();
assert!(
cipher_err
.to_string()
.contains("configure encryption before PRAGMA journal_mode='mvcc'"),
"unexpected error: {cipher_err:?}"
);
// Data inserted before the rejected pragmas must still be readable.
let mut pre_count = 0;
run_query_on_row(&tmp_db, &conn, "SELECT v FROM pre", |row: &Row| {
assert_eq!(row.get::<String>(0).unwrap(), "before_late_pragma");
pre_count += 1;
})?;
assert_eq!(pre_count, 1);
run_query(
&tmp_db,
&conn,
"CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
)?;
run_query(
&tmp_db,
&conn,
"INSERT INTO test (value) VALUES ('still plaintext')",
)?;
do_flush(&conn, &tmp_db)?;
let reopened = tmp_db.connect_limbo();
let mut row_count = 0;
run_query_on_row(&tmp_db, &reopened, "SELECT value FROM test", |row: &Row| {
assert_eq!(row.get::<String>(0).unwrap(), "still plaintext");
row_count += 1;
})?;
assert_eq!(row_count, 1);
Ok(())
}
// TODO: mvcc for some reason does not error on corruption here
#[turso_macros::test]
fn test_corruption_turso_magic_bytes(tmp_db: TempDatabase) -> anyhow::Result<()> {
let _ = env_logger::try_init();
let db_path = tmp_db.path.clone();
let opts = tmp_db.db_opts;
{
let conn = tmp_db.connect_limbo();
run_query(
&tmp_db,
&conn,
"PRAGMA hexkey = 'b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327';",
)?;
run_query(&tmp_db, &conn, "PRAGMA cipher = 'aegis256';")?;
run_query(
&tmp_db,
&conn,
"CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
)?;
run_query(
&tmp_db,
&conn,
"INSERT INTO test (value) VALUES ('Test corruption')",
)?;
run_query(&tmp_db, &conn, "PRAGMA wal_checkpoint(TRUNCATE);")?;
do_flush(&conn, &tmp_db)?;
}
// corrupt the Turso magic bytes by changing "Turso" to "Vurso" (the db name as it was intended)
{
use std::fs::OpenOptions;
use std::io::{Seek, SeekFrom, Write};
let mut file = OpenOptions::new().write(true).open(&db_path)?;
file.seek(SeekFrom::Start(0))?;
file.write_all(b"V")?;
}
// try to connect to the corrupted database - this should return a decryption error
{
let uri = format!(
"file:{}?cipher=aegis256&hexkey=b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
db_path.to_str().unwrap()
);
let (_io, conn) = turso_core::Connection::from_uri(&uri, opts)?;
let result = run_query_on_row(&tmp_db, &conn, "SELECT * FROM test", |_row: &Row| {});
assert!(
result.is_err(),
"should return error when accessing encrypted DB with corrupted Turso magic bytes"
);
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains("Decryption failed"),
"error should indicate decryption failure, got: {err_msg}"
);
}
Ok(())
}
#[turso_macros::test]
fn test_corruption_associated_data_bytes(tmp_db: TempDatabase) -> anyhow::Result<()> {
run_corruption_associated_data_bytes_test(&tmp_db, false)
}
#[turso_macros::test]
fn test_corruption_associated_data_bytes_mvcc(tmp_db: TempDatabase) -> anyhow::Result<()> {
run_corruption_associated_data_bytes_test(&tmp_db, true)
}
#[turso_macros::test(mvcc)]
fn test_turso_header_structure(db: TempDatabase) -> anyhow::Result<()> {
let _ = env_logger::try_init();
let verify_header =
|db_path: &str, expected_cipher_id: u8, description: &str| -> anyhow::Result<()> {
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
let mut file = File::open(db_path)?;
let mut header = [0u8; 16];
file.seek(SeekFrom::Start(0))?;
file.read_exact(&mut header)?;
assert_eq!(
&header[0..5],
b"Turso",
"Magic bytes should be 'Turso' for {description}"
);
assert_eq!(header[5], 0x00, "Version should be 0x00 for {description}");
assert_eq!(
header[6], expected_cipher_id,
"Cipher ID should be {expected_cipher_id} for {description}"
);
// the unused bytes should be zeroed
for (i, &byte) in header[7..16].iter().enumerate() {
assert_eq!(
byte,
0,
"Unused byte at position {} should be 0 for {}",
i + 7,
description
);
}
println!("Verified {} header: cipher ID = {}", description, header[6]);
Ok(())
};
let test_cases = [
(
"aes128gcm",
1,
"AES-128-GCM",
"b1bbfda4f589dc9daaf004fe21111e00",
),
(
"aes256gcm",
2,
"AES-256-GCM",
"b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
),
(
"aegis256",
3,
"AEGIS-256",
"b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
),
(
"aegis256x2",
4,
"AEGIS-256X2",
"b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327",
),
(
"aegis128l",
6,
"AEGIS-128L",
"b1bbfda4f589dc9daaf004fe21111e00",
),
(
"aegis128x2",
7,
"AEGIS-128X2",
"b1bbfda4f589dc9daaf004fe21111e00",
),
(
"aegis128x4",
8,
"AEGIS-128X4",
"b1bbfda4f589dc9daaf004fe21111e00",
),
];
let opts = db.db_opts;
let flags = db.db_flags;
for (cipher_name, expected_id, description, hexkey) in test_cases {
let tmp_db = TempDatabase::builder()
.with_opts(opts)
.with_flags(flags)
.build();
let db_path = tmp_db.path.clone();
{
let conn = tmp_db.connect_limbo();
run_query(&tmp_db, &conn, &format!("PRAGMA hexkey = '{hexkey}';"))?;
run_query(&tmp_db, &conn, &format!("PRAGMA cipher = '{cipher_name}';"))?;
run_query(
&tmp_db,
&conn,
"CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT);",
)?;
do_flush(&conn, &tmp_db)?;
}
verify_header(db_path.to_str().unwrap(), expected_id, description)?;
}
Ok(())
}
/// this is a smoll test for database registry caching encryption keys
///
/// Previously, the DATABASE_MANAGER cached Database instances with keys. Which led to:
/// 1. Open database with correct key -> Database cached with correct encryption_key
/// 2. Open database with WRONG key or no key -> Cached Database returned
/// 3. Decryption succeeds because cached Database has correct key
///
/// This test ensures that opening with wrong encryption key (or no key) fails even after
/// the database has been opened with the correct key (which populates the cache).
#[turso_macros::test(mvcc)]
fn test_encryption_key_validation_with_cached_database(_db: TempDatabase) -> anyhow::Result<()> {
let _ = env_logger::try_init();
let temp_dir = tempfile::tempdir()?;
let db_path = temp_dir
.path()
.join(format!("test-enc-cache-{}.db", rng().next_u32()));
let db_path_str = db_path.to_str().unwrap();
let correct_key = "b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327";
let wrong_key = "aaaaaaa4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327";
let io = Arc::new(PlatformIO::new()?);
let opts = DatabaseOpts::new().with_encryption(ENABLE_ENCRYPTION);
let correct_encryption_opts = Some(EncryptionOpts {
cipher: "aegis256".to_string(),
hexkey: correct_key.to_string(),
});
let main_db = Database::open_file_with_flags(
io.clone(),
db_path_str,
OpenFlags::Create,
opts,
correct_encryption_opts.clone(),
)?;
// step 1: Create encrypted database with correct key
{
let correct_encryption_key =
turso_core::EncryptionKey::from_hex_string(correct_key).unwrap();
let conn = main_db.connect()?;
conn.set_encryption_cipher(turso_core::CipherMode::Aegis256)?;
conn.set_encryption_key(correct_encryption_key)?;
conn.execute("CREATE TABLE secret_data (id INTEGER PRIMARY KEY, value TEXT)")?;
conn.execute("INSERT INTO secret_data (value) VALUES ('top secret')")?;
conn.query("PRAGMA wal_checkpoint(TRUNCATE)")?;
for completion in conn.cacheflush()? {
io.wait_for_completion(completion)?;
}
}
// Step 2: re-open with correct key (this uses the DATABASE_MANAGER cache)
{
let correct_encryption_key =
turso_core::EncryptionKey::from_hex_string(correct_key).unwrap();
let db = Database::open_file_with_flags(
io.clone(),
db_path_str,
OpenFlags::default(),
opts,
correct_encryption_opts.clone(),
)?;
let conn = db.connect()?;
conn.set_encryption_cipher(turso_core::CipherMode::Aegis256)?;
conn.set_encryption_key(correct_encryption_key)?;
let rows = conn.query("SELECT * FROM secret_data")?;
let mut row_count = 0;
if let Some(mut rows) = rows {
loop {
match rows.step()? {
turso_core::StepResult::Row => {
let row = rows.row().unwrap();
assert_eq!(row.get::<String>(1).unwrap(), "top secret");
row_count += 1;
}
turso_core::StepResult::Done => break,
turso_core::StepResult::Interrupt => break,
turso_core::StepResult::Busy | turso_core::StepResult::IO => continue,
}
}
}
assert_eq!(row_count, 1, "Should read data with correct key");
}
// Step 3: Opening with wrong key succeeds, but reading data fails with decryption error
{
let wrong_encryption_key = turso_core::EncryptionKey::from_hex_string(wrong_key).unwrap();
let db = Database::open_file_with_flags(
io.clone(),
db_path_str,
OpenFlags::default(),
opts,
Some(EncryptionOpts {
cipher: "aegis256".to_string(),
hexkey: wrong_key.to_string(),
}),
)?;
// opening succeeds - the key is not validated at open time
let conn = db.connect()?;
conn.set_encryption_cipher(turso_core::CipherMode::Aegis256)?;
conn.set_encryption_key(wrong_encryption_key)?;
// Reading data should fail with a decryption error
let read_failed = match conn.query("SELECT * FROM secret_data") {
Err(_) => true,
Ok(Some(mut rows)) => loop {
match rows.step() {
Err(_) => break true, // Error - read failed
Ok(turso_core::StepResult::Done) => break false, // Completed without error
Ok(turso_core::StepResult::Interrupt) => break false,
Ok(turso_core::StepResult::Row) => break false, // Got data - unexpected!!
Ok(turso_core::StepResult::Busy) | Ok(turso_core::StepResult::IO) => continue,
}
},
Ok(None) => false,
};
assert!(
read_failed,
"Reading data with wrong key should fail with decryption error"
);
}
// Step 4: Opening without encryption options should fail immediately
{
let result = Database::open_file_with_flags(
io.clone(),
db_path_str,
OpenFlags::default(),
opts,
None,
);
assert!(
result.is_err(),
"Opening encrypted database without encryption options should fail"
);
let err = result.unwrap_err();
assert!(
err.to_string()
.contains("Database is encrypted but no encryption options provided"),
"Error message should indicate missing encryption options"
);
}
// Step 5: verify correct key still works after wrong key attempt
{
let correct_encryption_key =
turso_core::EncryptionKey::from_hex_string(correct_key).unwrap();
let db = Database::open_file_with_flags(
io.clone(),
db_path_str,
OpenFlags::default(),
opts,
correct_encryption_opts.clone(),
)?;
let conn = db.connect()?;
conn.set_encryption_cipher(turso_core::CipherMode::Aegis256)?;
conn.set_encryption_key(correct_encryption_key)?;
let rows = conn.query("SELECT * FROM secret_data")?;
let mut row_count = 0;
if let Some(mut rows) = rows {
loop {
match rows.step()? {
turso_core::StepResult::Row => {
let row = rows.row().unwrap();
assert_eq!(row.get::<String>(1).unwrap(), "top secret");
row_count += 1;
}
turso_core::StepResult::Done => break,
turso_core::StepResult::Interrupt => break,
turso_core::StepResult::Busy | turso_core::StepResult::IO => continue,
}
}
}
assert_eq!(
row_count, 1,
"Should still read data with correct key after wrong key attempt"
);
}
Ok(())
}
// Two different keys/ciphers for the two attached databases
const KEY_A: &str = "b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327";
const CIPHER_A: &str = "aegis256";
const KEY_B: &str = "a2ccfeb5f690ed0ebf01a843f22222f11ed11d9348213f6d8113b677ae84ad38";
const CIPHER_B: &str = "aes256gcm";
/// Helper: create an encrypted database file with the given cipher, hexkey, table name, and value.
/// Returns the file path.
fn create_encrypted_db(
cipher: &str,
hexkey: &str,
table_name: &str,
value: &str,
) -> anyhow::Result<std::path::PathBuf> {
let temp_dir = tempfile::tempdir()?;
let db_path = temp_dir
.path()
.join(format!("enc-{}-{}.db", table_name, rng().next_u32()));
let db_path_str = db_path.to_str().unwrap();
let io: Arc<dyn IO + Send> = Arc::new(PlatformIO::new()?);
let opts = DatabaseOpts::new().with_encryption(true);
let encryption_opts = Some(EncryptionOpts {
cipher: cipher.to_string(),
hexkey: hexkey.to_string(),
});
let db = Database::open_file_with_flags(
io.clone(),
db_path_str,
OpenFlags::Create,
opts,
encryption_opts,
)?;
let conn = db.connect()?;
let cipher_mode = CipherMode::try_from(cipher)?;
let key = EncryptionKey::from_hex_string(hexkey)?;
conn.set_encryption_cipher(cipher_mode)?;
conn.set_encryption_key(key)?;
conn.execute(format!(
"CREATE TABLE {table_name} (id INTEGER PRIMARY KEY, value TEXT)"
))?;
conn.execute(format!(
"INSERT INTO {table_name} (value) VALUES ('{value}')"
))?;
conn.query("PRAGMA wal_checkpoint(TRUNCATE)")?;
for c in conn.cacheflush()? {
io.wait_for_completion(c)?;
}
// Keep the temp dir alive by leaking it (the test process will clean up)
std::mem::forget(temp_dir);
Ok(db_path)
}
/// Helper: open a plain (unencrypted) main database with attach + encryption enabled.
fn open_main_db() -> anyhow::Result<(TempDatabase, Arc<turso_core::Connection>)> {
let tmp_db = TempDatabase::builder()
.with_opts(DatabaseOpts::new().with_encryption(true).with_attach(true))
.build();
let conn = tmp_db.connect_limbo();
Ok((tmp_db, conn))
}
#[turso_macros::test(mvcc)]
fn test_attach_encrypted_database(_tmp_db: TempDatabase) -> anyhow::Result<()> {
let _ = env_logger::try_init();
// Create two encrypted databases with different keys and ciphers
let path_a = create_encrypted_db(CIPHER_A, KEY_A, "secret_a", "data from A")?;
let path_b = create_encrypted_db(CIPHER_B, KEY_B, "secret_b", "data from B")?;
// --- Test 1: Happy path — attach both with correct keys ---
{
let (main_db, conn) = open_main_db()?;
let attach_a = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_a",
path_a.to_str().unwrap(),
CIPHER_A,
KEY_A
);
let attach_b = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_b",
path_b.to_str().unwrap(),
CIPHER_B,
KEY_B
);
run_query(&main_db, &conn, &attach_a)?;
run_query(&main_db, &conn, &attach_b)?;
let mut row_count = 0;
run_query_on_row(
&main_db,
&conn,
"SELECT value FROM aux_a.secret_a",
|row: &Row| {
assert_eq!(row.get::<String>(0).unwrap(), "data from A");
row_count += 1;
},
)?;
assert_eq!(row_count, 1, "Should read one row from aux_a");
let mut row_count = 0;
run_query_on_row(
&main_db,
&conn,
"SELECT value FROM aux_b.secret_b",
|row: &Row| {
assert_eq!(row.get::<String>(0).unwrap(), "data from B");
row_count += 1;
},
)?;
assert_eq!(row_count, 1, "Should read one row from aux_b");
}
// --- Test 2: Wrong key for db_a — use key_b instead ---
{
let (main_db, conn) = open_main_db()?;
let attach_wrong = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_a",
path_a.to_str().unwrap(),
CIPHER_A,
KEY_B // wrong key!
);
// Attaching may succeed (key is not validated at open time), but reading must fail
let attach_result = run_query(&main_db, &conn, &attach_wrong);
if attach_result.is_ok() {
let read_result = run_query_on_row(
&main_db,
&conn,
"SELECT value FROM aux_a.secret_a",
|_: &Row| {},
);
assert!(
read_result.is_err(),
"Reading with wrong key should fail with decryption error"
);
}
// If attach itself failed, that's also acceptable
}
// --- Test 3: Swapped keys — db_a gets key_b, db_b gets key_a ---
{
let (main_db, conn) = open_main_db()?;
let attach_a_wrong = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_a",
path_a.to_str().unwrap(),
CIPHER_A,
KEY_B
);
let attach_b_wrong = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_b",
path_b.to_str().unwrap(),
CIPHER_B,
KEY_A
);
// Attach may succeed at open time; reading should fail for both
let _ = run_query(&main_db, &conn, &attach_a_wrong);
let _ = run_query(&main_db, &conn, &attach_b_wrong);
let read_a = run_query_on_row(
&main_db,
&conn,
"SELECT value FROM aux_a.secret_a",
|_: &Row| {},
);
let read_b = run_query_on_row(
&main_db,
&conn,
"SELECT value FROM aux_b.secret_b",
|_: &Row| {},
);
assert!(
read_a.is_err() || read_b.is_err(),
"At least one read with swapped keys must fail"
);
}
// --- Test 4: Missing hexkey in URI ---
{
let (main_db, conn) = open_main_db()?;
let attach_no_hexkey = format!(
"ATTACH 'file:{}?cipher={}' AS aux_a",
path_a.to_str().unwrap(),
CIPHER_A
);
let result = run_query(&main_db, &conn, &attach_no_hexkey);
assert!(
result.is_err(),
"ATTACH with cipher but no hexkey should fail"
);
}
// --- Test 5: Missing cipher in URI ---
{
let (main_db, conn) = open_main_db()?;
let attach_no_cipher = format!(
"ATTACH 'file:{}?hexkey={}' AS aux_a",
path_a.to_str().unwrap(),
KEY_A
);
let result = run_query(&main_db, &conn, &attach_no_cipher);
assert!(
result.is_err(),
"ATTACH with hexkey but no cipher should fail"
);
}
// --- Test 6: No encryption params at all ---
{
let (main_db, conn) = open_main_db()?;
let attach_no_enc = format!("ATTACH '{}' AS aux_a", path_a.to_str().unwrap());
let result = run_query(&main_db, &conn, &attach_no_enc);
// Opening an encrypted DB without key should fail
assert!(
result.is_err(),
"ATTACH encrypted DB without key should fail"
);
}
// --- Test 7: Correct key after wrong key attempt ---
{
let (main_db, conn) = open_main_db()?;
// First, try wrong key
let attach_wrong = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_a",
path_a.to_str().unwrap(),
CIPHER_A,
KEY_B
);
let _ = run_query(&main_db, &conn, &attach_wrong);
// Detach (ignore error if attach failed)
let _ = run_query(&main_db, &conn, "DETACH aux_a");
// Now attach with correct key
let attach_correct = format!(
"ATTACH 'file:{}?cipher={}&hexkey={}' AS aux_a",
path_a.to_str().unwrap(),
CIPHER_A,
KEY_A
);
run_query(&main_db, &conn, &attach_correct)?;
let mut row_count = 0;
run_query_on_row(
&main_db,
&conn,
"SELECT value FROM aux_a.secret_a",
|row: &Row| {
assert_eq!(row.get::<String>(0).unwrap(), "data from A");