system_image/
path_hash_mapping.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
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
// 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 crate::errors::PathHashMappingError;
use fuchsia_hash::Hash;
use fuchsia_pkg::PackagePath;
use std::io::{self, BufRead as _};
use std::marker::PhantomData;
use std::str::FromStr as _;

/// PhantomData type marker to indicate a `PathHashMapping` is a "data/static_packages" file.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Static;

/// PhantomData type marker to indicate a `PathHashMapping` is a "data/bootfs_packages" file.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Bootfs;

pub type StaticPackages = PathHashMapping<Static>;

/// A `PathHashMapping` reads and writes line-oriented "{package_path}={hash}\n" files, e.g.
/// "data/static_packages".
/// Deprecated.
#[derive(Debug, PartialEq, Eq)]
pub struct PathHashMapping<T> {
    contents: Vec<(PackagePath, Hash)>,
    phantom: PhantomData<T>,
}

impl<T> PathHashMapping<T> {
    /// Reads the line-oriented "package-path=hash" static_packages or cache_packages file.
    /// Validates the package paths and hashes.
    pub fn deserialize(reader: impl io::Read) -> Result<Self, PathHashMappingError> {
        let reader = io::BufReader::new(reader);
        let mut contents = vec![];
        for line in reader.lines() {
            let line = line?;
            let i = line.rfind('=').ok_or_else(|| PathHashMappingError::EntryHasNoEqualsSign {
                entry: line.clone(),
            })?;
            let hash = Hash::from_str(&line[i + 1..])?;
            let path = line[..i].parse()?;
            contents.push((path, hash));
        }
        Ok(Self { contents, phantom: PhantomData })
    }

    /// Iterator over the contents of the mapping.
    pub fn contents(&self) -> impl ExactSizeIterator<Item = &(PackagePath, Hash)> {
        self.contents.iter()
    }

    /// Iterator over the contents of the mapping, consuming self.
    pub fn into_contents(self) -> impl ExactSizeIterator<Item = (PackagePath, Hash)> {
        self.contents.into_iter()
    }

    /// Iterator over the contained hashes.
    pub fn hashes(&self) -> impl Iterator<Item = &Hash> {
        self.contents.iter().map(|(_, hash)| hash)
    }

    /// Get the hash for a package.
    pub fn hash_for_package(&self, path: &PackagePath) -> Option<Hash> {
        self.contents.iter().find_map(|(n, hash)| if n == path { Some(*hash) } else { None })
    }

    /// Create a `PathHashMapping` from a `Vec` of `(PackagePath, Hash)` pairs.
    pub fn from_entries(entries: Vec<(PackagePath, Hash)>) -> Self {
        Self { contents: entries, phantom: PhantomData }
    }

    /// Write a `static_packages` or `cache_packages` file.
    pub fn serialize(&self, mut writer: impl io::Write) -> Result<(), PathHashMappingError> {
        for entry in self.contents.iter() {
            writeln!(&mut writer, "{}={}", entry.0, entry.1)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;
    use fuchsia_pkg::test::random_package_path;
    use proptest::prelude::*;

    #[test]
    fn deserialize_empty_file() {
        let empty = Vec::new();
        let static_packages = StaticPackages::deserialize(empty.as_slice()).unwrap();
        assert_eq!(static_packages.hashes().count(), 0);
    }

    #[test]
    fn deserialize_valid_file_list_hashes() {
        let bytes =
            "name/variant=0000000000000000000000000000000000000000000000000000000000000000\n\
             other-name/other-variant=1111111111111111111111111111111111111111111111111111111111111111\n"
                .as_bytes();
        let static_packages = StaticPackages::deserialize(bytes).unwrap();
        assert_eq!(
            static_packages.hashes().cloned().collect::<Vec<_>>(),
            vec![
                "0000000000000000000000000000000000000000000000000000000000000000".parse().unwrap(),
                "1111111111111111111111111111111111111111111111111111111111111111".parse().unwrap()
            ]
        );
    }

    #[test]
    fn deserialze_rejects_invalid_package_path() {
        let bytes =
            "name/=0000000000000000000000000000000000000000000000000000000000000000\n".as_bytes();
        let res = StaticPackages::deserialize(bytes);
        assert_matches!(res, Err(PathHashMappingError::ParsePackagePath(_)));
    }

    #[test]
    fn deserialize_rejects_invalid_hash() {
        let bytes = "name/variant=invalid-hash\n".as_bytes();
        let res = StaticPackages::deserialize(bytes);
        assert_matches!(res, Err(PathHashMappingError::ParseHash(_)));
    }

    #[test]
    fn deserialize_rejects_missing_equals() {
        let bytes =
            "name/variant~0000000000000000000000000000000000000000000000000000000000000000\n"
                .as_bytes();
        let res = StaticPackages::deserialize(bytes);
        assert_matches!(res, Err(PathHashMappingError::EntryHasNoEqualsSign { .. }));
    }

    #[test]
    fn from_entries_serialize() {
        let static_packages = StaticPackages::from_entries(vec![(
            PackagePath::from_name_and_variant("name0".parse().unwrap(), "0".parse().unwrap()),
            "0000000000000000000000000000000000000000000000000000000000000000".parse().unwrap(),
        )]);

        let mut serialized = vec![];
        static_packages.serialize(&mut serialized).unwrap();
        assert_eq!(
            serialized,
            &b"name0/0=0000000000000000000000000000000000000000000000000000000000000000\n"[..]
        );
    }

    #[test]
    fn hash_for_package_success() {
        let bytes =
            "name/variant=0000000000000000000000000000000000000000000000000000000000000000\n\
             "
            .as_bytes();
        let static_packages = StaticPackages::deserialize(bytes).unwrap();
        let res = static_packages.hash_for_package(&PackagePath::from_name_and_variant(
            "name".parse().unwrap(),
            "variant".parse().unwrap(),
        ));
        assert_eq!(
            res,
            Some(
                "0000000000000000000000000000000000000000000000000000000000000000".parse().unwrap(),
            )
        );
    }

    #[test]
    fn hash_for_missing_package_is_none() {
        let bytes =
            "name/variant=0000000000000000000000000000000000000000000000000000000000000000\n\
             "
            .as_bytes();
        let static_packages = StaticPackages::deserialize(bytes).unwrap();
        let res = static_packages.hash_for_package(&PackagePath::from_name_and_variant(
            "nope".parse().unwrap(),
            "variant".parse().unwrap(),
        ));
        assert_eq!(res, None);
    }

    prop_compose! {
        fn random_hash()(s in "[A-Fa-f0-9]{64}") -> Hash {
            s.parse().unwrap()
        }
    }

    prop_compose! {
        fn random_static_packages()
            (vec in prop::collection::vec(
                (random_package_path(), random_hash()), 0..4)
            ) -> PathHashMapping<Static> {
                StaticPackages::from_entries(vec)
            }
    }

    proptest! {
        #[test]
        fn serialize_deserialize_identity(static_packages in random_static_packages()) {
            let mut serialized = vec![];
            static_packages.serialize(&mut serialized).unwrap();
            let deserialized = StaticPackages::deserialize(serialized.as_slice()).unwrap();
            prop_assert_eq!(
                static_packages,
                deserialized
            );
        }
    }
}