dove-core 0.1.1

The shared library behind dove — client-side-encrypted, expiring file sharing from a cloud you own.
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
//! The full tier's encryption engine: chunked AES-256-GCM, streaming, with a
//! random key destined for the URL fragment. Same bytes on both ends (Rust and
//! WebCrypto both speak AES-GCM), so `dove get` and the browser page decrypt
//! the same container.
//!
//! Container format (all integers big-endian):
//!
//! ```text
//! header:  "DOVE" (4) | version:u8 | nonce_prefix:[u8;8] | chunk_size:u32
//! chunk:   is_last:u8 | ct_len:u32 | ciphertext(ct_len)      (repeated)
//! ```
//!
//! Each chunk is AES-256-GCM over one plaintext block. The 12-byte nonce is
//! `nonce_prefix || counter` (counter never repeats within a file, prefix is
//! random per file — so nonces never reuse). The **counter and the is_last flag
//! are the AAD**, so reordering chunks, flipping the terminal flag, or dropping
//! the last chunk all fail authentication. A stream that ends before an
//! `is_last = 1` chunk is a truncation and is rejected.

// Consumed by `dove get` and encrypted `share` (next slices).
#![allow(dead_code)]

use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Nonce};
use anyhow::{anyhow, bail, Result};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use std::io::{Read, Write};

const MAGIC: &[u8; 4] = b"DOVE";
const VERSION: u8 = 1;
/// Default plaintext chunk size: 1 MiB. Small enough to stream, big enough that
/// per-chunk overhead (16-byte tag + 5-byte framing) is negligible.
pub const DEFAULT_CHUNK: usize = 1 << 20;

/// A fresh random 256-bit content key.
pub fn gen_key() -> [u8; 32] {
    let mut k = [0u8; 32];
    getrandom::getrandom(&mut k).expect("OS RNG unavailable");
    k
}

/// Encode a key for the URL fragment (base64url, no padding).
pub fn key_to_fragment(key: &[u8; 32]) -> String {
    URL_SAFE_NO_PAD.encode(key)
}

/// Decode a key from a URL fragment.
pub fn key_from_fragment(s: &str) -> Result<[u8; 32]> {
    let bytes = URL_SAFE_NO_PAD
        .decode(s.trim())
        .map_err(|_| anyhow!("invalid key in the link"))?;
    bytes
        .try_into()
        .map_err(|_| anyhow!("key in the link is the wrong length"))
}

/// PBKDF2 iterations for PIN-locked shares. High enough that a leaked ciphertext
/// (past the gate) resists offline PIN brute force; fast enough (~100-200ms) that
/// a legitimate unlock is instant. Both Rust and WebCrypto run the same count.
pub const PBKDF2_ITERS: u32 = 600_000;

/// Derive the content key for a PIN-locked share: `PBKDF2-HMAC-SHA256(PIN,
/// salt = fragment_secret)`. The fragment carries only `fragment_secret` (high
/// entropy); the PIN (delivered out of band) is the second factor folded in. The
/// server never sees either, so end-to-end confidentiality holds. WebCrypto's
/// PBKDF2 with the same inputs produces byte-identical output.
pub fn derive_key(pin: &str, fragment_secret: &[u8; 32]) -> [u8; 32] {
    pbkdf2::pbkdf2_hmac_array::<sha2::Sha256, 32>(pin.as_bytes(), fragment_secret, PBKDF2_ITERS)
}

/// The salted hash the gate stores to verify a PIN online: `hex(SHA-256(id ":"
/// pin))`. The gate rate-limits and locks, so this need only resist a DB leak,
/// not an online guessing attack. The Python gate computes the same string.
pub fn pin_hash(share_id: &str, pin: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(share_id.as_bytes());
    h.update(b":");
    h.update(pin.as_bytes());
    hex_lower(&h.finalize())
}

/// Derive the key for the fragment's metadata blob (filename + trust) from the
/// secret, domain-separated so it's independent of the file key. `SHA-256(secret
/// ‖ "dove-meta-v1")` — a construction WebCrypto reproduces byte-for-byte.
pub fn meta_key(secret: &[u8; 32]) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(secret);
    h.update(b"dove-meta-v1");
    h.finalize().into()
}

/// Encrypt the metadata blob (filename + sender name + message) for the URL
/// fragment: `base64url(nonce(12) ‖ AES-256-GCM(meta_key, plaintext))`. It rides
/// the fragment, so the server never sees the real filename or the trust text.
pub fn encrypt_meta(secret: &[u8; 32], plaintext: &[u8]) -> String {
    let key = meta_key(secret);
    let cipher = Aes256Gcm::new_from_slice(&key).expect("32-byte key");
    let mut nonce = [0u8; 12];
    getrandom::getrandom(&mut nonce).expect("OS RNG unavailable");
    let ct = cipher
        .encrypt(Nonce::from_slice(&nonce), plaintext)
        .expect("metadata encryption");
    let mut blob = nonce.to_vec();
    blob.extend_from_slice(&ct);
    URL_SAFE_NO_PAD.encode(blob)
}

