vector-core 0.12.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
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
//! Attachment AES-256-GCM over a file, a chunk at a time: the cipher of
//! [`super::decrypt_data`] (16-byte nonce, 16-byte tag appended) without the file
//! ever sitting whole in memory.
//!
//! GCM is CTR encryption plus a GHASH over the ciphertext, and both run
//! incrementally. The catch is that the tag only speaks at the end, so plaintext
//! is written to a file the caller keeps out of sight until this returns Ok.

use std::io::{Read, Write};
use std::path::Path;

use super::gcm;
use zeroize::Zeroize;
use super::sha256::Sha256;

use super::hex;

/// Read size for every streamed pass. A multiple of the 16-byte GHASH block, so
/// only the final read can leave a partial block.
const CHUNK: usize = 1 << 20;

/// What one pass over a downloaded file learned.
#[derive(Debug)]
pub struct StreamedFile {
    /// SHA-256 of the file as downloaded: a Blossom URL's content address.
    pub source_sha256: String,
    /// SHA-256 of what was written out: the attachment's identity.
    pub output_sha256: String,
    pub output_len: u64,
}

/// What a pass stopped by its caller returns.
pub const CANCELLED: &str = "Upload cancelled";

/// Tell `progress` when `done` of `total` reaches a new whole percentage; false when
/// it asks the pass to stop.
fn report(done: u64, total: u64, reported: &mut u8, progress: &mut dyn FnMut(u8) -> bool) -> bool {
    let pct = done.saturating_mul(100).checked_div(total).map_or(100, |p| p.min(100) as u8);
    if pct > *reported {
        *reported = pct;
        return progress(pct);
    }
    true
}

fn hex32(bytes: &[u8]) -> String {
    hex::encode(bytes)
}

/// Decrypt `src` (ciphertext || tag) into `dst`, hashing both sides on the way.
/// `dst` holds unauthenticated plaintext until this returns: on any error it is
/// removed, and a tag mismatch is reported as a decryption failure.
pub fn decrypt_file(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str) -> Result<StreamedFile, String> {
    decrypt_file_with_progress(src, dst, key_hex, nonce_hex, &mut |_| true)
}

