update_package/
hash.rs

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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use fidl_fuchsia_io as fio;
use fuchsia_hash::Hash;
use thiserror::Error;

/// An error encountered while extracting the package hash.
#[derive(Debug, Error)]
#[allow(missing_docs)]
pub enum HashError {
    #[error("opening the 'meta' file")]
    Open(#[source] fuchsia_fs::node::OpenError),

    #[error("reading the 'meta' file")]
    Read(#[source] fuchsia_fs::file::ReadError),

    #[error("parsing the 'meta' file")]
    Parse(#[source] fuchsia_hash::ParseHashError),
}

pub(crate) async fn hash(proxy: &fio::DirectoryProxy) -> Result<Hash, HashError> {
    let meta = fuchsia_fs::directory::open_file(proxy, "meta", fio::PERM_READABLE)
        .await
        .map_err(HashError::Open)?;
    let contents = fuchsia_fs::file::read_to_string(&meta).await.map_err(HashError::Read)?;
    contents.parse::<Hash>().map_err(HashError::Parse)
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use fuchsia_async as fasync;
    use fuchsia_fs::directory::open_in_namespace;
    use std::fs::File;
    use std::io::Write as _;
    use tempfile::tempdir;

    #[fasync::run_singlethreaded(test)]
    async fn open_error() {
        let temp_dir = tempdir().expect("/tmp to exist");
        let proxy = open_in_namespace(temp_dir.path().to_str().unwrap(), fio::PERM_READABLE)
            .expect("temp dir to open");

        assert_matches!(hash(&proxy).await, Err(HashError::Open(_)));
    }

    #[fasync::run_singlethreaded(test)]
    async fn parse_error() {
        let temp_dir = tempdir().expect("/tmp to exist");
        File::create(temp_dir.path().join("meta")).unwrap();
        let proxy = open_in_namespace(temp_dir.path().to_str().unwrap(), fio::PERM_READABLE)
            .expect("temp dir to open");

        assert_matches!(hash(&proxy).await, Err(HashError::Parse(_)));
    }

    #[fasync::run_singlethreaded(test)]
    async fn success() {
        let temp_dir = tempdir().expect("/tmp to exist");
        let mut meta = File::create(temp_dir.path().join("meta")).unwrap();
        let hex = "0000000000000000000000000000000000000000000000000000000000000000";
        meta.write_all(hex.as_bytes()).unwrap();
        let proxy = open_in_namespace(temp_dir.path().to_str().unwrap(), fio::PERM_READABLE)
            .expect("temp dir to open");

        assert_matches!(hash(&proxy).await, Ok(hash) if hash == hex.parse().unwrap());
    }
}