/// Decrypt a metadata blob produced by `encrypt_meta` (or WebCrypto's equivalent).
pub fn decrypt_meta(secret: &[u8; 32], blob_b64: &str) -> Result<Vec<u8>> {
    let blob = URL_SAFE_NO_PAD
        .decode(blob_b64.trim())
        .map_err(|_| anyhow!("invalid metadata in the link"))?;
    if blob.len() < 12 + 16 {
        bail!("metadata in the link is too short");
    }
    let key = meta_key(secret);
    let cipher = Aes256Gcm::new_from_slice(&key).expect("32-byte key");
    let (nonce, ct) = blob.split_at(12);
    cipher
        .decrypt(Nonce::from_slice(nonce), ct)
        .map_err(|_| anyhow!("metadata decryption failed"))
}

/// A fresh 32-byte gate secret, hex-encoded — the key for MAC'd share ids. Stored
/// in `secrets.toml` (to mint) and in the gate Lambda's env (to verify).
pub fn gen_gate_secret() -> String {
    let mut b = [0u8; 32];
    getrandom::getrandom(&mut b).expect("OS RNG unavailable");
    hex_lower(&b)
}

/// Mint an unforgeable share id: `hex(nonce(8) ‖ HMAC-SHA256(gate_secret,
/// nonce)[:8])`. The 64-bit MAC means the gate can reject any id it didn't mint
/// with a compute-only check, *before* touching the database — so forged /
/// random-id floods die cheap. The gate (Python) verifies with the same
/// construction.
pub fn mint_share_id(gate_secret: &[u8], nonce: &[u8; 8]) -> String {
    use hmac::{Hmac, Mac};
    let mut m =
        <Hmac<sha2::Sha256> as Mac>::new_from_slice(gate_secret).expect("HMAC accepts any key len");
    m.update(nonce);
    let tag = m.finalize().into_bytes();
    let mut raw = nonce.to_vec();
    raw.extend_from_slice(&tag[..8]);
    hex_lower(&raw)
}

/// A fresh MAC'd share id from a hex-encoded gate secret.
pub fn new_share_id(gate_secret_hex: &str) -> Result<String> {
    let secret = hex_decode(gate_secret_hex).ok_or_else(|| anyhow!("invalid gate secret"))?;
    let mut nonce = [0u8; 8];
    getrandom::getrandom(&mut nonce).expect("OS RNG unavailable");
    Ok(mint_share_id(&secret, &nonce))
}

/// Decode a lowercase hex string to bytes.
pub fn hex_decode(s: &str) -> Option<Vec<u8>> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
        .collect()
}

fn hex_lower(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
        s.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
    }
    s
}

/// Encrypt `reader` into `writer` as the chunked container above.
pub fn encrypt<R: Read, W: Write>(
    key: &[u8; 32],
    chunk_size: usize,
    mut reader: R,
    mut writer: W,
) -> Result<()> {
    let cipher = Aes256Gcm::new_from_slice(key).expect("32-byte key");
    let mut prefix = [0u8; 8];
    getrandom::getrandom(&mut prefix).expect("OS RNG unavailable");

    writer.write_all(MAGIC)?;
    writer.write_all(&[VERSION])?;
    writer.write_all(&prefix)?;
    writer.write_all(&(chunk_size as u32).to_be_bytes())?;

    let mut buf = vec![0u8; chunk_size];
    let mut counter: u32 = 0;
    loop {
        let n = read_full(&mut reader, &mut buf)?;
        let is_last = n < chunk_size; // a short (incl. empty) read means EOF
        let ct = cipher
            .encrypt(
                &nonce(&prefix, counter),
                Payload {
                    msg: &buf[..n],
                    aad: &aad(counter, is_last),
                },
            )
            .map_err(|_| anyhow!("encryption failed"))?;
        writer.write_all(&[is_last as u8])?;
        writer.write_all(&(ct.len() as u32).to_be_bytes())?;
        writer.write_all(&ct)?;
        if is_last {
            break;
        }
        counter += 1;
    }
    Ok(())
}

