-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
190 lines (160 loc) · 6.18 KB
/
lib.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
// Copyright (C) 2020 O.S. Systems Sofware LTDA
//
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
pub use serde_json::Error as ParsingError;
pub mod prelude {
pub use super::{AppImpl, LocalClientImpl, RemoteClientImpl};
}
#[async_trait::async_trait(?Send)]
pub trait LocalClientImpl: Sized {
type Err: std::fmt::Debug;
fn new() -> Self;
async fn fetch_info(&mut self) -> Result<Info, Self::Err>;
}
#[async_trait::async_trait(?Send)]
pub trait RemoteClientImpl: Sized {
type Err;
fn new(url: &str) -> Self;
async fn fetch_package(&mut self) -> Result<Option<(Package, Signature)>, Self::Err>;
}
#[async_trait::async_trait(?Send)]
pub trait AppImpl: Sized {
type RemoteClient: RemoteClientImpl;
type Err: From<<Self::RemoteClient as RemoteClientImpl>::Err> + std::fmt::Debug;
fn new(client: Self::RemoteClient) -> Self;
fn serve(&mut self) -> Result<(), Self::Err>;
async fn map_info<F: FnOnce(&mut Info)>(&mut self, f: F) -> Result<(), Self::Err>;
async fn client(&mut self) -> Result<&mut Self::RemoteClient, Self::Err>;
async fn process(&mut self) -> Result<(), Self::Err> {
match self.client().await?.fetch_package().await? {
None => {}
Some((pkg, sig)) => {
if sig.validate(&pkg) {
self.map_info(move |info| info.current_version = pkg.version).await?;
return Ok(());
}
self.map_info(move |info| info.count_invalid_packages += 1).await?;
}
}
Ok(())
}
}
pub async fn run<C: LocalClientImpl, A: AppImpl>(mut client: C, mut app: A) {
app.serve().unwrap(); // Start serving the app for the local client
// Give time for the server to actually start
std::thread::sleep(std::time::Duration::from_secs(1));
let info = client.fetch_info().await.unwrap();
assert_eq!(info, Info::default(), "Info should be default as nothing has run so far");
app.process().await.unwrap();
let info = client.fetch_info().await.unwrap();
assert_eq!(info, Info::default(), "Info should still be default as update will not apply yet");
app.process().await.unwrap();
let info = client.fetch_info().await.unwrap();
assert_eq!(
info,
Info { current_version: String::from("0.0.2"), count_invalid_packages: 0 },
"Info should show the updated current_version"
);
app.process().await.unwrap();
let info = client.fetch_info().await.unwrap();
assert_eq!(
info,
Info { current_version: String::from("0.0.2"), count_invalid_packages: 1 },
"Info should show the updated current_version with the updated count of invalid packages"
);
app.process().await.unwrap();
let info = client.fetch_info().await.unwrap();
assert_eq!(
info,
Info { current_version: String::from("0.0.2"), count_invalid_packages: 2 },
"Info should show increase in the count of invalid packages"
);
}
pub fn start_remote_mock() -> (String, Vec<mockito::Mock>) {
let mut guards = Vec::default();
let body = Package::default().raw;
guards.push(mockito::mock("GET", "/").with_status(404).create());
guards.push(
mockito::mock("GET", "/")
.with_status(200)
.with_header("signature", Signature::VALID_SAMPLE)
.with_body(&body)
.create(),
);
guards.push(
mockito::mock("GET", "/")
.with_status(200)
.with_header("signature", Signature::INVALID_SAMPLE)
.with_body(&body)
.expect_at_least(2)
.create(),
);
(mockito::server_url(), guards)
}
#[derive(Debug)]
pub struct Signature(pub Vec<u8>);
impl Signature {
pub const INVALID_SAMPLE: &'static str = r#"Hx6kv5dndxA/3qi9QAgXlaiyCrhKZLE7TLXVHVIU9XNq0qIyuRWCDaBDSXCbFKTgd26gBY6q30FHpxrDuf09UPnznluxv/0LbGbwyyskj4c5CZwQIGCcj+5a+ypV68G7hzFsaY3l7COvtGfQPnFT3B7JovqoLTpNgh/VtI0PHDo="#;
/// Get a valid signature. Static signature generated with:
/// ```shell
/// echo -n '{"product":"fooobarrr","version":"0.0.2"}' | \
/// openssl dgst -sha256 -sign fixtures/ssh/key | base64
/// ```
pub const VALID_SAMPLE: &'static str = r#"xcPhKCRaL3YheiVvJOhypjFKW7e8sJzyIve2k+Higp+BtB5ED31rW3wl/noDqvIA7YVyWVnEE/nzRfRrjNOE1ylbxwUuOsjRamCr2y6C8q7rBshA6msRmwsVAmIKHcjGWhL/p1bF9WjS7vNbItx0ujHuDlqgTwutvM9XN702IjE="#;
pub fn from_base64_str(content: &str) -> Self {
Signature(openssl::base64::decode_block(content).unwrap().to_vec())
}
pub fn validate(&self, pkg: &Package) -> bool {
use openssl::{hash::MessageDigest, pkey::PKey, rsa::Rsa, sign::Verifier};
let fun = move || {
let content = &std::fs::read("fixtures/ssh/key.pub").unwrap();
let key = Rsa::public_key_from_pem(content)?;
let key = PKey::from_rsa(key)?;
let mut ver = Verifier::new(MessageDigest::sha256(), &key)?;
Result::<bool, openssl::error::ErrorStack>::Ok(ver.verify_oneshot(&self.0, &pkg.raw)?)
};
fun().unwrap_or_default()
}
}
#[derive(Debug)]
pub struct Package {
pub product_uid: String,
pub version: String,
pub raw: Vec<u8>,
}
impl Default for Package {
fn default() -> Self {
Package {
product_uid: String::from("fooobarrr"),
version: String::from("0.0.2"),
raw: br#"{"product":"fooobarrr","version":"0.0.2"}"#.to_vec(),
}
}
}
impl Package {
pub fn parse(content: &[u8]) -> Result<Self, ParsingError> {
#[derive(Deserialize)]
struct PackageAux {
#[serde(rename = "product")]
product_uid: String,
version: String,
}
let update_package = serde_json::from_slice::<PackageAux>(content)?;
Ok(Package {
product_uid: update_package.product_uid,
version: update_package.version,
raw: content.to_vec(),
})
}
}
#[derive(Deserialize, Debug, Serialize, PartialEq)]
pub struct Info {
pub current_version: String,
pub count_invalid_packages: u32,
}
impl Default for Info {
fn default() -> Self {
Info { current_version: String::from("0.0.1"), count_invalid_packages: 0 }
}
}