sefy-core 0.4.0

Core library for sefy: an inconspicuous encrypted secret store in a single file
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
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
//! The database living inside the encrypted blob.
//!
//! The connection is always in-memory: bytes arrive decrypted, are handed to
//! SQLite's deserialize interface, and go back out through serialize. SQLite is
//! never pointed at a path, so no plaintext page ever reaches the disk.

use crate::error::{Error, Result};
use crate::model::{Credential, Item, ItemKind, ItemSummary, NewItem, Payload, Query};
use rusqlite::{Connection, MAIN_DB, OptionalExtension, params};
use std::io::Cursor;

/// Schema version of the database inside the blob.
///
/// Distinct from the file format version: the envelope can stay the same while
/// the tables under it grow. Version 2 added `items.uuid`, which is why a vault
/// written by 0.1.x still opens — it is migrated on load, not rejected.
const SCHEMA_VERSION: i64 = 2;

/// Opens an empty in-memory database with the current schema.
pub fn create() -> Result<Connection> {
    let connection = Connection::open_in_memory()?;
    configure(&connection)?;
    migrate(&connection)?;
    Ok(connection)
}

/// Loads a serialized database into memory and brings it up to date.
pub fn load(database: &[u8]) -> Result<Connection> {
    let mut connection = Connection::open_in_memory()?;
    connection.deserialize_read_exact(MAIN_DB, Cursor::new(database), database.len(), false)?;
    configure(&connection)?;
    migrate(&connection)?;
    Ok(connection)
}

/// Serializes the in-memory database back to bytes.
pub fn dump(connection: &Connection) -> Result<Vec<u8>> {
    Ok(connection.serialize(MAIN_DB)?.to_vec())
}

fn configure(connection: &Connection) -> Result<()> {
    // Journaling has nothing to protect here — the database is a memory buffer
    // that is either sealed to disk whole or not at all.
    connection.execute_batch(
        "PRAGMA journal_mode = MEMORY;
         PRAGMA temp_store = MEMORY;
         PRAGMA foreign_keys = ON;",
    )?;
    Ok(())
}

fn migrate(connection: &Connection) -> Result<()> {
    let version: i64 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;

    if version < SCHEMA_VERSION {
        // Steps run in order and each is idempotent, so a vault written by any
        // earlier version arrives at the current schema by the same path.
        migrate_to_v1(connection)?;
        migrate_to_v2(connection)?;
        connection.pragma_update(None, "user_version", SCHEMA_VERSION)?;
    }

    // Unconditional, even at the current version: a migrated vault stays
    // readable *and writable* by 0.1.x, which knows nothing about uuids and
    // leaves the column NULL. So an up-to-date `user_version` does not prove
    // every row carries an identity — only that this database passed through
    // here once.
    assign_missing_uuids(connection)?;
    Ok(())
}

/// Adds `items.uuid`: an identity that survives leaving this vault.
///
/// Row ids cannot serve: they are per-vault autoincrements, so the same item
/// carries different ids on two machines while unrelated items collide. Merging
/// and re-importing both need to recognise an item, which is what this is for.
fn migrate_to_v2(connection: &Connection) -> Result<()> {
    let already_there = connection
        .prepare("SELECT 1 FROM pragma_table_info('items') WHERE name = 'uuid'")?
        .exists([])?;
    if !already_there {
        connection.execute_batch("ALTER TABLE items ADD COLUMN uuid TEXT")?;
    }

    assign_missing_uuids(connection)?;

    // Unique rather than merely indexed: two items sharing an identity would
    // make a merge ambiguous, and there is no sane way to guess which is which.
    // NULLs are exempt in SQLite, which is why the pass above runs first.
    connection.execute_batch("CREATE UNIQUE INDEX IF NOT EXISTS idx_items_uuid ON items(uuid)")?;
    Ok(())
}

/// Gives an identity to every item that lacks one.
///
/// Two ways a row gets here: it predates the column, or an older build inserted
/// it after this vault was already migrated. Both are answered the same way,
/// and both only ever happen once per row.
fn assign_missing_uuids(connection: &Connection) -> Result<()> {
    let missing: Vec<i64> = connection
        .prepare("SELECT id FROM items WHERE uuid IS NULL OR uuid = ''")?
        .query_map([], |row| row.get(0))?
        .collect::<std::result::Result<_, _>>()?;

    for id in missing {
        connection.execute(
            "UPDATE items SET uuid = ?1 WHERE id = ?2",
            params![new_uuid()?, id],
        )?;
    }
    Ok(())
}

/// A random UUID (version 4), rendered in the usual hyphenated form.
pub fn new_uuid() -> Result<String> {
    let mut bytes = crate::crypto::random_bytes::<16>()?;
    // Version 4, variant 1 — the bits that say "this was made from randomness".
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;

    let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
    Ok(format!(
        "{}-{}-{}-{}-{}",
        &hex[0..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..32]
    ))
}