/// Decrypt the chunked container from `reader` into `writer`. Fails on a wrong
/// key, any tampering, reordering, or truncation.
pub fn decrypt<R: Read, W: Write>(key: &[u8; 32], mut reader: R, mut writer: W) -> Result<()> {
    let cipher = Aes256Gcm::new_from_slice(key).expect("32-byte key");

    let mut magic = [0u8; 4];
    reader
        .read_exact(&mut magic)
        .map_err(|_| anyhow!("not a dove-encrypted file"))?;
    if &magic != MAGIC {
        bail!("not a dove-encrypted file");
    }
    let mut ver = [0u8; 1];
    reader.read_exact(&mut ver)?;
    if ver[0] != VERSION {
        bail!("unsupported dove format version {}", ver[0]);
    }
    let mut prefix = [0u8; 8];
    reader.read_exact(&mut prefix)?;
    let mut _chunk_size = [0u8; 4];
    reader.read_exact(&mut _chunk_size)?; // informational

    let mut counter: u32 = 0;
    loop {
        let mut flag = [0u8; 1];
        if reader.read(&mut flag)? == 0 {
            bail!("truncated: the file ended before its final chunk");
        }
        let is_last = flag[0];
        let mut len = [0u8; 4];
        reader.read_exact(&mut len)?;
        let mut ct = vec![0u8; u32::from_be_bytes(len) as usize];
        reader.read_exact(&mut ct)?;

        let pt = cipher
            .decrypt(
                &nonce(&prefix, counter),
                Payload {
                    msg: &ct,
                    aad: &aad(counter, is_last == 1),
                },
            )
            .map_err(|_| anyhow!("decryption failed — wrong key, or the data was tampered with"))?;
        writer.write_all(&pt)?;
        if is_last == 1 {
            break;
        }
        counter += 1;
    }
    Ok(())
}

/// The 12-byte GCM nonce for a chunk: `prefix(8) || counter(4)`.
fn nonce(prefix: &[u8; 8], counter: u32) -> Nonce<aes_gcm::aead::consts::U12> {
    let mut n = [0u8; 12];
    n[..8].copy_from_slice(prefix);
    n[8..].copy_from_slice(&counter.to_be_bytes());
    *Nonce::from_slice(&n)
}

/// The additional authenticated data for a chunk: `counter(4) || is_last(1)`.
fn aad(counter: u32, is_last: bool) -> Vec<u8> {
    let mut a = counter.to_be_bytes().to_vec();
    a.push(is_last as u8);
    a
}

