walletkit-core 0.20.0

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
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
//! Encrypted vault database for credential storage.
//!
//! Thin wrapper over [`walletkit_db::Vault`]: the credential-specific schema,
//! queries, and backup-table list live here; the underlying open / key /
//! integrity-check machinery and the shared `blob_objects` table come from
//! [`walletkit_db`].

mod schema;
#[cfg(test)]
mod tests;

use std::path::Path;

use crate::storage::error::{StorageError, StorageResult};
use crate::storage::types::{BlobKind, CredentialRecord};
use schema::{ensure_schema, VAULT_SCHEMA_VERSION};
use secrecy::SecretBox;
use walletkit_db::{blobs, cipher, params, DbError, Row, StepResult, Value, Vault};

/// Tables included in plaintext vault backups, in order.
///
/// `vault_meta` is intentionally excluded: on restore, the destination vault
/// already has its own `vault_meta` (created by `schema::ensure_schema` +
/// `init_leaf_index`) with the authoritative `leaf_index` from the
/// authenticator.
///
/// **Note:** New tables added to the vault schema must be added here too.
pub(crate) const BACKUP_TABLES: &[&str] = &["credential_records", "blob_objects"];

/// Encrypted vault database wrapper around [`walletkit_db::Vault`].
#[derive(Debug)]
pub struct CredentialVault {
    vault: Vault,
}

impl CredentialVault {
    /// Opens or creates the encrypted vault database at `path`.
    ///
    /// # Errors
    ///
    /// Returns an error if the database cannot be opened, keyed, or
    /// initialized.
    pub fn new(
        path: &Path,
        k_intermediate: &SecretBox<[u8; 32]>,
    ) -> StorageResult<Self> {
        let vault = Vault::open(path, k_intermediate, |conn| {
            blobs::ensure_schema(conn)?;
            ensure_schema(conn)
        })?;
        Ok(Self { vault })
    }

    /// Initializes or validates the leaf index for this vault.
    ///
    /// The leaf index is the account's position in the registry tree and must
    /// be consistent for all subsequent operations. A mismatch returns an
    /// error.
    ///
    /// # Errors
    ///
    /// Returns an error if the stored leaf index does not match.
    pub fn init_leaf_index(&self, leaf_index: u64, now: u64) -> StorageResult<()> {
        let leaf_index_i64 = to_i64(leaf_index, "leaf_index")?;
        let now_i64 = to_i64(now, "now")?;
        let conn = self.vault.connection();
        let tx = conn.transaction().map_err(|err| map_db_err(&err))?;
        let stored = tx
            .query_row(
                "INSERT INTO vault_meta (schema_version, leaf_index, created_at, updated_at)
                 VALUES (?1, ?2, ?3, ?3)
                 ON CONFLICT(schema_version) DO UPDATE SET
                     leaf_index = CASE
                         WHEN vault_meta.leaf_index IS NULL
                         THEN excluded.leaf_index
                         ELSE vault_meta.leaf_index
                     END
                 RETURNING leaf_index",
                params![VAULT_SCHEMA_VERSION, leaf_index_i64, now_i64],
                |stmt| Ok(stmt.column_i64(0)),
            )
            .map_err(|err| map_db_err(&err))?;
        if stored != leaf_index_i64 {
            let expected = to_u64(stored, "leaf_index")?;
            return Err(StorageError::InvalidLeafIndex {
                expected,
                provided: leaf_index,
            });
        }
        tx.commit().map_err(|err| map_db_err(&err))?;
        Ok(())
    }