fn migrate_to_v1(connection: &Connection) -> Result<()> {
    connection.execute_batch(
        "CREATE TABLE IF NOT EXISTS items (
             id         INTEGER PRIMARY KEY,
             title      TEXT    NOT NULL,
             kind       TEXT    NOT NULL,
             created_at INTEGER NOT NULL,
             updated_at INTEGER NOT NULL
         );

         CREATE TABLE IF NOT EXISTS notes (
             item_id INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE,
             text    TEXT NOT NULL
         );

         CREATE TABLE IF NOT EXISTS credentials (
             item_id  INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE,
             login    TEXT NOT NULL,
             password TEXT NOT NULL,
             url      TEXT,
             totp     TEXT,
             notes    TEXT
         );

         CREATE TABLE IF NOT EXISTS files (
             item_id  INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE,
             filename TEXT NOT NULL,
             bytes    BLOB NOT NULL
         );

         CREATE TABLE IF NOT EXISTS tags (
             id   INTEGER PRIMARY KEY,
             name TEXT NOT NULL UNIQUE
         );

         CREATE TABLE IF NOT EXISTS item_tags (
             item_id INTEGER NOT NULL REFERENCES items(id) ON DELETE CASCADE,
             tag_id  INTEGER NOT NULL REFERENCES tags(id)  ON DELETE CASCADE,
             PRIMARY KEY (item_id, tag_id)
         );

         CREATE INDEX IF NOT EXISTS idx_items_kind  ON items(kind);
         CREATE INDEX IF NOT EXISTS idx_items_title ON items(title);
         CREATE INDEX IF NOT EXISTS idx_item_tags_tag ON item_tags(tag_id);",
    )?;
    Ok(())
}

/// Inserts an item and returns its identifier.
pub fn insert_item(connection: &mut Connection, item: NewItem, now: i64) -> Result<i64> {
    insert_item_with_uuid(connection, item, &new_uuid()?, now, now)
}

/// Inserts an item under an identity and timestamps decided by the caller.
///
/// Merging and importing need this: an item arriving from another vault keeps
/// the identity and the history it already had, or the two copies would stop
/// being the same item the moment they travelled.
pub fn insert_item_with_uuid(
    connection: &mut Connection,
    item: NewItem,
    uuid: &str,
    created_at: i64,
    updated_at: i64,
) -> Result<i64> {
    let transaction = connection.transaction()?;
    let kind = item.payload.kind();

    transaction.execute(
        "INSERT INTO items (uuid, title, kind, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)",
        params![uuid, item.title, kind.as_str(), created_at, updated_at],
    )?;
    let id = transaction.last_insert_rowid();

    insert_payload(&transaction, id, &item.payload)?;
    set_tags(&transaction, id, &item.tags)?;

    transaction.commit()?;
    Ok(id)
}

/// Finds the item carrying this identity, if the vault holds one.
pub fn find_by_uuid(connection: &Connection, uuid: &str) -> Result<Option<i64>> {
    Ok(connection
        .query_row(
            "SELECT id FROM items WHERE uuid = ?1",
            params![uuid],
            |row| row.get(0),
        )
        .optional()?)
}

fn insert_payload(connection: &Connection, id: i64, payload: &Payload) -> Result<()> {
    match payload {
        Payload::Note { text } => {
            connection.execute(
                "INSERT INTO notes (item_id, text) VALUES (?1, ?2)",
                params![id, text],
            )?;
        }
        Payload::Credential(credential) => {
            connection.execute(
                "INSERT INTO credentials (item_id, login, password, url, totp, notes)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    id,
                    credential.login,
                    credential.password,
                    credential.url,
                    credential.totp,
                    credential.notes
                ],
            )?;
        }
        Payload::File { filename, bytes } => {
            connection.execute(
                "INSERT INTO files (item_id, filename, bytes) VALUES (?1, ?2, ?3)",
                params![id, filename, bytes],
            )?;
        }
    }
    Ok(())
}

fn delete_payload(connection: &Connection, id: i64) -> Result<()> {
    connection.execute("DELETE FROM notes WHERE item_id = ?1", params![id])?;
    connection.execute("DELETE FROM credentials WHERE item_id = ?1", params![id])?;
    connection.execute("DELETE FROM files WHERE item_id = ?1", params![id])?;
    Ok(())
}