/// Read until `buf` is full or EOF; returns bytes read.
fn read_full<R: Read>(reader: &mut R, buf: &mut [u8]) -> std::io::Result<usize> {
    let mut n = 0;
    while n < buf.len() {
        match reader.read(&mut buf[n..])? {
            0 => break,
            k => n += k,
        }
    }
    Ok(n)
}

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

    fn roundtrip(data: &[u8], chunk: usize) -> Vec<u8> {
        let key = gen_key();
        let mut ct = Vec::new();
        encrypt(&key, chunk, data, &mut ct).unwrap();
        let mut pt = Vec::new();
        decrypt(&key, &ct[..], &mut pt).unwrap();
        pt
    }

    #[test]
    fn roundtrips_across_sizes_and_chunk_boundaries() {
        // empty, sub-chunk, exact chunk, exact multiple, and multi-chunk.
        assert_eq!(roundtrip(b"", 16), b"");
        assert_eq!(roundtrip(b"hi", 16), b"hi");
        assert_eq!(roundtrip(&[7u8; 16], 16), vec![7u8; 16]);
        assert_eq!(roundtrip(&[8u8; 32], 16), vec![8u8; 32]);
        assert_eq!(roundtrip(&[9u8; 1000], 64), vec![9u8; 1000]);
    }

    #[test]
    fn wrong_key_fails() {
        let mut ct = Vec::new();
        encrypt(&gen_key(), 16, &b"secret"[..], &mut ct).unwrap();
        let mut pt = Vec::new();
        assert!(decrypt(&gen_key(), &ct[..], &mut pt).is_err());
    }

    #[test]
    fn tampering_is_detected() {
        let key = gen_key();
        let mut ct = Vec::new();
        encrypt(&key, 16, &[1u8; 50][..], &mut ct).unwrap();
        let last = ct.len() - 1;
        ct[last] ^= 1; // flip a bit in the final chunk
        let mut pt = Vec::new();
        assert!(decrypt(&key, &ct[..], &mut pt).is_err());
    }

    #[test]
    fn truncation_is_detected() {
        let key = gen_key();
        let mut ct = Vec::new();
        encrypt(&key, 16, &[1u8; 50][..], &mut ct).unwrap(); // multi-chunk
        ct.truncate(ct.len() / 2); // drop the tail, incl. the terminal chunk
        let mut pt = Vec::new();
        assert!(decrypt(&key, &ct[..], &mut pt).is_err());
    }

    #[test]
    fn key_fragment_round_trips() {
        let key = gen_key();
        assert_eq!(key_from_fragment(&key_to_fragment(&key)).unwrap(), key);
    }

    #[test]
    fn pbkdf2_matches_standard_vector() {
        // Known PBKDF2-HMAC-SHA256 vector (password="password", salt="salt",
        // 1 iteration, 32 bytes) — locks us to standard PBKDF2 so WebCrypto's
        // deriveBits with the same inputs is byte-identical.
        let mut key = [0u8; 32];
        pbkdf2::pbkdf2_hmac::<sha2::Sha256>(b"password", b"salt", 1, &mut key);
        let expect = [
            0x12, 0x0f, 0xb6, 0xcf, 0xfc, 0xf8, 0xb3, 0x2c, 0x43, 0xe7, 0x22, 0x52, 0x56, 0xc4,
            0xf8, 0x37, 0xa8, 0x65, 0x48, 0xc9, 0x2c, 0xcc, 0x35, 0x48, 0x08, 0x05, 0x98, 0x7c,
            0xb7, 0x0b, 0xe1, 0x7b,
        ];
        assert_eq!(key, expect);
    }

    #[test]
    fn derive_key_binds_pin_and_fragment() {
        let frag = [7u8; 32];
        // Same inputs → same key; different PIN or fragment → different key.
        assert_eq!(derive_key("4917", &frag), derive_key("4917", &frag));
        assert_ne!(derive_key("4917", &frag), derive_key("0000", &frag));
        assert_ne!(derive_key("4917", &frag), derive_key("4917", &[8u8; 32]));
    }

    #[test]
    fn meta_round_trips_and_rejects_wrong_secret() {
        let secret = [3u8; 32];
        let plaintext = br#"{"name":"q3 report.pdf","from":"Alex","msg":"the codes"}"#;
        let blob = encrypt_meta(&secret, plaintext);
        assert_eq!(decrypt_meta(&secret, &blob).unwrap(), plaintext);
        assert!(decrypt_meta(&[4u8; 32], &blob).is_err()); // wrong secret → fails
                                                           // Emit a fixture so the browser (WebCrypto) decryptor can be cross-checked.
        let fixture = serde_json::json!({
            "secret_hex": hex_lower(&secret),
            "blob_b64url": blob,
            "plaintext": String::from_utf8_lossy(plaintext),
        });
        let _ = std::fs::write("/tmp/dove-meta-fixture.json", fixture.to_string());
    }

    #[test]
    fn share_id_is_maced_and_deterministic() {
        let secret = crypto_secret();
        let nonce = [0x11u8; 8];
        let id = mint_share_id(&secret, &nonce);
        assert_eq!(id.len(), 32); // 8-byte nonce + 8-byte mac, hex
        assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
        // Deterministic; the first 8 bytes are the nonce.
        assert_eq!(mint_share_id(&secret, &nonce), id);
        assert_eq!(&id[..16], "1111111111111111");
        // A different secret produces a different mac (same nonce prefix).
        let other = mint_share_id(&[9u8; 32], &nonce);
        assert_eq!(&other[..16], "1111111111111111");
        assert_ne!(&other[16..], &id[16..]);
        // Emit a fixture so the Python gate's verifier can be cross-checked.
        let fixture = serde_json::json!({
            "secret_hex": hex_lower(&secret), "nonce_hex": hex_lower(&nonce), "id": id,
        });
        let _ = std::fs::write("/tmp/dove-macid-fixture.json", fixture.to_string());
    }

    fn crypto_secret() -> [u8; 32] {
        let mut s = [0u8; 32];
        for (i, b) in s.iter_mut().enumerate() {
            *b = i as u8;
        }
        s
    }

    #[test]
    fn hex_decode_round_trips() {
        assert_eq!(hex_decode("00ff10").unwrap(), vec![0x00, 0xff, 0x10]);
        assert_eq!(hex_decode("abc"), None); // odd length
        assert_eq!(hex_decode("zz"), None); // non-hex
    }

    #[test]
    fn pin_hash_is_stable_and_salted_by_id() {
        // Deterministic, and the id salts it so the same PIN hashes differently
        // per share (must match the Python gate's sha256(id ":" pin)).
        assert_eq!(pin_hash("abc123", "4917"), pin_hash("abc123", "4917"));
        assert_ne!(pin_hash("abc123", "4917"), pin_hash("def456", "4917"));
        assert_eq!(pin_hash("abc123", "4917").len(), 64);
    }
}