walletkit-core 0.23.0

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
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
//! Encrypted cache database for credential storage.

use std::path::Path;

use crate::storage::error::StorageResult;
use crate::storage::types::{ActivityEntry, ActivityMetadata, ActivityQuery};
use secrecy::SecretBox;
use walletkit_db::Vault;

mod activity;
mod maintenance;
mod merkle;
mod nullifiers;
mod schema;
mod session;
mod util;

/// Encrypted cache database wrapper.
///
/// Stores non-authoritative, regenerable data (proof cache, session keys,
/// replay guard). Wraps [`walletkit_db::Vault`].
///
/// Unlike the credential vault, cache corruption is recoverable: open
/// failures or integrity failures trigger a wipe-and-rebuild rather than
/// a fatal error.
#[derive(Debug)]
pub struct CacheDb {
    vault: Vault,
}

impl CacheDb {
    /// Opens or rebuilds the encrypted cache database at `path`.
    ///
    /// If the database is corrupted or unreadable, the file is deleted
    /// and a fresh empty cache is created.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened or rebuilt.
    pub fn new(
        path: &Path,
        k_intermediate: &SecretBox<[u8; 32]>,
    ) -> StorageResult<Self> {
        let vault = maintenance::open_or_rebuild(path, k_intermediate)?;
        Ok(Self { vault })
    }