    /// Stores a credential and optional associated data.
    ///
    /// Blob content is deduplicated by content id to avoid storing identical
    /// payloads multiple times.
    ///
    /// # Errors
    ///
    /// Returns an error if any insert fails.
    #[expect(
        clippy::too_many_arguments,
        reason = "fields mirror the credential record schema"
    )]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "byte buffers are consumed here; callers don't reuse them"
    )]
    pub fn store_credential(
        &self,
        issuer_schema_id: u64,
        subject_blinding_factor: Vec<u8>,
        genesis_issued_at: u64,
        expires_at: u64,
        credential_blob: Vec<u8>,
        associated_data: Option<Vec<u8>>,
        now: u64,
    ) -> StorageResult<u64> {
        let now_i64 = to_i64(now, "now")?;
        let issuer_schema_id_i64 = to_i64(issuer_schema_id, "issuer_schema_id")?;
        let genesis_issued_at_i64 = to_i64(genesis_issued_at, "genesis_issued_at")?;
        let expires_at_i64 = to_i64(expires_at, "expires_at")?;

        let conn = self.vault.connection();
        let tx = conn.transaction().map_err(|err| map_db_err(&err))?;

        let credential_blob_id = blobs::put(
            conn,
            BlobKind::CredentialBlob as u8,
            credential_blob.as_slice(),
            now,
        )?;

        let associated_data_id = associated_data
            .as_ref()
            .map(|data| {
                blobs::put(conn, BlobKind::AssociatedData as u8, data.as_slice(), now)
            })
            .transpose()?;

        let ad_cid_value: Value = associated_data_id
            .as_ref()
            .map_or(Value::Null, |cid| Value::Blob(cid.to_vec()));

        let credential_id = tx
            .query_row(
                "INSERT INTO credential_records (
                    issuer_schema_id,
                    subject_blinding_factor,
                    genesis_issued_at,
                    expires_at,
                    updated_at,
                    credential_blob_cid,
                    associated_data_cid
                ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
                RETURNING credential_id",
                params![
                    issuer_schema_id_i64,
                    subject_blinding_factor,
                    genesis_issued_at_i64,
                    expires_at_i64,
                    now_i64,
                    credential_blob_id.as_slice(),
                    ad_cid_value,
                ],
                |stmt| Ok(stmt.column_i64(0)),
            )
            .map_err(|err| map_db_err(&err))?;

        tx.commit().map_err(|err| map_db_err(&err))?;
        to_u64(credential_id, "credential_id")
    }

    /// Lists credential metadata, optionally filtered by issuer schema.
    ///
    /// Results include both active and expired credentials. Expiry status is
    /// reported via [`CredentialRecord::is_expired`] and uses
    /// `now >= expires_at` semantics.
    ///
    /// Results are ordered by `updated_at` descending (most recent first).
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn list_credentials(
        &self,
        issuer_schema_id: Option<u64>,
        now: u64,
    ) -> StorageResult<Vec<CredentialRecord>> {
        let now_i64 = to_i64(now, "now")?;
        let issuer_schema_id_i64 = issuer_schema_id
            .map(|value| to_i64(value, "issuer_schema_id"))
            .transpose()?;

        let mut records = Vec::new();
        let issuer_filter = issuer_schema_id_i64.map_or(Value::Null, Value::Integer);

        let sql = "SELECT
                cr.credential_id,
                cr.issuer_schema_id,
                cr.genesis_issued_at,
                cr.expires_at,
                CASE WHEN cr.expires_at <= ?1 THEN 1 ELSE 0 END AS is_expired
             FROM credential_records cr
             WHERE (?2 IS NULL OR cr.issuer_schema_id = ?2)
             ORDER BY cr.updated_at DESC";

        let mut stmt = self
            .vault
            .connection()
            .prepare(sql)
            .map_err(|err| map_db_err(&err))?;
        stmt.bind_values(&[Value::Integer(now_i64), issuer_filter])
            .map_err(|err| map_db_err(&err))?;
        while let StepResult::Row(row) = stmt.step().map_err(|err| map_db_err(&err))? {
            records.push(map_record(&row)?);
        }

        Ok(records)
    }

    /// Deletes a credential record by ID.
    ///
    /// Deleting a credential also removes orphaned `credential_blob_cid` and
    /// `associated_data_cid` blobs when no records reference them.
    ///
    /// # Errors
    ///
    /// Returns an error if the delete query fails or the credential ID does
    /// not exist.
    pub fn delete_credential(&self, credential_id: u64) -> StorageResult<()> {
        let credential_id_i64 = to_i64(credential_id, "credential_id")?;
        let conn = self.vault.connection();
        let tx = conn.transaction().map_err(|err| map_db_err(&err))?;

        let deleted = tx
            .execute(
                "DELETE FROM credential_records WHERE credential_id = ?1",
                params![credential_id_i64],
            )
            .map_err(|err| map_db_err(&err))?;

        if deleted == 0 {
            return Err(StorageError::CredentialIdNotFound { credential_id });
        }

        // Delete orphaned credential blobs
        tx.execute(
            "DELETE FROM blob_objects
             WHERE blob_kind = ?1
               AND NOT EXISTS (
                   SELECT 1
                   FROM credential_records cr
                   WHERE cr.credential_blob_cid = blob_objects.content_id
               )",
            params![BlobKind::CredentialBlob.as_i64()],
        )
        .map_err(|err| map_db_err(&err))?;

        // Delete orphaned associated data blobs
        tx.execute(
            "DELETE FROM blob_objects
             WHERE blob_kind = ?1
               AND NOT EXISTS (
                   SELECT 1
                   FROM credential_records cr
                   WHERE cr.associated_data_cid = blob_objects.content_id
               )",
            params![BlobKind::AssociatedData.as_i64()],
        )
        .map_err(|err| map_db_err(&err))?;

        tx.commit().map_err(|err| map_db_err(&err))?;
        Ok(())
    }

    /// Retrieves the credential bytes and blinding factor by issuer schema ID.
    ///
    /// Returns the most recent non-expired credential matching the issuer
    /// schema ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub fn fetch_credential_and_blinding_factor(
        &self,
        issuer_schema_id: u64,
        now: u64,
    ) -> StorageResult<Option<(Vec<u8>, Vec<u8>)>> {
        let expires = to_i64(now, "now")?;
        let issuer_schema_id_i64 = to_i64(issuer_schema_id, "issuer_schema_id")?;

        let sql = "SELECT
                cr.subject_blinding_factor,
                blob.bytes as credential_blob
             FROM credential_records cr
             INNER JOIN blob_objects blob ON cr.credential_blob_cid = blob.content_id
             WHERE cr.expires_at > ?1 AND cr.issuer_schema_id = ?2
             ORDER BY cr.updated_at DESC
             LIMIT 1";

        let mut stmt = self
            .vault
            .connection()
            .prepare(sql)
            .map_err(|err| map_db_err(&err))?;
        stmt.bind_values(params![expires, issuer_schema_id_i64])
            .map_err(|err| map_db_err(&err))?;
        match stmt.step().map_err(|err| map_db_err(&err))? {
            StepResult::Row(row) => {
                let blinding_factor = row.column_blob(0);
                let credential_blob = row.column_blob(1);
                Ok(Some((credential_blob, blinding_factor)))
            }
            StepResult::Done => Ok(None),
        }
    }

    /// **Development only.** Permanently deletes all credentials and their
    /// associated blob data from the vault.
    ///
    /// This is a destructive, unrecoverable operation. Do not call in
    /// production. Vault metadata (leaf index, schema version) is preserved.
    ///
    /// # Errors
    ///
    /// Returns an error if the delete operation fails.
    pub fn danger_delete_all_credentials(&self) -> StorageResult<u64> {
        let conn = self.vault.connection();
        let tx = conn.transaction().map_err(|err| map_db_err(&err))?;

        let deleted = tx
            .execute("DELETE FROM credential_records", &[])
            .map_err(|err| map_db_err(&err))?;

        tx.execute("DELETE FROM blob_objects", &[])
            .map_err(|err| map_db_err(&err))?;

        tx.commit().map_err(|err| map_db_err(&err))?;
        Ok(deleted as u64)
    }

    /// Runs an integrity check on the vault database.
    ///
    /// # Errors
    ///
    /// Returns an error if the check cannot be executed.
    pub fn check_integrity(&self) -> StorageResult<bool> {
        cipher::integrity_check(self.vault.connection()).map_err(|e| map_db_err(&e))
    }

    /// Exports a plaintext (unencrypted) copy of the vault to `dest`.
    ///
    /// Callers that need cross-process exclusion (to keep a concurrent
    /// writer from interleaving between stale-file cleanup and the
    /// `ATTACH`-based copy) must hold [`crate::storage::StorageLock`]
    /// themselves. The caller is also responsible for deleting the
    /// exported file after use.
    ///
    /// # Errors
    ///
    /// Returns an error if the export fails.
    pub fn export_plaintext(&self, dest: &Path) -> StorageResult<()> {
        let conn = self.vault.connection();
        if dest.exists() {
            std::fs::remove_file(dest).map_err(|e| {
                StorageError::VaultDb(format!("failed to remove stale backup: {e}"))
            })?;
        }
        cipher::export_plaintext_copy(conn, dest, BACKUP_TABLES)
            .map_err(|e| map_db_err(&e))
    }

    /// Imports credentials from a plaintext (unencrypted) vault backup into
    /// an empty vault. Intended for restore on a fresh install.
    ///
    /// Callers that need cross-process exclusion must hold
    /// [`crate::storage::StorageLock`] themselves. The caller is also
    /// responsible for deleting the source file after the import completes.
    ///
    /// # Errors
    ///
    /// Returns an error if the import fails.
    pub fn import_plaintext(&self, source: &Path) -> StorageResult<()> {
        let conn = self.vault.connection();
        cipher::import_plaintext_copy(conn, source, BACKUP_TABLES)
            .map_err(|e| map_db_err(&e))
    }
}

fn map_record(row: &Row<'_, '_>) -> StorageResult<CredentialRecord> {
    let credential_id = row.column_i64(0);
    let issuer_schema_id = row.column_i64(1);
    let genesis_issued_at = row.column_i64(2);
    let expires_at = row.column_i64(3);
    let is_expired = row.column_i64(4);
    Ok(CredentialRecord {
        credential_id: to_u64(credential_id, "credential_id")?,
        issuer_schema_id: to_u64(issuer_schema_id, "issuer_schema_id")?,
        genesis_issued_at: to_u64(genesis_issued_at, "genesis_issued_at")?,
        expires_at: to_u64(expires_at, "expires_at")?,
        is_expired: is_expired != 0,
    })
}

fn to_i64(value: u64, label: &str) -> StorageResult<i64> {
    i64::try_from(value).map_err(|_| {
        StorageError::VaultDb(format!("{label} out of range for i64: {value}"))
    })
}

fn to_u64(value: i64, label: &str) -> StorageResult<u64> {
    u64::try_from(value).map_err(|_| {
        StorageError::VaultDb(format!("{label} out of range for u64: {value}"))
    })
}

fn map_db_err(err: &DbError) -> StorageError {
    StorageError::VaultDb(err.to_string())
}