fn set_tags(connection: &Connection, id: i64, tags: &[String]) -> Result<()> {
    connection.execute("DELETE FROM item_tags WHERE item_id = ?1", params![id])?;
    for tag in normalize_tags(tags) {
        connection.execute(
            "INSERT OR IGNORE INTO tags (name) VALUES (?1)",
            params![tag],
        )?;
        let tag_id: i64 =
            connection.query_row("SELECT id FROM tags WHERE name = ?1", params![tag], |row| {
                row.get(0)
            })?;
        connection.execute(
            "INSERT OR IGNORE INTO item_tags (item_id, tag_id) VALUES (?1, ?2)",
            params![id, tag_id],
        )?;
    }
    prune_tags(connection)?;
    Ok(())
}

/// Drops tag rows no item refers to any more.
///
/// Tags exist to group items; one left behind by an edit or a deletion would
/// otherwise linger in `sefy tags` forever.
fn prune_tags(connection: &Connection) -> Result<()> {
    connection.execute(
        "DELETE FROM tags WHERE id NOT IN (SELECT tag_id FROM item_tags)",
        [],
    )?;
    Ok(())
}

/// Trims tags, drops empty ones and removes duplicates, keeping order stable.
fn normalize_tags(tags: &[String]) -> Vec<String> {
    let mut seen = Vec::new();
    for tag in tags {
        let tag = tag.trim();
        if tag.is_empty() {
            continue;
        }
        if !seen.iter().any(|kept: &String| kept == tag) {
            seen.push(tag.to_owned());
        }
    }
    seen
}

/// Replaces the title, payload and tags of an existing item.
pub fn update_item(
    connection: &mut Connection,
    id: i64,
    title: Option<String>,
    payload: Option<Payload>,
    tags: Option<Vec<String>>,
    now: i64,
) -> Result<()> {
    let transaction = connection.transaction()?;

    let existing_kind: Option<String> = transaction
        .query_row("SELECT kind FROM items WHERE id = ?1", params![id], |row| {
            row.get(0)
        })
        .optional()?;
    let existing_kind = existing_kind.ok_or(Error::ItemNotFound(id))?;

    if let Some(title) = title {
        transaction.execute(
            "UPDATE items SET title = ?2 WHERE id = ?1",
            params![id, title],
        )?;
    }

    if let Some(payload) = payload {
        let kind = payload.kind();
        // Changing an item's kind would leave callers holding an id whose shape
        // silently changed; edits stay within the kind the item was created as.
        if kind.as_str() != existing_kind {
            return Err(Error::ItemKindMismatch {
                id,
                actual: ItemKind::parse(&existing_kind)
                    .map(ItemKind::as_str)
                    .unwrap_or("unknown"),
                expected: kind.as_str(),
            });
        }
        delete_payload(&transaction, id)?;
        insert_payload(&transaction, id, &payload)?;
    }

    if let Some(tags) = tags {
        set_tags(&transaction, id, &tags)?;
    }

    transaction.execute(
        "UPDATE items SET updated_at = ?2 WHERE id = ?1",
        params![id, now],
    )?;
    transaction.commit()?;
    Ok(())
}

/// Removes an item and everything hanging off it.
pub fn delete_item(connection: &Connection, id: i64) -> Result<()> {
    let removed = connection.execute("DELETE FROM items WHERE id = ?1", params![id])?;
    if removed == 0 {
        return Err(Error::ItemNotFound(id));
    }
    prune_tags(connection)?;
    Ok(())
}

/// Reads one item with its payload.
pub fn get_item(connection: &Connection, id: i64) -> Result<Item> {
    let summary = get_summary(connection, id)?;
    let payload = match summary.kind {
        ItemKind::Note => {
            let text = connection.query_row(
                "SELECT text FROM notes WHERE item_id = ?1",
                params![id],
                |row| row.get(0),
            )?;
            Payload::Note { text }
        }
        ItemKind::Credential => connection.query_row(
            "SELECT login, password, url, totp, notes FROM credentials WHERE item_id = ?1",
            params![id],
            |row| {
                Ok(Payload::Credential(Credential {
                    login: row.get(0)?,
                    password: row.get(1)?,
                    url: row.get(2)?,
                    totp: row.get(3)?,
                    notes: row.get(4)?,
                }))
            },
        )?,
        ItemKind::File => connection.query_row(
            "SELECT filename, bytes FROM files WHERE item_id = ?1",
            params![id],
            |row| {
                Ok(Payload::File {
                    filename: row.get(0)?,
                    bytes: row.get(1)?,
                })
            },
        )?,
    };
    Ok(Item { summary, payload })
}

/// Reads one item without its payload.
pub fn get_summary(connection: &Connection, id: i64) -> Result<ItemSummary> {
    let row = connection
        .query_row(
            "SELECT id, uuid, title, kind, created_at, updated_at FROM items WHERE id = ?1",
            params![id],
            |row| {
                Ok((
                    row.get::<_, i64>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, i64>(4)?,
                    row.get::<_, i64>(5)?,
                ))
            },
        )
        .optional()?;
    let (id, uuid, title, kind, created_at, updated_at) = row.ok_or(Error::ItemNotFound(id))?;

    Ok(ItemSummary {
        id,
        uuid,
        title,
        kind: ItemKind::parse(&kind).ok_or(Error::ItemNotFound(id))?,
        tags: tags_of(connection, id)?,
        created_at,
        updated_at,
    })
}