/// [`decrypt_file`], telling `progress` each new whole percentage of the file opened.
/// `progress` answering false stops the pass, as for [`encrypt_file_with_progress`].
pub fn decrypt_file_with_progress(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<StreamedFile, String> {
    let result = decrypt_file_inner(src, Some(dst), key_hex, nonce_hex, progress);
    if result.is_err() {
        let _ = std::fs::remove_file(dst);
    }
    result
}

/// What [`decrypt_file`] learns about `src`, with no plaintext written anywhere: the tag
/// verdict, both hashes and the length. For ciphertext that stays ciphertext on disk.
pub fn verify_file(src: &Path, key_hex: &str, nonce_hex: &str) -> Result<StreamedFile, String> {
    verify_file_with_progress(src, key_hex, nonce_hex, &mut |_| true)
}

/// [`verify_file`], reporting progress as [`decrypt_file_with_progress`] does.
pub fn verify_file_with_progress(src: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<StreamedFile, String> {
    decrypt_file_inner(src, None, key_hex, nonce_hex, progress)
}

/// Encrypt `src` into `dst` (ciphertext || tag), the counterpart of [`decrypt_file`].
/// Returns the SHA-256 and length of what was written: the blob a server will hold.
pub fn encrypt_file(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str) -> Result<(String, u64), String> {
    encrypt_file_with_progress(src, dst, key_hex, nonce_hex, &mut |_| true)
}

/// [`encrypt_file`], telling `progress` each new whole percentage of the file sealed.
/// `progress` answering false stops the pass: nothing is written and the error says
/// it was cancelled.
pub fn encrypt_file_with_progress(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<(String, u64), String> {
    let result = encrypt_file_inner(src, dst, key_hex, nonce_hex, progress);
    if result.is_err() {
        let _ = std::fs::remove_file(dst);
    }
    result.map(|(blob, len, _)| (blob, len))
}

/// What opening says when the bytes aren't the ones sealed under that key.
pub const TAG_MISMATCH: &str = "Decryption failed: aead::Error (authentication tag mismatch)";

/// What a send says when its file changed between being hashed and being sealed.
pub const CHANGED: &str = "The file changed while it was being sent. Attach it again to send it.";

/// [`encrypt_file_with_progress`] for a file the sender may still change: the bytes sealed
/// must be the ones hashed as `plain_sha256`, or nothing is written and the send says so.
pub fn encrypt_file_matching(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, plain_sha256: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<(String, u64), String> {
    let result = encrypt_file_inner(src, dst, key_hex, nonce_hex, progress).and_then(|(blob, len, plain)| {
        if plain == plain_sha256 { Ok((blob, len)) } else { Err(CHANGED.to_string()) }
    });
    if result.is_err() {
        let _ = std::fs::remove_file(dst);
    }
    result
}

/// GCM's limit for one message (2^36 - 32 bytes): past it the 32-bit counter wraps and
/// the keystream repeats.
const GCM_MAX_PLAINTEXT: u64 = (1 << 36) - 32;

fn encrypt_file_inner(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<(String, u64, String), String> {
    let (mut key, nonce) = super::attachment_params(key_hex, nonce_hex, "Invalid decryption key")?;
    let mut input = std::fs::File::open(src).map_err(|e| format!("open file: {e}"))?;
    let total = input.metadata().map(|m| m.len()).unwrap_or(0);
    if total > GCM_MAX_PLAINTEXT {
        return Err("File too large to encrypt as one attachment (over 64 GiB)".to_string());
    }
    let mut gcm = gcm::Stream::new(&key, &nonce);
    key.zeroize();
    let mut reported = 0u8;
    let mut output = std::io::BufWriter::with_capacity(
        CHUNK,
        std::fs::File::create(dst).map_err(|e| format!("create ciphertext: {e}"))?,
    );
    let mut blob_hash = Sha256::new();
    let mut plain_hash = Sha256::new();
    let mut buf = vec![0u8; CHUNK];
    let mut len = 0u64;
    loop {
        // Fill the buffer before encrypting: GHASH may only pad the final block.
        let mut n = 0;
        while n < CHUNK {
            let got = input.read(&mut buf[n..]).map_err(|e| format!("read file: {e}"))?;
            if got == 0 {
                break;
            }
            n += got;
        }
        if n == 0 {
            break;
        }
        let chunk = &mut buf[..n];
        plain_hash.update(&*chunk);
        gcm.encrypt(chunk);
        blob_hash.update(&*chunk);
        output.write_all(chunk).map_err(|e| format!("write ciphertext: {e}"))?;
        len += n as u64;
        if !report(len, total, &mut reported, progress) {
            return Err(CANCELLED.to_string());
        }
        if n < CHUNK {
            break;
        }
    }
    let tag = gcm.finish();
    blob_hash.update(tag);
    output.write_all(&tag).map_err(|e| format!("write ciphertext: {e}"))?;
    let file = output.into_inner().map_err(|e| format!("write ciphertext: {e}"))?;
    file.sync_all().map_err(|e| format!("sync ciphertext: {e}"))?;
    Ok((hex32(&blob_hash.finalize()), len + 16, hex32(&plain_hash.finalize())))
}

fn decrypt_file_inner(src: &Path, dst: Option<&Path>, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<StreamedFile, String> {
    let (mut key, nonce) = super::attachment_params(key_hex, nonce_hex, "Invalid decryption key")?;
    let mut input = std::fs::File::open(src).map_err(|e| format!("open download: {e}"))?;
    let total = input.metadata().map_err(|e| format!("stat download: {e}"))?.len();
    if total < 16 {
        return Err(format!("Invalid Input: encrypted data too small ({} bytes, minimum 16 bytes required for authentication tag)", total));
    }
    let ciphertext_len = total - 16;
    if ciphertext_len > GCM_MAX_PLAINTEXT {
        return Err("Invalid Input: encrypted data exceeds the AES-GCM limit".to_string());
    }
    let mut gcm = gcm::Stream::new(&key, &nonce);
    key.zeroize();
    let mut reported = 0u8;

    let mut source_hash = Sha256::new();
    let mut output_hash = Sha256::new();
    let mut output = match dst {
        Some(dst) => Some(std::io::BufWriter::with_capacity(
            CHUNK,
            std::fs::File::create(dst).map_err(|e| format!("create output: {e}"))?,
        )),
        None => None,
    };

    let mut buf = vec![0u8; CHUNK];
    let mut remaining = ciphertext_len;
    while remaining > 0 {
        let n = remaining.min(CHUNK as u64) as usize;
        let chunk = &mut buf[..n];
        input.read_exact(chunk).map_err(|e| format!("read download: {e}"))?;
        source_hash.update(&*chunk);
        gcm.decrypt(chunk);
        output_hash.update(&*chunk);
        if let Some(output) = output.as_mut() {
            output.write_all(chunk).map_err(|e| format!("write output: {e}"))?;
        }
        remaining -= n as u64;
        if !report(ciphertext_len - remaining, ciphertext_len, &mut reported, progress) {
            return Err(CANCELLED.to_string());
        }
    }

    let mut tag = [0u8; 16];
    input.read_exact(&mut tag).map_err(|e| format!("read download: {e}"))?;
    source_hash.update(tag);

    if !gcm::tags_equal(&gcm.finish(), &tag) {
        return Err(TAG_MISMATCH.to_string());
    }

    if let Some(output) = output {
        let file = output.into_inner().map_err(|e| format!("write output: {e}"))?;
        file.sync_all().map_err(|e| format!("sync output: {e}"))?;
    }
    Ok(StreamedFile {
        source_sha256: hex32(&source_hash.finalize()),
        output_sha256: hex32(&output_hash.finalize()),
        output_len: ciphertext_len,
    })
}

/// SHA-256 of a file, read a chunk at a time.
pub fn hash_file(path: &Path) -> Result<(String, u64), String> {
    let mut file = std::fs::File::open(path).map_err(|e| format!("open: {e}"))?;
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; CHUNK];
    let mut len = 0u64;
    loop {
        let n = file.read(&mut buf).map_err(|e| format!("read: {e}"))?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
        len += n as u64;
    }
    Ok((hex32(&hasher.finalize()), len))
}

/// Put a verified download into the download directory under `name`: an identical
/// file already there (same name, size and hash) is reused and `src` dropped;
/// otherwise `src` moves to a free spelling of the name. Returns where it landed.
pub fn place_download(src: &Path, file_hash: &str, len: u64, name: &str, extension: &str) -> Result<std::path::PathBuf, String> {
    let dir = crate::db::get_download_dir();
    std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create directory: {}", e))?;
    let target_name = if name.is_empty() { format!("{}.{}", file_hash, extension) } else { name.to_string() };
    // One plain component, or nothing: the name and extension come from the sender.
    let mut parts = Path::new(&target_name).components();
    if !matches!((parts.next(), parts.next()), (Some(std::path::Component::Normal(_)), None))
        || target_name.contains(['/', '\\'])
    {
        return Err("Refusing a download name outside the download folder".to_string());
    }

    let candidate = dir.join(&target_name);
    let identical = std::fs::metadata(&candidate).map(|m| m.len() == len).unwrap_or(false)
        && hash_file(&candidate).map(|(h, _)| h == file_hash).unwrap_or(false);
    if identical {
        let _ = std::fs::remove_file(src);
        return Ok(candidate);
    }

    let dest = crate::crypto::resolve_unique_filename(&dir, &target_name);
    // A rename can't cross filesystems (app storage to shared storage on Android):
    // copy beside the destination, then rename that into place.
    if std::fs::rename(src, &dest).is_err() {
        let staging = dir.join(format!(".{}.{}.tmp", file_hash, extension));
        let copied = std::fs::copy(src, &staging)
            .map_err(|e| format!("Failed to write file: {}", e))
            .and_then(|_| std::fs::File::open(&staging).and_then(|f| f.sync_all()).map_err(|e| format!("Failed to write file: {}", e)))
            .and_then(|_| std::fs::rename(&staging, &dest).map_err(|e| format!("Failed to rename file: {}", e)));
        if let Err(e) = copied {
            let _ = std::fs::remove_file(&staging);
            return Err(e);
        }
        let _ = std::fs::remove_file(src);
    }
    Ok(dest)
}

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

    fn scratch(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("vector-stream-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn a_download_never_lands_outside_its_folder() {
        let dir = scratch("escape");
        let src = dir.join("plain");
        std::fs::write(&src, b"x").unwrap();
        for bad in ["..\\..\\evil.bat", "../evil", "sub/evil", ".."] {
            assert!(place_download(&src, "abc", 1, bad, "bin").is_err(), "{bad}");
        }
        assert!(place_download(&src, "abc", 1, "", "..\\evil").is_err());
    }

    fn roundtrip(len: usize) {
        let dir = scratch(&format!("rt{len}"));
        let plain: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();
        let params = crate::crypto::generate_encryption_params();
        let sealed = crate::crypto::encrypt_data(&plain, &params).unwrap();
        let (src, dst) = (dir.join("in"), dir.join("out"));
        std::fs::write(&src, &sealed).unwrap();

        let got = decrypt_file(&src, &dst, &params.key, &params.nonce).unwrap();
        assert_eq!(std::fs::read(&dst).unwrap(), plain, "same plaintext as the one-shot cipher at {len} bytes");
        assert_eq!(got.output_sha256, crate::crypto::sha256_hex(&plain));
        assert_eq!(got.source_sha256, crate::crypto::sha256_hex(&sealed));
        assert_eq!(got.output_len, len as u64);
    }

    #[test]
    fn it_matches_the_one_shot_cipher_across_chunk_and_block_edges() {
        for len in [0, 1, 15, 16, 17, CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK + 7] {
            roundtrip(len);
        }
    }

    #[test]
    fn a_verify_pass_learns_what_a_decrypt_does_and_writes_nothing() {
        for len in [0usize, 17, CHUNK + 1] {
            let dir = scratch(&format!("verify{len}"));
            let plain: Vec<u8> = (0..len).map(|i| (i * 13 % 241) as u8).collect();
            let params = crate::crypto::generate_encryption_params();
            let sealed = crate::crypto::encrypt_data(&plain, &params).unwrap();
            let src = dir.join("blob");
            std::fs::write(&src, &sealed).unwrap();

            let got = verify_file(&src, &params.key, &params.nonce).unwrap();
            assert_eq!(got.output_sha256, crate::crypto::sha256_hex(&plain));
            assert_eq!(got.source_sha256, crate::crypto::sha256_hex(&sealed));
            assert_eq!(got.output_len, len as u64);
            let left: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
            assert_eq!(left, vec![std::ffi::OsString::from("blob")], "nothing beside the blob at {len} bytes");
        }
    }

    #[test]
    fn a_verify_pass_refuses_a_wrong_key_tamper_and_truncation() {
        let dir = scratch("verifybad");
        let plain = vec![0x42u8; CHUNK + 33];
        let params = crate::crypto::generate_encryption_params();
        let sealed = crate::crypto::encrypt_data(&plain, &params).unwrap();
        let src = dir.join("blob");

        let mut tampered = sealed.clone();
        tampered[CHUNK + 3] ^= 1;
        std::fs::write(&src, &tampered).unwrap();
        assert!(verify_file(&src, &params.key, &params.nonce).unwrap_err().contains("aead"));

        std::fs::write(&src, &sealed[..sealed.len() - 1]).unwrap();
        assert!(verify_file(&src, &params.key, &params.nonce).is_err(), "a truncated blob");
        std::fs::write(&src, &sealed[..10]).unwrap();
        assert!(verify_file(&src, &params.key, &params.nonce).is_err(), "shorter than its tag");

        std::fs::write(&src, &sealed).unwrap();
        let other = crate::crypto::generate_encryption_params();
        assert!(verify_file(&src, &other.key, &params.nonce).unwrap_err().contains("aead"));
        let mut stop = |pct: u8| pct < 50;
        assert_eq!(verify_file_with_progress(&src, &params.key, &params.nonce, &mut stop).unwrap_err(), CANCELLED);
        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "only the blob, whatever happened");
    }

    #[test]
    fn a_file_changed_after_hashing_is_never_sealed() {
        let dir = scratch("matching");
        let (src, sealed) = (dir.join("plain"), dir.join("sealed"));
        std::fs::write(&src, b"what was hashed").unwrap();
        let hash = crate::crypto::sha256_hex(b"what was hashed");
        let params = crate::crypto::generate_encryption_params();
        assert!(encrypt_file_matching(&src, &sealed, &params.key, &params.nonce, &hash, &mut |_| true).is_ok());
        std::fs::write(&src, b"what was hashed, then edited").unwrap();
        assert_eq!(encrypt_file_matching(&src, &sealed, &params.key, &params.nonce, &hash, &mut |_| true).unwrap_err(), CHANGED);
        assert!(!sealed.exists(), "nothing is left to upload");
    }

    #[test]
    fn a_streamed_seal_opens_with_the_one_shot_cipher() {
        for len in [0usize, 1, 16, 17, CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK + 7] {
            let dir = scratch(&format!("enc{len}"));
            let plain: Vec<u8> = (0..len).map(|i| (i * 7 % 253) as u8).collect();
            let (src, sealed) = (dir.join("plain"), dir.join("sealed"));
            std::fs::write(&src, &plain).unwrap();
            let params = crate::crypto::generate_encryption_params();
            let (hash, sealed_len) = encrypt_file(&src, &sealed, &params.key, &params.nonce).unwrap();
            let blob = std::fs::read(&sealed).unwrap();
            assert_eq!(blob, crate::crypto::encrypt_data(&plain, &params).unwrap(), "byte for byte at {len} bytes");
            assert_eq!((hash, sealed_len), (crate::crypto::sha256_hex(&blob), blob.len() as u64));
        }
    }

    #[test]
    fn a_stopped_pass_ends_early_and_leaves_nothing() {
        let dir = scratch("stop");
        let (src, sealed, opened) = (dir.join("plain"), dir.join("sealed"), dir.join("opened"));
        std::fs::write(&src, vec![3u8; 4 * CHUNK]).unwrap();
        let params = crate::crypto::generate_encryption_params();
        let mut seen = 0;
        let err = encrypt_file_with_progress(&src, &sealed, &params.key, &params.nonce, &mut |pct| { seen = pct; pct < 25 }).unwrap_err();
        assert_eq!(err, CANCELLED);
        assert!(seen < 100 && !sealed.exists(), "stopped at {seen}%, nothing left behind");

        encrypt_file(&src, &sealed, &params.key, &params.nonce).unwrap();
        let err = decrypt_file_with_progress(&sealed, &opened, &params.key, &params.nonce, &mut |pct| pct < 50).unwrap_err();
        assert_eq!(err, CANCELLED);
        assert!(!opened.exists(), "no half-opened plaintext");
    }

    #[test]
    fn a_flipped_byte_fails_and_leaves_no_plaintext() {
        let dir = scratch("tamper");
        let params = crate::crypto::generate_encryption_params();
        let mut sealed = crate::crypto::encrypt_data(&vec![7u8; 5000], &params).unwrap();
        sealed[2500] ^= 1;
        let (src, dst) = (dir.join("in"), dir.join("out"));
        std::fs::write(&src, &sealed).unwrap();
        let err = decrypt_file(&src, &dst, &params.key, &params.nonce).unwrap_err();
        assert!(err.contains("aead"), "reads as a decryption failure: {err}");
        assert!(!dst.exists(), "unauthenticated plaintext must not survive");
    }

    #[test]
    fn a_wrong_key_fails() {
        let dir = scratch("key");
        let params = crate::crypto::generate_encryption_params();
        let sealed = crate::crypto::encrypt_data(b"hello", &params).unwrap();
        let (src, dst) = (dir.join("in"), dir.join("out"));
        std::fs::write(&src, &sealed).unwrap();
        let other = crate::crypto::generate_encryption_params();
        assert!(decrypt_file(&src, &dst, &other.key, &params.nonce).is_err());
    }

    #[test]
    fn hash_file_matches_the_in_memory_hash() {
        let dir = scratch("hash");
        let data: Vec<u8> = (0..(CHUNK + 5)).map(|i| i as u8).collect();
        std::fs::write(dir.join("f"), &data).unwrap();
        assert_eq!(hash_file(&dir.join("f")).unwrap(), (crate::crypto::sha256_hex(&data), data.len() as u64));
    }
}