    /// Fetches a cached Merkle proof if it remains valid beyond `valid_until`.
    ///
    /// Returns `None` when missing or expired so callers can refetch from the
    /// indexer without relying on stale proofs.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn merkle_cache_get(&self, valid_until: u64) -> StorageResult<Option<Vec<u8>>> {
        merkle::get(self.vault.connection(), valid_until)
    }

    /// Inserts a cached Merkle proof with a TTL. Existing entries for the
    /// same key are replaced.
    ///
    /// # Errors
    ///
    /// Returns an error if the insert fails.
    pub fn merkle_cache_put(
        &self,
        proof_bytes: &[u8],
        now: u64,
        ttl_seconds: u64,
    ) -> StorageResult<()> {
        merkle::put(self.vault.connection(), proof_bytes, now, ttl_seconds)
    }

    /// Fetches a cached `session_id_r_seed` for the given RP and `oprf_seed`.
    ///
    /// Returns `None` when missing or expired.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn session_seed_get(
        &self,
        rp_id: u64,
        oprf_seed: [u8; 32],
        now: u64,
    ) -> StorageResult<Option<[u8; 32]>> {
        let key = util::session_cache_key(rp_id, oprf_seed);
        session::get(self.vault.connection(), &key, now)
    }

    /// Stores a `session_id_r_seed` keyed by RP and `oprf_seed` with a TTL.
    ///
    /// # Errors
    ///
    /// Returns an error if the insert fails.
    pub fn session_seed_put(
        &self,
        rp_id: u64,
        oprf_seed: [u8; 32],
        session_id_r_seed: [u8; 32],
        now: u64,
        ttl_seconds: u64,
    ) -> StorageResult<()> {
        let key = util::session_cache_key(rp_id, oprf_seed);
        session::put(
            self.vault.connection(),
            &key,
            session_id_r_seed,
            now,
            ttl_seconds,
        )
    }

    /// Checks whether a replay guard entry exists for the given nullifier.
    ///
    /// # Returns
    ///
    /// - `true` if a replay guard entry exists (nullifier replay).
    /// - `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the query to the cache unexpectedly fails.
    pub fn is_nullifier_replay(
        &self,
        nullifier: [u8; 32],
        now: u64,
    ) -> StorageResult<bool> {
        nullifiers::is_nullifier_replay(self.vault.connection(), nullifier, now)
    }

    /// After a proof has been successfully generated, creates a replay guard
    /// entry locally to avoid future replays of the same nullifier.
    ///
    /// # Errors
    ///
    /// Returns an error if the query to the cache unexpectedly fails.
    pub fn replay_guard_set(&self, nullifier: [u8; 32], now: u64) -> StorageResult<()> {
        nullifiers::replay_guard_set(self.vault.connection(), nullifier, now)
    }

    /// Records an activity entry.
    ///
    /// # Errors
    ///
    /// Returns an error if the entry is misconfigured or the insert fails.
    pub fn record_activity(
        &self,
        entry: &ActivityEntry,
        now: u64,
    ) -> StorageResult<u64> {
        activity::record(self.vault.connection(), entry, now)
    }

    /// Lists activity entries, most recent first.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn list_activities(
        &self,
        query: ActivityQuery,
        limit: u32,
        offset: u32,
    ) -> StorageResult<Vec<ActivityEntry>> {
        activity::list(self.vault.connection(), query, limit, offset)
    }

    /// Returns aggregate activity metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn activity_metadata(&self) -> StorageResult<ActivityMetadata> {
        activity::metadata(self.vault.connection())
    }

    /// Deletes all activity entries. Returns the number of entries deleted.
    ///
    /// # Errors
    ///
    /// Returns an error if the delete fails.
    pub fn clear_activities(&self) -> StorageResult<u64> {
        activity::clear(self.vault.connection())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::types::{ActivityOutcome, ProtocolVersion};
    use secrecy::SecretBox;
    use std::fs;
    use std::path::PathBuf;
    use uuid::Uuid;

    fn sample_new_activity_entry() -> ActivityEntry {
        ActivityEntry {
            id: None,
            rp_id: 1,
            app_identifier: "app_test".to_string(),
            client_id: "req-1".to_string(),
            protocol: ProtocolVersion::V3,
            timestamp: None,
            issuer_schema_ids: vec![],
            outcome: ActivityOutcome::Completed,
            failure_reason: None,
        }
    }

    fn temp_cache_path() -> PathBuf {
        let mut path = std::env::temp_dir();
        path.push(format!("walletkit-cache-{}.sqlite", Uuid::new_v4()));
        path
    }

    fn cleanup_cache_files(path: &Path) {
        let _ = fs::remove_file(path);
        let _ = fs::remove_file(path.with_extension("sqlite-wal"));
        let _ = fs::remove_file(path.with_extension("sqlite-shm"));
    }

    fn temp_lock_path() -> PathBuf {
        let mut path = std::env::temp_dir();
        path.push(format!("walletkit-cache-lock-{}.lock", Uuid::new_v4()));
        path
    }

    fn cleanup_lock_file(path: &Path) {
        let _ = fs::remove_file(path);
    }

    #[test]
    fn test_cache_create_and_open() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x11u8; 32]);
        let lock_path = temp_lock_path();
        let db = CacheDb::new(&path, &key).expect("create cache");
        drop(db);
        CacheDb::new(&path, &key).expect("open cache");
        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }

    #[test]
    fn test_cache_rebuild_on_corruption() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x22u8; 32]);
        let lock_path = temp_lock_path();
        let db = CacheDb::new(&path, &key).expect("create cache");
        let oprf_seed = [0x01u8; 32];
        let r_seed = [0x02u8; 32];
        let now = 1_000;
        db.session_seed_put(1, oprf_seed, r_seed, now, 1000)
            .expect("put session seed");
        drop(db);

        fs::write(&path, b"corrupt").expect("corrupt cache file");

        let db = CacheDb::new(&path, &key).expect("rebuild cache");
        let value = db
            .session_seed_get(1, oprf_seed, now)
            .expect("get session seed");
        assert!(value.is_none());
        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }

    #[test]
    fn test_merkle_cache_ttl() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x33u8; 32]);
        let lock_path = temp_lock_path();
        let db = CacheDb::new(&path, &key).expect("create cache");
        db.merkle_cache_put(&[1, 2, 3], 100, 10)
            .expect("put merkle proof");
        let hit = db.merkle_cache_get(105).expect("get merkle proof");
        assert!(hit.is_some());
        let miss = db.merkle_cache_get(111).expect("get merkle proof");
        assert!(miss.is_none());
        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }

    #[test]
    fn test_session_seed_cache_ttl() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x44u8; 32]);
        let lock_path = temp_lock_path();
        let db = CacheDb::new(&path, &key).expect("create cache");
        let oprf_seed = [0x55u8; 32];
        let r_seed = [0x66u8; 32];
        let now = 100;
        db.session_seed_put(1, oprf_seed, r_seed, now, 10)
            .expect("put session seed");
        let hit = db.session_seed_get(1, oprf_seed, now).expect("get");
        assert_eq!(hit, Some(r_seed));
        let miss = db.session_seed_get(1, oprf_seed, now + 11).expect("get");
        assert!(miss.is_none());
        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }

    #[test]
    fn test_schema_version_mismatch_resets_database() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x77u8; 32]);
        let lock_path = temp_lock_path();
        let db = CacheDb::new(&path, &key).expect("create cache");

        db.record_activity(&sample_new_activity_entry(), 1000)
            .expect("record activity");

        db.session_seed_put(1, [0x01u8; 32], [0x02u8; 32], 1000, 1000)
            .expect("put session seed");

        drop(db);

        let conn = walletkit_sqlite::cipher::open_encrypted(&path, &key)
            .expect("open raw connection");
        conn.execute(
            "UPDATE cache_meta SET schema_version = schema_version + 1",
            &[],
        )
        .expect("bump schema version");
        drop(conn);

        let db = CacheDb::new(&path, &key).expect("reopen cache after version bump");

        let seed = db
            .session_seed_get(1, [0x01u8; 32], 1000)
            .expect("get session seed");

        assert!(
            seed.is_none(),
            "cache_entries should be wiped on a schema version mismatch"
        );

        let entries = db
            .list_activities(ActivityQuery::default(), 10, 0)
            .expect("list activities after version bump");

        assert!(
            entries.is_empty(),
            "activity history shares the cache schema, so it is reset too"
        );

        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }

    #[test]
    fn test_activity_migration_applies_to_preexisting_cache_file() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x88u8; 32]);
        let lock_path = temp_lock_path();

        let conn = walletkit_sqlite::cipher::open_encrypted(&path, &key)
            .expect("create raw connection");
        conn.execute_batch(
            "CREATE TABLE cache_meta (
                schema_version INTEGER NOT NULL,
                created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL
            );
            CREATE TABLE cache_entries (
                key_bytes BLOB NOT NULL,
                value_bytes BLOB NOT NULL,
                inserted_at INTEGER NOT NULL,
                expires_at INTEGER NOT NULL,
                PRIMARY KEY (key_bytes)
            );
            INSERT INTO cache_meta (schema_version, created_at, updated_at)
            VALUES (2, 1000, 1000);
            INSERT INTO cache_entries (key_bytes, value_bytes, inserted_at, expires_at)
            VALUES (X'AA', X'BB', 1000, 999999999);",
        )
        .expect("seed legacy cache schema");
        drop(conn);

        let db = CacheDb::new(&path, &key).expect("open legacy cache file");

        db.record_activity(&sample_new_activity_entry(), 1000)
            .expect("record activity after migration");

        let entries = db
            .list_activities(ActivityQuery::default(), 10, 0)
            .expect("list activities");

        assert_eq!(entries.len(), 1, "migration should add activity_entries");

        drop(db);

        let conn = walletkit_sqlite::cipher::open_encrypted(&path, &key)
            .expect("reopen raw connection");

        let count = conn
            .query_row("SELECT COUNT(*) FROM cache_entries", &[], |stmt| {
                Ok(stmt.column_i64(0))
            })
            .expect("count cache_entries");

        assert_eq!(
            count, 1,
            "pre-existing cache_entries row must survive the activity migration"
        );

        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }

    #[test]
    fn test_schema_version_is_recorded() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x99u8; 32]);
        let lock_path = temp_lock_path();

        let db = CacheDb::new(&path, &key).expect("create cache");
        db.record_activity(&sample_new_activity_entry(), 1000)
            .expect("record activity");
        drop(db);

        let conn = walletkit_sqlite::cipher::open_encrypted(&path, &key)
            .expect("open raw connection");
        let version = conn
            .query_row("SELECT schema_version FROM cache_meta", &[], |stmt| {
                Ok(stmt.column_i64(0))
            })
            .expect("read cache schema version");
        drop(conn);

        // Three migrations: cache_entries, activity init, activity rebuild.
        assert_eq!(version, 3, "the cache schema registers as version 3");

        let db = CacheDb::new(&path, &key).expect("reopen cache");
        let entries = db
            .list_activities(ActivityQuery::default(), 10, 0)
            .expect("list activities");

        assert_eq!(entries.len(), 1, "reopening must not restamp or reset");
        assert_eq!(entries[0].rp_id, 1);
        assert_eq!(entries[0].app_identifier, "app_test");

        cleanup_cache_files(&path);
        cleanup_lock_file(&lock_path);
    }
}