fn tags_of(connection: &Connection, id: i64) -> Result<Vec<String>> {
    let mut statement = connection.prepare(
        "SELECT t.name FROM tags t
         JOIN item_tags it ON it.tag_id = t.id
         WHERE it.item_id = ?1
         ORDER BY t.name",
    )?;
    let tags = statement
        .query_map(params![id], |row| row.get::<_, String>(0))?
        .collect::<rusqlite::Result<Vec<_>>>()?;
    Ok(tags)
}

/// Finds items matching a query, newest first.
pub fn search(connection: &Connection, query: &Query) -> Result<Vec<ItemSummary>> {
    let mut sql = String::from(
        "SELECT DISTINCT i.id FROM items i
         LEFT JOIN notes n       ON n.item_id = i.id
         LEFT JOIN credentials c ON c.item_id = i.id
         WHERE 1 = 1",
    );
    let mut arguments: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

    if let Some(kind) = query.kind {
        arguments.push(Box::new(kind.as_str().to_owned()));
        sql.push_str(&format!(" AND i.kind = ?{}", arguments.len()));
    }

    if let Some(text) = query
        .text
        .as_deref()
        .map(str::trim)
        .filter(|t| !t.is_empty())
    {
        // Attachment bytes are deliberately left out: a blob match would say
        // nothing useful and would mean scanning every file in the vault.
        arguments.push(Box::new(format!("%{}%", escape_like(text))));
        let placeholder = arguments.len();
        sql.push_str(&format!(
            " AND (i.title LIKE ?{p} ESCAPE '\\'
                OR n.text  LIKE ?{p} ESCAPE '\\'
                OR c.login LIKE ?{p} ESCAPE '\\'
                OR c.url   LIKE ?{p} ESCAPE '\\'
                OR c.notes LIKE ?{p} ESCAPE '\\')",
            p = placeholder
        ));
    }

    for tag in normalize_tags(&query.tags) {
        arguments.push(Box::new(tag));
        sql.push_str(&format!(
            " AND EXISTS (SELECT 1 FROM item_tags it
                          JOIN tags t ON t.id = it.tag_id
                          WHERE it.item_id = i.id AND t.name = ?{})",
            arguments.len()
        ));
    }

    sql.push_str(" ORDER BY i.updated_at DESC, i.id DESC");

    let mut statement = connection.prepare(&sql)?;
    let bindings: Vec<&dyn rusqlite::ToSql> = arguments.iter().map(AsRef::as_ref).collect();
    let ids = statement
        .query_map(bindings.as_slice(), |row| row.get::<_, i64>(0))?
        .collect::<rusqlite::Result<Vec<_>>>()?;

    ids.into_iter()
        .map(|id| get_summary(connection, id))
        .collect()
}

/// Escapes the wildcards SQL `LIKE` would otherwise interpret.
fn escape_like(text: &str) -> String {
    text.replace('\\', "\\\\")
        .replace('%', "\\%")
        .replace('_', "\\_")
}

/// Lists every tag in the vault with how many items carry it.
pub fn list_tags(connection: &Connection) -> Result<Vec<(String, i64)>> {
    let mut statement = connection.prepare(
        "SELECT t.name, COUNT(it.item_id) FROM tags t
         LEFT JOIN item_tags it ON it.tag_id = t.id
         GROUP BY t.id
         ORDER BY t.name",
    )?;
    let tags = statement
        .query_map([], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
        })?
        .collect::<rusqlite::Result<Vec<_>>>()?;
    Ok(tags)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normalize_tags_trims_and_deduplicates() {
        let tags = vec![
            " bank ".to_owned(),
            "bank".to_owned(),
            String::new(),
            "  ".to_owned(),
            "mail".to_owned(),
        ];
        assert_eq!(normalize_tags(&tags), vec!["bank", "mail"]);
    }

    #[test]
    fn escape_like_neutralizes_wildcards() {
        assert_eq!(escape_like("100%_a\\b"), "100\\%\\_a\\\\b");
    }

    #[test]
    fn dump_and_load_preserve_items() {
        let mut connection = create().unwrap();
        let id = insert_item(
            &mut connection,
            NewItem::new(
                "note",
                Payload::Note {
                    text: "text".to_owned(),
                },
            ),
            10,
        )
        .unwrap();

        let bytes = dump(&connection).unwrap();
        let reloaded = load(&bytes).unwrap();

        assert_eq!(get_item(&reloaded, id).unwrap().summary.title, "note");
    }
}