Debian Codegraph @

third_party/rust/mls-rs-provider-sqlite/src/lib.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 use connection_strategy::ConnectionStrategy;
6 use group_state::SqLiteGroupStateStorage;
7 use psk::SqLitePreSharedKeyStorage;
8 use rusqlite::Connection;
9 use storage::{SqLiteApplicationStorage, SqLiteKeyPackageStorage};
10 use thiserror::Error;
11
12 mod application;
13 mod group_state;
14 mod key_package;
15 mod psk;
16
17 #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-bundled"))]
18 mod cipher;
19
20 #[cfg(test)]
21 pub(crate) mod test_utils;
22
23 /// Connection strategies.
24 pub mod connection_strategy;
25
26 /// SQLite storage components.
27 pub mod storage {
28 pub use {
29 crate::application::{Item, SqLiteApplicationStorage},
30 crate::group_state::SqLiteGroupStateStorage,
31 crate::key_package::SqLiteKeyPackageStorage,
32 crate::psk::SqLitePreSharedKeyStorage,
33 };
34 }
35
36 #[derive(Debug, Error)]
37 /// SQLite data storage error.
38 pub enum SqLiteDataStorageError {
39 #[error(transparent)]
40 /// SQLite error.
41 SqlEngineError(Box<dyn std::error::Error + Send + Sync + 'static>),
42 #[error(transparent)]
43 /// Stored data is not compatible with the expected data type.
44 DataConversionError(Box<dyn std::error::Error + Send + Sync + 'static>),
45 #[cfg(any(feature = "sqlcipher", feature = "sqlcipher-bundled"))]
46 #[error("invalid key, must use SqlCipherKey::RawKeyWithSalt with plaintext_header_size > 0")]
47 /// Invalid SQLCipher key header.
48 SqlCipherKeyInvalidWithHeader,
49 }
50
51 impl mls_rs_core::error::IntoAnyError for SqLiteDataStorageError {
52 fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> {
53 Ok(self.into())
54 }
55 }
56
57 #[derive(Clone, Debug)]
58 pub enum JournalMode {
59 Delete,
60 Truncate,
61 Persist,
62 Memory,
63 Wal,
64 Off,
65 }
66
67 /// Note: for in-memory dbs (such as what the tests use), the only available options are MEMORY or OFF
68 /// Invalid modes do not error, only no-op
69 impl JournalMode {
70 fn as_str(&self) -> &'static str {
71 match self {
72 JournalMode::Delete => "DELETE",
73 JournalMode::Truncate => "TRUNCATE",
74 JournalMode::Persist => "PERSIST",
75 JournalMode::Memory => "MEMORY",
76 JournalMode::Wal => "WAL",
77 JournalMode::Off => "OFF",
78 }
79 }
80 }
81
82 #[derive(Clone, Debug)]
83 /// SQLite data storage engine.
84 pub struct SqLiteDataStorageEngine<CS>
85 where
86 CS: ConnectionStrategy,
87 {
88 connection_strategy: CS,
89 group_state_context: Option<Vec<u8>>,
90 journal_mode: Option<JournalMode>,
91 }
92
93 impl<CS> SqLiteDataStorageEngine<CS>
94 where
95 CS: ConnectionStrategy,
96 {
97 pub fn new(
98 connection_strategy: CS,
99 ) -> Result<SqLiteDataStorageEngine<CS>, SqLiteDataStorageError> {
100 Ok(SqLiteDataStorageEngine {
101 connection_strategy,
102 group_state_context: None,
103 journal_mode: None,
104 })
105 }
106
107 pub fn with_context(self, group_state_context: Vec<u8>) -> Self {
108 Self {
109 group_state_context: Some(group_state_context),
110 ..self
111 }
112 }
113
114 /// A `journal_mode` of `None` means the SQLite default is used.
115 pub fn with_journal_mode(self, journal_mode: Option<JournalMode>) -> Self {
116 Self {
117 journal_mode,
118 ..self
119 }
120 }
121
122 fn create_connection(&self) -> Result<Connection, SqLiteDataStorageError> {
123 let connection = self.connection_strategy.make_connection()?;
124
125 // Run SQL to establish the schema
126 let current_schema = connection
127 .pragma_query_value(None, "user_version", |rows| rows.get::<_, u32>(0))
128 .map_err(|e| SqLiteDataStorageError::SqlEngineError(e.into()))?;
129
130 if let Some(journal_mode) = &self.journal_mode {
131 connection
132 .pragma_update(None, "journal_mode", journal_mode.as_str())
133 .map_err(|e| SqLiteDataStorageError::SqlEngineError(e.into()))?;
134 }
135
136 if current_schema != 1 {
137 create_tables_v1(&connection)?;
138 }
139
140 Ok(connection)
141 }
142
143 /// Returns a struct that implements the `GroupStateStorage` trait for use in MLS.
144 pub fn group_state_storage(&self) -> Result<SqLiteGroupStateStorage, SqLiteDataStorageError> {
145 Ok(SqLiteGroupStateStorage::new(
146 self.create_connection()?,
147 self.group_state_context.clone(),
148 ))
149 }
150
151 /// Returns a struct that implements the `KeyPackageStorage` trait for use in MLS.
152 pub fn key_package_storage(&self) -> Result<SqLiteKeyPackageStorage, SqLiteDataStorageError> {
153 Ok(SqLiteKeyPackageStorage::new(self.create_connection()?))
154 }
155
156 /// Returns a struct that implements the `PreSharedKeyStorage` trait for use in MLS.
157 pub fn pre_shared_key_storage(
158 &self,
159 ) -> Result<SqLitePreSharedKeyStorage, SqLiteDataStorageError> {
160 Ok(SqLitePreSharedKeyStorage::new(self.create_connection()?))
161 }
162
163 /// Returns a key value store that can be used to store application specific data.
164 pub fn application_data_storage(
165 &self,
166 ) -> Result<SqLiteApplicationStorage, SqLiteDataStorageError> {
167 Ok(SqLiteApplicationStorage::new(self.create_connection()?))
168 }
169 }
170
171 fn create_tables_v1(connection: &Connection) -> Result<(), SqLiteDataStorageError> {
172 connection
173 .execute_batch(
174 "BEGIN;
175 CREATE TABLE mls_group (
176 group_id BLOB PRIMARY KEY,
177 snapshot BLOB NOT NULL
178 ) WITHOUT ROWID;
179 CREATE TABLE epoch (
180 group_id BLOB,
181 epoch_id INTEGER,
182 epoch_data BLOB NOT NULL,
183 FOREIGN KEY (group_id) REFERENCES mls_group (group_id) ON DELETE CASCADE
184 PRIMARY KEY (group_id, epoch_id)
185 ) WITHOUT ROWID;
186 CREATE TABLE key_package (
187 id BLOB PRIMARY KEY,
188 expiration INTEGER,
189 data BLOB NOT NULL
190 ) WITHOUT ROWID;
191 CREATE INDEX key_package_exp ON key_package (expiration);
192 CREATE TABLE psk (
193 psk_id BLOB PRIMARY KEY,
194 data BLOB NOT NULL
195 ) WITHOUT ROWID;
196 CREATE TABLE kvs (
197 key TEXT PRIMARY KEY,
198 value BLOB NOT NULL
199 ) WITHOUT ROWID;
200 PRAGMA user_version = 1;
201 COMMIT;",
202 )
203 .map_err(|e| SqLiteDataStorageError::SqlEngineError(e.into()))
204 }
205
206 #[cfg(test)]
207 mod tests {
208 use tempfile::tempdir;
209
210 use crate::{
211 connection_strategy::{FileConnectionStrategy, MemoryStrategy},
212 SqLiteDataStorageEngine,
213 };
214
215 #[test]
216 pub fn user_version_test() {
217 let database = SqLiteDataStorageEngine::new(MemoryStrategy).unwrap();
218
219 let _connection = database.create_connection().unwrap();
220
221 // Create another connection to make sure the migration doesn't try to happen again.
222 let connection = database.create_connection().unwrap();
223
224 // Run SQL to establish the schema
225 let current_schema = connection
226 .pragma_query_value(None, "user_version", |rows| rows.get::<_, u32>(0))
227 .unwrap();
228
229 assert_eq!(current_schema, 1);
230 }
231
232 #[test]
233 pub fn journal_mode_test() {
234 let temp = tempdir().unwrap();
235
236 // Connect with journal_mode other than the default of MEMORY
237 let database = SqLiteDataStorageEngine::new(FileConnectionStrategy::new(
238 &temp.path().join("test_db.sqlite"),
239 ))
240 .unwrap();
241
242 let connection = database
243 .with_journal_mode(Some(crate::JournalMode::Truncate))
244 .create_connection()
245 .unwrap();
246
247 let journal_mode = connection
248 .pragma_query_value(None, "journal_mode", |rows| rows.get::<_, String>(0))
249 .unwrap();
250
251 assert_eq!(journal_mode, "truncate");
252 }
253 }