rust_ev_verifier_lib 0.4.5

Main library for the E-Voting system of Swiss Post.
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
// Copyright © 2025 Denis Morel
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License and
// a copy of the GNU General Public License along with this program. If not, see
// <https://www.gnu.org/licenses/>.

use crate::data_structures::dataset::DatasetTypeKind;
use chrono::Local;
use rust_ev_system_library::{
    chanel_security::stream::{StreamSymEncryptionError, get_stream_plaintext},
    rust_ev_crypto_primitives::prelude::{
        ByteArray, EncodeTrait,
        argon2::Argon2idParameters,
        basic_crypto_functions::{BasisCryptoError, sha256_stream},
    },
};
use std::{
    fs::{self, File},
    io::{self, BufReader, BufWriter},
    path::{Path, PathBuf},
};
use thiserror::Error;
use tracing::{instrument, trace};
use zip::result::ZipError;

#[derive(Error, Debug)]
#[error(transparent)]
/// Error with dataset
pub struct DatasetError(#[from] Box<DatasetErrorImpl>);

#[derive(Error, Debug)]
enum DatasetErrorImpl {
    #[error("Kind {0} delivered. Only context, setup and tally possible")]
    WrongKindStr(String),
    #[error("Error opening file {path} to calculate fingerprint")]
    IOFingerprint {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("Error calculating fingerprint of {path}")]
    Fingerprint {
        path: PathBuf,
        source: BasisCryptoError,
    },
    #[error("Path doesn't exists {0}")]
    PathNotExist(PathBuf),
    #[error("Path is not a file {0}")]
    PathNotFile(PathBuf),
    #[error("Path is not a directory {0}")]
    PathIsNotDir(PathBuf),
    #[error("IO Error form {path}: {msg}")]
    IO {
        path: PathBuf,
        msg: &'static str,
        source: std::io::Error,
    },
    #[error("Error new zipArchive {file}")]
    NewZipArchive { file: PathBuf, source: ZipError },
    #[error("Error extracting {file}: {msg}")]
    Extract {
        file: PathBuf,
        msg: String,
        source: std::io::Error,
    },
    #[error("process_dataset_operations: Error crreating EncryptedZipReader")]
    ProcessNewEncryptedZipReader { source: Box<DatasetError> },
    #[error("process_dataset_operations: Error unzipping")]
    ProcessUnzip { source: Box<DatasetError> },
    #[error("Error streaming the file {path}")]
    GetStreamPlaintext {
        path: PathBuf,
        source: StreamSymEncryptionError,
    },
}

/// Metadata containing the information of the zip dataset before and after extraction
#[derive(Debug, Clone)]
pub struct DatasetMetadata {
    dataset_kind: DatasetTypeKind,
    source_path: PathBuf,
    decrypted_zip_path: PathBuf,
    extracted_dir_path: PathBuf,
    fingerprint: ByteArray,
}

impl DatasetMetadata {
    /// New [DatasetMetadata]
    pub fn new(
        dataset_kind: DatasetTypeKind,
        source_path: &Path,
        decrypted_zip_path: &Path,
        extracted_dir_path: &Path,
        fingerprint: &ByteArray,
    ) -> Self {
        Self {
            dataset_kind,
            source_path: source_path.to_path_buf(),
            decrypted_zip_path: decrypted_zip_path.to_path_buf(),
            extracted_dir_path: extracted_dir_path.to_path_buf(),
            fingerprint: fingerprint.clone(),
        }
    }

    /// Source path
    pub fn source_path(&self) -> &Path {
        &self.source_path
    }

    /// Path of the zip decrypted
    pub fn decrypted_zip_path(&self) -> &Path {
        &self.decrypted_zip_path
    }

    /// Path of the folder containing the extracted files
    pub fn extracted_dir_path(&self) -> &Path {
        &self.extracted_dir_path
    }

    /// Fingerprint of the source encrypted zip
    pub fn fingerprint(&self) -> &ByteArray {
        &self.fingerprint
    }

    /// Fingerprint of the source encrypted zip as string (16 coding)
    pub fn fingerprint_str(&self) -> String {
        self.fingerprint().base16_encode().unwrap()
    }

    /// Kind of the dataset
    pub fn kind(&self) -> DatasetTypeKind {
        self.dataset_kind
    }

    /// Extract the data as datatype given with the kind of the dataset type.
    ///
    /// Return [DatasetMetadata] with the correct metadata or Error if something goes wrong
    pub fn extract_dataset_kind_with_inputs(
        kind: DatasetTypeKind,
        input: &Path,
        password: &str,
        extract_dir: &Path,
        zip_temp_dir_path: &Path,
    ) -> Result<Self, DatasetError> {
        Self::process_dataset_operations(kind, input, password, extract_dir, zip_temp_dir_path)
    }

    /// Extract the data as datatype give with the name of the dataset type.
    ///
    /// Return [DatasetMetadata] with the correct metadata or Error if something goes wrong
    pub fn extract_dataset_str_with_inputs(
        datasettype_str: &str,
        input: &Path,
        password: &str,
        extract_dir: &Path,
        zip_temp_dir_path: &Path,
    ) -> Result<Self, DatasetError> {
        Self::extract_dataset_kind_with_inputs(
            DatasetTypeKind::try_from(datasettype_str)
                .map_err(|_| DatasetErrorImpl::WrongKindStr(datasettype_str.to_string()))
                .map_err(|e| DatasetError(Box::new(e)))?,
            input,
            password,
            extract_dir,
            zip_temp_dir_path,
        )
    }

    fn calculate_fingerprint(input: &Path) -> Result<ByteArray, Box<DatasetErrorImpl>> {
        let f = std::fs::File::open(input).map_err(|e| DatasetErrorImpl::IOFingerprint {
            path: input.to_path_buf(),
            source: e,
        })?;
        let mut reader = std::io::BufReader::new(f);
        sha256_stream(&mut reader).map_err(|e| {
            Box::new(DatasetErrorImpl::Fingerprint {
                path: input.to_path_buf(),
                source: e,
            })
        })
    }

    /// Process all the operations
    ///
    /// - Decrypt the zip defined by `input` to the `zip_temp_dir_path` using the password
    /// - Extract the decrypted zip to `extract_dir`
    ///
    /// Return [Self] with the correct metadata or Error if something goes wrong
    #[instrument(skip(password))]
    pub fn process_dataset_operations(
        datasetkind: DatasetTypeKind,
        input: &Path,
        password: &str,
        extract_dir: &Path,
        zip_temp_dir_path: &Path,
    ) -> Result<Self, DatasetError> {
        Self::process_dataset_operations_impl(
            datasetkind,
            input,
            password,
            extract_dir,
            zip_temp_dir_path,
        )
        .map_err(DatasetError)
    }

    fn process_dataset_operations_impl(
        datasetkind: DatasetTypeKind,
        input: &Path,
        password: &str,
        extract_dir: &Path,
        zip_temp_dir_path: &Path,
    ) -> Result<Self, Box<DatasetErrorImpl>> {
        if !input.exists() {
            return Err(Box::new(DatasetErrorImpl::PathNotExist(
                input.to_path_buf(),
            )));
        }
        if !input.is_file() {
            return Err(Box::new(DatasetErrorImpl::PathNotFile(input.to_path_buf())));
        }
        if !extract_dir.is_dir() {
            return Err(Box::new(DatasetErrorImpl::PathIsNotDir(
                extract_dir.to_path_buf(),
            )));
        }
        if !zip_temp_dir_path.is_dir() {
            return Err(Box::new(DatasetErrorImpl::PathIsNotDir(
                zip_temp_dir_path.to_path_buf(),
            )));
        }
        trace!("Start process_dataset_operations");
        let fingerprint = Self::calculate_fingerprint(input)?;
        let extract_dir_with_context = extract_dir.join(datasetkind.as_ref());
        let mut reader = EncryptedZipReader::new(input, password, extract_dir, zip_temp_dir_path)
            .map_err(|e| DatasetErrorImpl::ProcessNewEncryptedZipReader {
            source: Box::new(e),
        })?;
        trace!("Zip decrypter");
        reader.unzip().map_err(|e| DatasetErrorImpl::ProcessUnzip {
            source: Box::new(e),
        })?;
        trace!("unzip finished");
        Ok(DatasetMetadata::new(
            datasetkind,
            input,
            &extract_dir_with_context,
            &reader.temp_zip,
            &fingerprint,
        ))
    }
}

/// Structure to decrypt the zip file and to extract the files
///
/// The zip will be first encrypted in the given location `target_dir`. The filename will extend with the word `encryption` and
/// the actual date time
///
/// In a second step, the extraction is done in the target directory (with strip away the topmost directory)
pub struct EncryptedZipReader {
    internal_reader: BufReader<File>,
    password: String,
    target_dir: PathBuf,
    temp_zip: PathBuf,
}

impl EncryptedZipReader {
    /// New Reader of encrypted zip
    ///
    /// # parameters
    /// - File: path of the source file
    /// - password: The password for the decryption
    /// - target_dir: The target directory to extract the files. The extraction will strip away the topmost directory
    /// - temp_zip_dir: Location to the store the encrypted zip file
    pub fn new(
        file: &Path,
        password: &str,
        target_dir: &Path,
        temp_zip_dir: &Path,
    ) -> Result<Self, DatasetError> {
        Self::new_impl(file, password, target_dir, temp_zip_dir).map_err(DatasetError)
    }

    fn new_impl(
        file: &Path,
        password: &str,
        target_dir: &Path,
        temp_zip_dir: &Path,
    ) -> Result<Self, Box<DatasetErrorImpl>> {
        let f = File::open(file).map_err(|e| DatasetErrorImpl::IO {
            path: file.to_path_buf(),
            msg: "Opening file",
            source: e,
        })?;
        let buf = BufReader::new(f);
        Ok(Self {
            internal_reader: buf,
            password: password.to_string(),
            target_dir: target_dir.to_path_buf(),
            temp_zip: Self::temp_zip_path(file, temp_zip_dir),
        })
    }

    fn decrypt_to_zip(&mut self) -> Result<PathBuf, Box<DatasetErrorImpl>> {
        let target = std::fs::File::create(&self.temp_zip).map_err(|e| DatasetErrorImpl::IO {
            path: self.temp_zip.clone(),
            msg: "Creating Temp Zip",
            source: e,
        })?;
        let mut target_writer = BufWriter::new(target);
        get_stream_plaintext(
            &mut self.internal_reader,
            &self.password,
            &ByteArray::default(),
            &mut target_writer,
            Argon2idParameters::default(),
        )
        .map_err(|e| DatasetErrorImpl::GetStreamPlaintext {
            path: self.temp_zip.clone(),
            source: e,
        })?;
        Ok(self.temp_zip.to_owned())
    }

    /// Decrypt and unzip the source file
    ///
    /// The method return the target directory
    pub fn unzip(&mut self) -> Result<PathBuf, DatasetError> {
        self.unzip_impl().map_err(DatasetError)
    }

    fn unzip_impl(&mut self) -> Result<PathBuf, Box<DatasetErrorImpl>> {
        if !self.temp_zip.exists() {
            self.decrypt_to_zip()?;
        }
        let f = std::fs::File::open(&self.temp_zip).map_err(|e| DatasetErrorImpl::IO {
            path: self.temp_zip.clone(),
            msg: "Opening temp zip file {}",
            source: e,
        })?;
        let buf_reader = std::io::BufReader::new(f);
        let mut zip =
            zip::ZipArchive::new(buf_reader).map_err(|e| DatasetErrorImpl::NewZipArchive {
                file: self.temp_zip.to_path_buf(),
                source: e,
            })?;

        // Explicitly implement the extraction to avoid problem between Windows and Linux (Backslashes)
        // Implementation is using the example: https://github.com/zip-rs/zip2/blob/master/examples/extract.rs
        for i in 0..zip.len() {
            let mut file = zip.by_index(i).unwrap();
            let outpath = file.mangled_name();
            let outpath = self.target_dir.join(outpath);
            if file.is_dir() {
                fs::create_dir_all(&outpath).map_err(|e| DatasetErrorImpl::Extract {
                    file: self.temp_zip.to_path_buf(),
                    msg: format!("Create dir {:?}", outpath),
                    source: e,
                })?;
            } else {
                if let Some(p) = outpath.parent()
                    && !p.exists()
                {
                    fs::create_dir_all(p).map_err(|e| DatasetErrorImpl::Extract {
                        file: self.temp_zip.to_path_buf(),
                        msg: format!("Create dir {:?}", p),
                        source: e,
                    })?;
                }
                let mut outfile =
                    fs::File::create(&outpath).map_err(|e| DatasetErrorImpl::Extract {
                        file: self.temp_zip.to_path_buf(),
                        msg: format!("Create file {:?}", outpath),
                        source: e,
                    })?;
                io::copy(&mut file, &mut outfile).map_err(|e| DatasetErrorImpl::Extract {
                    file: self.temp_zip.to_path_buf(),
                    msg: format!("Extract file {:?}", outpath),
                    source: e,
                })?;
            }
            // Get and Set permissions
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;

                if let Some(mode) = file.unix_mode() {
                    fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap();
                }
            }
        }

        // This is not working (backslash problem)
        /*zip.extract(&self.target_dir)
        .map_err(|e| DatasetErrorImpl::Extract {
            file: self.temp_zip.to_path_buf(),
            source: e,
        })?;*/
        Ok(self.target_dir.to_owned())
    }

    fn temp_zip_path(source: &Path, temp_zip_dir: &Path) -> PathBuf {
        let mut new_name = source.file_stem().unwrap().to_os_string();
        let now = Local::now().format("%Y%m%d-%H%M%S").to_string();
        new_name.push(format!(
            "-decrypted-{}.{}",
            now,
            source.extension().unwrap().to_str().unwrap()
        ));
        temp_zip_dir.join(new_name)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::config::test::{
        CONFIG_TEST, test_datasets_context_zip_path, test_datasets_path, test_decrypt_zip_password,
        test_temp_dir_path,
    };
    use std::ffi::OsString;

    #[test]
    fn test_temp_zip_path() {
        let f = PathBuf::from("./toto/12345.zip");
        let res = EncryptedZipReader::temp_zip_path(&f, &PathBuf::from("/abc/xyz"));
        assert_eq!(res.extension(), Some(OsString::from("zip").as_os_str()));
        assert_eq!(res.parent(), Some(PathBuf::from("/abc/xyz").as_path()));
    }

    #[test]
    #[ignore = "Test done in test_unzip. Avoid parallel test with error"]
    fn test_decrypt_zip() {
        let path = test_datasets_context_zip_path();
        let mut zip_reader = EncryptedZipReader::new(
            &path,
            test_decrypt_zip_password(),
            &test_datasets_path(),
            &CONFIG_TEST.zip_temp_dir_path(),
        )
        .unwrap();
        let decrypt_res = zip_reader.decrypt_to_zip();
        let res_path = decrypt_res.unwrap();
        assert_eq!(
            res_path.extension(),
            Some(OsString::from("zip").as_os_str())
        );
        assert_eq!(
            res_path.parent(),
            Some(CONFIG_TEST.zip_temp_dir_path().as_path())
        );
    }

    #[test]
    fn test_decryt_and_unzip() {
        let path = test_datasets_context_zip_path();
        let subdir_time =
            test_temp_dir_path().join(Local::now().format("%Y%m%d-%H%M%S").to_string());
        let _ = std::fs::create_dir(&subdir_time);
        let target_dir = subdir_time;
        let mut zip_reader = EncryptedZipReader::new(
            &path,
            test_decrypt_zip_password(),
            &target_dir,
            &CONFIG_TEST.zip_temp_dir_path(),
        )
        .unwrap();
        let unzip_res = zip_reader.unzip();
        let path_res = unzip_res.unwrap();
        assert_eq!(path_res, target_dir);
        assert!(path_res.join("context").exists());
        assert!(!path_res.join("context").join("context").exists());
    }
}