Debian Codegraph @

tests/sqlite/sqlcipher.rs

raw symbols SCIP
1 #![cfg(sqlite_test_sqlcipher)]
2
3 use std::str::FromStr;
4
5 use sqlx::sqlite::SqliteQueryResult;
6 use sqlx::{query, Connection, SqliteConnection};
7 use sqlx::{sqlite::SqliteConnectOptions, ConnectOptions};
8 use tempfile::TempDir;
9
10 async fn new_db_url() -> anyhow::Result<(String, TempDir)> {
11 let dir = TempDir::new()?;
12 let filepath = dir.path().join("database.sqlite3");
13
14 Ok((format!("sqlite://{}", filepath.display()), dir))
15 }
16
17 async fn fill_db(conn: &mut SqliteConnection) -> anyhow::Result<SqliteQueryResult> {
18 conn.transaction(|tx| {
19 Box::pin(async move {
20 query(
21 "
22 CREATE TABLE Company(
23 Id INT PRIMARY KEY NOT NULL,
24 Name TEXT NOT NULL,
25 Salary REAL
26 );
27 ",
28 )
29 .execute(&mut **tx)
30 .await?;
31
32 query(
33 r#"
34 INSERT INTO Company(Id, Name, Salary)
35 VALUES
36 (1, "aaa", 111),
37 (2, "bbb", 222)
38 "#,
39 )
40 .execute(&mut **tx)
41 .await
42 })
43 })
44 .await
45 .map_err(|e| e.into())
46 }
47
48 #[sqlx_macros::test]
49 async fn it_encrypts() -> anyhow::Result<()> {
50 let (url, _dir) = new_db_url().await?;
51
52 let mut conn = SqliteConnectOptions::from_str(&url)?
53 .pragma("key", "the_password")
54 .create_if_missing(true)
55 .connect()
56 .await?;
57
58 fill_db(&mut conn).await?;
59
60 // Create another connection without key, query should fail
61 let mut conn = SqliteConnectOptions::from_str(&url)?.connect().await?;
62
63 assert!(conn
64 .transaction(|tx| {
65 Box::pin(async move { query("SELECT * FROM Company;").fetch_all(&mut **tx).await })
66 })
67 .await
68 .is_err());
69
70 Ok(())
71 }
72
73 #[sqlx_macros::test]
74 async fn it_can_store_and_read_encrypted_data() -> anyhow::Result<()> {
75 let (url, _dir) = new_db_url().await?;
76
77 let mut conn = SqliteConnectOptions::from_str(&url)?
78 .pragma("key", "the_password")
79 .create_if_missing(true)
80 .connect()
81 .await?;
82
83 fill_db(&mut conn).await?;
84
85 // Create another connection with valid key
86 let mut conn = SqliteConnectOptions::from_str(&url)?
87 .pragma("key", "the_password")
88 .connect()
89 .await?;
90
91 let result = conn
92 .transaction(|tx| {
93 Box::pin(async move { query("SELECT * FROM Company;").fetch_all(&mut **tx).await })
94 })
95 .await?;
96
97 assert!(result.len() > 0);
98
99 Ok(())
100 }
101
102 #[sqlx_macros::test]
103 async fn it_fails_if_password_is_incorrect() -> anyhow::Result<()> {
104 let (url, _dir) = new_db_url().await?;
105
106 let mut conn = SqliteConnectOptions::from_str(&url)?
107 .pragma("key", "the_password")
108 .create_if_missing(true)
109 .connect()
110 .await?;
111
112 fill_db(&mut conn).await?;
113
114 // Connection with invalid key should not allow to execute queries
115 let mut conn = SqliteConnectOptions::from_str(&url)?
116 .pragma("key", "BADBADBAD")
117 .connect()
118 .await?;
119
120 assert!(conn
121 .transaction(|tx| {
122 Box::pin(async move { query("SELECT * FROM Company;").fetch_all(&mut **tx).await })
123 })
124 .await
125 .is_err());
126
127 Ok(())
128 }
129
130 #[sqlx_macros::test]
131 async fn it_honors_order_of_encryption_pragmas() -> anyhow::Result<()> {
132 let (url, _dir) = new_db_url().await?;
133
134 // Make call of cipher configuration mixed with other pragmas,
135 // it should have no effect, encryption related pragmas should be
136 // executed first and allow to establish valid connection
137 let mut conn = SqliteConnectOptions::from_str(&url)?
138 .pragma("cipher_kdf_algorithm", "PBKDF2_HMAC_SHA1")
139 .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal)
140 .pragma("cipher_page_size", "1024")
141 .pragma("key", "the_password")
142 .foreign_keys(true)
143 .pragma("kdf_iter", "64000")
144 .auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Incremental)
145 .pragma("cipher_hmac_algorithm", "HMAC_SHA1")
146 .create_if_missing(true)
147 .connect()
148 .await?;
149
150 fill_db(&mut conn).await?;
151
152 let mut conn = SqliteConnectOptions::from_str(&url)?
153 .pragma("dummy", "pragma")
154 // The cipher configuration set on first connection is
155 // version 3 of SQLCipher, so for second it's enough to set
156 // the compatibility mode.
157 .pragma("cipher_compatibility", "3")
158 .pragma("key", "the_password")
159 .connect()
160 .await?;
161
162 let result = conn
163 .transaction(|tx| {
164 Box::pin(async move { query("SELECT * FROM COMPANY;").fetch_all(&mut **tx).await })
165 })
166 .await?;
167
168 assert!(result.len() > 0);
169
170 Ok(())
171 }
172
173 #[sqlx_macros::test]
174 async fn it_allows_to_rekey_the_db() -> anyhow::Result<()> {
175 let (url, _dir) = new_db_url().await?;
176
177 let mut conn = SqliteConnectOptions::from_str(&url)?
178 .pragma("key", "the_password")
179 .create_if_missing(true)
180 .connect()
181 .await?;
182
183 fill_db(&mut conn).await?;
184
185 // The 'pragma rekey' can be called at any time
186 query("PRAGMA rekey = new_password;")
187 .execute(&mut conn)
188 .await?;
189
190 let mut conn = SqliteConnectOptions::from_str(&url)?
191 .pragma("dummy", "pragma")
192 .pragma("key", "new_password")
193 .connect()
194 .await?;
195
196 let result = conn
197 .transaction(|tx| {
198 Box::pin(async move { query("SELECT * FROM COMPANY;").fetch_all(&mut **tx).await })
199 })
200 .await?;
201
202 assert!(result.len() > 0);
203
204 Ok(())
205 }