-
Notifications
You must be signed in to change notification settings - Fork 8
/
sources.rs
335 lines (289 loc) · 10.8 KB
/
sources.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
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
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::convert::{TryFrom, TryInto};
use std::path::{Path, PathBuf};
use std::{fs, fs::File};
#[derive(Clone, Default, Deserialize, Debug)]
struct RawSourceAuthorities(HashMap<String, Vec<RawSourceAuthority>>);
// This is how a RawSourceAuthority looks like:
// ```json
// {
// "type": "Path"
// "path": "/foo.pem"
// },
// {
// "type": "Data"
// "data": "PEM Data"
// }
// ```
#[derive(Clone, Deserialize, Debug)]
#[serde(tag = "type")]
enum RawSourceAuthority {
Data { data: RawCertificate },
Path { path: PathBuf },
}
impl TryFrom<RawSourceAuthority> for RawCertificate {
type Error = anyhow::Error;
fn try_from(raw_source_authority: RawSourceAuthority) -> Result<Self> {
match raw_source_authority {
RawSourceAuthority::Data { data } => Ok(data),
RawSourceAuthority::Path { path } => {
let file_data = fs::read(path.clone()).map_err(|e| {
anyhow!("Cannot read certificate from file '{:?}': {:?}", path, e)
})?;
Ok(RawCertificate(String::from_utf8(file_data).unwrap()))
}
}
}
}
#[derive(Clone, Default, Deserialize, Debug)]
#[serde(default)]
struct RawSources {
insecure_sources: HashSet<String>,
source_authorities: RawSourceAuthorities,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
struct RawCertificate(String);
#[derive(Clone, Debug, Default)]
struct SourceAuthorities(HashMap<String, Vec<Certificate>>);
impl TryFrom<RawSourceAuthorities> for SourceAuthorities {
type Error = anyhow::Error;
fn try_from(raw_source_authorities: RawSourceAuthorities) -> Result<SourceAuthorities> {
let mut sa = SourceAuthorities::default();
for (host, authorities) in raw_source_authorities.0 {
let mut certs: Vec<Certificate> = Vec::new();
for authority in authorities {
let raw_cert: RawCertificate = authority.try_into()?;
let cert: Certificate = raw_cert.try_into()?;
certs.push(cert);
}
sa.0.insert(host.clone(), certs);
}
Ok(sa)
}
}
#[derive(Clone, Debug, Default)]
pub struct Sources {
insecure_sources: HashSet<String>,
source_authorities: SourceAuthorities,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Certificate {
Der(Vec<u8>),
Pem(Vec<u8>),
}
impl TryFrom<RawSources> for Sources {
type Error = anyhow::Error;
fn try_from(sources: RawSources) -> Result<Sources> {
Ok(Sources {
insecure_sources: sources.insecure_sources.clone(),
source_authorities: sources.source_authorities.try_into()?,
})
}
}
impl TryFrom<RawCertificate> for Certificate {
type Error = anyhow::Error;
fn try_from(raw_certificate: RawCertificate) -> Result<Certificate> {
if reqwest::Certificate::from_pem(raw_certificate.0.as_bytes()).is_ok() {
Ok(Certificate::Pem(raw_certificate.0.as_bytes().to_vec()))
} else if reqwest::Certificate::from_der(raw_certificate.0.as_bytes()).is_ok() {
Ok(Certificate::Der(raw_certificate.0.as_bytes().to_vec()))
} else {
Err(anyhow!(
"certificate {:?} is not in PEM nor in DER encoding",
raw_certificate
))
}
}
}
impl From<&Certificate> for sigstore::registry::Certificate {
fn from(cert: &Certificate) -> Self {
match cert {
Certificate::Der(data) => sigstore::registry::Certificate {
encoding: sigstore::registry::CertificateEncoding::Der,
data: data.clone(),
},
Certificate::Pem(data) => sigstore::registry::Certificate {
encoding: sigstore::registry::CertificateEncoding::Pem,
data: data.clone(),
},
}
}
}
impl From<Sources> for oci_distribution::client::ClientConfig {
fn from(sources: Sources) -> Self {
let protocol = if sources.insecure_sources.is_empty() {
oci_distribution::client::ClientProtocol::Https
} else {
let insecure: Vec<String> = sources.insecure_sources.iter().cloned().collect();
oci_distribution::client::ClientProtocol::HttpsExcept(insecure)
};
let extra_root_certificates: Vec<oci_distribution::client::Certificate> = sources
.source_authorities
.0
.iter()
.flat_map(|(_, certs)| {
certs
.iter()
.map(|c| c.into())
.collect::<Vec<oci_distribution::client::Certificate>>()
})
.collect();
oci_distribution::client::ClientConfig {
protocol,
accept_invalid_certificates: false,
extra_root_certificates,
platform_resolver: None,
}
}
}
impl From<Sources> for sigstore::registry::ClientConfig {
fn from(sources: Sources) -> Self {
let protocol = if sources.insecure_sources.is_empty() {
sigstore::registry::ClientProtocol::Https
} else {
let insecure: Vec<String> = sources.insecure_sources.iter().cloned().collect();
sigstore::registry::ClientProtocol::HttpsExcept(insecure)
};
let extra_root_certificates: Vec<sigstore::registry::Certificate> = sources
.source_authorities
.0
.iter()
.flat_map(|(_, certs)| {
certs
.iter()
.map(|c| c.into())
.collect::<Vec<sigstore::registry::Certificate>>()
})
.collect();
sigstore::registry::ClientConfig {
accept_invalid_certificates: false,
protocol,
extra_root_certificates,
}
}
}
impl Sources {
pub fn is_insecure_source(&self, host: &str) -> bool {
self.insecure_sources.contains(host)
}
pub fn source_authority(&self, host: &str) -> Option<Vec<Certificate>> {
self.source_authorities.0.get(host).map(Clone::clone)
}
}
pub fn read_sources_file(path: &Path) -> Result<Sources> {
serde_yaml::from_reader::<_, RawSources>(File::open(path)?)?.try_into()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::io::Write;
use tempfile::NamedTempFile;
const CERT_DATA: &str = r#"-----BEGIN CERTIFICATE-----
MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL
MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC
VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx
NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD
TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu
ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j
V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj
gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA
FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE
CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS
BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE
BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju
Wm7DCfrPNGVwFWUQOmsPue9rZBgO
-----END CERTIFICATE-----
"#;
#[test]
fn test_deserialization_of_path_based_raw_source_authority() {
let expected_path = "/foo.pem";
let raw = json!({"type": "Path", "path": expected_path });
let actual: Result<RawSourceAuthority, serde_json::Error> = serde_json::from_value(raw);
match actual {
Ok(RawSourceAuthority::Path { path }) => {
let expected: PathBuf = expected_path.into();
assert_eq!(path, expected);
}
unexpected => {
panic!("Didn't get the expected value: {:?}", unexpected);
}
}
}
#[test]
fn test_deserialization_of_data_based_raw_source_authority() {
let expected_data = RawCertificate("hello world".into());
let raw = json!({ "type": "Data", "data": expected_data });
let actual: Result<RawSourceAuthority, serde_json::Error> = serde_json::from_value(raw);
match actual {
Ok(RawSourceAuthority::Data { data }) => {
assert_eq!(data, expected_data);
}
unexpected => {
panic!("Didn't get the expected value: {:?}", unexpected);
}
}
}
#[test]
fn test_deserialization_of_unknown_raw_source_authority() {
let broken_cases = vec![json!({ "something": "unknown" }), json!({ "path": 1 })];
for bc in broken_cases {
let actual: Result<RawSourceAuthority, serde_json::Error> =
serde_json::from_value(bc.clone());
assert!(
actual.is_err(),
"Expected {:?} to fail, got instead {:?}",
bc,
actual
);
}
}
#[test]
fn test_raw_source_authority_cannot_be_converted_into_raw_certificate_when_file_is_missing() {
let mut path = PathBuf::new();
path.push("/boom");
let auth = RawSourceAuthority::Path { path };
let expected: Result<RawCertificate> = auth.try_into();
assert!(expected.is_err());
}
#[test]
fn test_raw_path_based_source_authority_convertion_into_raw_certificate() {
let mut file = NamedTempFile::new().unwrap();
let expected_contents = "hello world";
write!(file, "{}", expected_contents).unwrap();
let path = file.path();
let auth = RawSourceAuthority::Path {
path: path.to_path_buf(),
};
let expected: Result<RawCertificate> = auth.try_into();
match expected {
Ok(RawCertificate(data)) => {
assert_eq!(&data, expected_contents);
}
unexpected => {
panic!("Didn't get what I was expecting: {:?}", unexpected);
}
}
}
#[test]
fn test_raw_source_authorities_to_source_authority() {
let expected_cert = Certificate::Pem(CERT_DATA.into());
let raw = json!({
"foo.com": [
{"type": "Data", "data": RawCertificate(CERT_DATA.into())},
{"type": "Data", "data": RawCertificate(CERT_DATA.into())}
]}
);
let raw_source_authorities: RawSourceAuthorities = serde_json::from_value(raw).unwrap();
let actual: Result<SourceAuthorities> = raw_source_authorities.try_into();
assert!(actual.is_ok(), "Got an expected error: {:?}", actual);
let actual_map = actual.unwrap().0;
let actual_certs = actual_map.get("foo.com").unwrap();
assert_eq!(actual_certs.len(), 2);
for actual_cert in actual_certs {
assert_eq!(actual_cert, &expected_cert);
}
}
}