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
|
use crate::MOZART_VERSION;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use anyhow::{Context, Result, anyhow, bail};
/// Returns the common User-Agent string for all HTTP requests.
///
/// Format: `Mozart/<version> (<os>; <arch>)`
pub fn user_agent() -> String {
format!(
"Mozart/{} ({}; {})",
MOZART_VERSION,
std::env::consts::OS,
std::env::consts::ARCH,
)
}
/// TLS verification options, mirroring Composer's `config.cafile` and
/// `config.capath`.
#[derive(Debug, Default, Clone)]
pub struct TlsOptions {
pub cafile: Option<PathBuf>,
pub capath: Option<PathBuf>,
}
/// Pre-parsed root certificates, loaded once from `cafile`/`capath` and shared
/// across every reqwest client built via [`client_builder`].
static EXTRA_ROOT_CERTS: OnceLock<Vec<reqwest::Certificate>> = OnceLock::new();
/// Initialize the process-wide TLS options.
///
/// Reads `cafile` and `capath` (if set), parses every certificate up-front,
/// and stores the parsed [`reqwest::Certificate`] list in a global so that
/// subsequent [`client_builder`] calls are infallible.
///
/// May be called at most once; subsequent calls are silently ignored. This
/// matches the lifetime of the binary's HTTP configuration: load on startup,
/// reuse for the rest of the process.
pub fn init_tls_options(opts: &TlsOptions) -> Result<()> {
if EXTRA_ROOT_CERTS.get().is_some() {
return Ok(());
}
let mut certs = Vec::new();
if let Some(ref cafile) = opts.cafile {
certs.extend(load_cafile(cafile)?);
}
if let Some(ref capath) = opts.capath {
certs.extend(load_capath(capath)?);
}
let _ = EXTRA_ROOT_CERTS.set(certs);
Ok(())
}
fn load_cafile(path: &Path) -> Result<Vec<reqwest::Certificate>> {
let pem = std::fs::read(path).with_context(|| {
format!(
"The configured cafile {} could not be read.",
path.display()
)
})?;
let certs = reqwest::Certificate::from_pem_bundle(&pem)
.with_context(|| format!("The configured cafile {} was not valid.", path.display()))?;
if certs.is_empty() {
bail!(
"The configured cafile {} did not contain any certificates.",
path.display()
);
}
Ok(certs)
}
fn load_capath(path: &Path) -> Result<Vec<reqwest::Certificate>> {
let metadata = std::fs::metadata(path).with_context(|| {
format!(
"The configured capath {} could not be accessed.",
path.display()
)
})?;
if !metadata.is_dir() {
return Err(anyhow!(
"The configured capath {} is not a directory.",
path.display()
));
}
let mut out = Vec::new();
let entries = std::fs::read_dir(path).with_context(|| {
format!(
"The configured capath {} could not be read.",
path.display()
)
})?;
for entry in entries {
let entry =
entry.with_context(|| format!("Failed to enumerate capath {}", path.display()))?;
let entry_path = entry.path();
if !entry_path.is_file() {
continue;
}
let Ok(pem) = std::fs::read(&entry_path) else {
continue;
};
match reqwest::Certificate::from_pem_bundle(&pem) {
Ok(parsed) => out.extend(parsed),
Err(e) => {
tracing::debug!(
path = %entry_path.display(),
error = %e,
"skipping non-PEM file in capath"
);
}
}
}
Ok(out)
}
/// Returns a [`reqwest::ClientBuilder`] preconfigured with Mozart's User-Agent
/// and any extra root certificates registered via [`init_tls_options`].
pub fn client_builder() -> reqwest::ClientBuilder {
let mut b = reqwest::Client::builder().user_agent(user_agent());
if let Some(certs) = EXTRA_ROOT_CERTS.get() {
for cert in certs {
b = b.add_root_certificate(cert.clone());
}
}
b
}
/// Build a default [`reqwest::Client`] with Mozart's User-Agent and any
/// configured root certificates. Panics on build failure, matching
/// [`reqwest::Client::new`] semantics.
pub fn default_client() -> reqwest::Client {
client_builder()
.build()
.expect("failed to build default HTTP client")
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
// A self-signed PEM cert generated for testing only.
//
// $ openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 \
// -keyout key.pem -out cert.pem -days 365 -nodes \
// -subj "/CN=localhost" \
// -addext "subjectAltName=DNS:localhost,DNS:*.localhost,IP:127.0.0.1"
const TEST_PEM: &[u8] = b"\
-----BEGIN CERTIFICATE-----
MIIBpjCCAUygAwIBAgIUF1tLFV2l2URaYf1oYgEMs89bv8owCgYIKoZIzj0EAwIw
FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDUwNDA0NTU1OVoXDTI3MDUwNDA0
NTU1OVowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D
AQcDQgAEAFZrTfAdhntykKL3WTL/hGHnBQhxv1205XRWnXzMwWSaow9R+VIEKZRw
kwrKKPM04RlpiwqCbJOV/IutFvQHvqN8MHowHQYDVR0OBBYEFLryrLkUMiRWV9yF
Dj7paTV/36+/MB8GA1UdIwQYMBaAFLryrLkUMiRWV9yFDj7paTV/36+/MA8GA1Ud
EwEB/wQFMAMBAf8wJwYDVR0RBCAwHoIJbG9jYWxob3N0ggsqLmxvY2FsaG9zdIcE
fwAAATAKBggqhkjOPQQDAgNIADBFAiEAhgdXBmYJYqipYwiDM1SKiXDg2bwN9YLu
zbjOBz0kJ14CIA+tqV3c2sYRJhqwLu7phihPef38zcG70ADcz5o2VQnk
-----END CERTIFICATE-----
";
#[test]
fn user_agent_includes_version() {
let ua = user_agent();
assert!(ua.starts_with("Mozart/"));
}
#[test]
fn load_cafile_parses_pem_bundle() {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(TEST_PEM).unwrap();
let certs = load_cafile(f.path()).expect("valid PEM should parse");
assert_eq!(certs.len(), 1);
}
#[test]
fn load_cafile_missing_file_errors() {
let err = load_cafile(Path::new("/nonexistent/path/to/cafile.pem")).unwrap_err();
assert!(err.to_string().contains("could not be read"));
}
#[test]
fn load_cafile_invalid_pem_errors() {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(b"this is not a PEM file\n").unwrap();
let err = load_cafile(f.path()).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("not valid") || msg.contains("did not contain"),
"unexpected error message: {msg}"
);
}
#[test]
fn load_capath_reads_pem_files_and_skips_others() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("ca.pem"), TEST_PEM).unwrap();
std::fs::write(dir.path().join("README.txt"), b"not a cert").unwrap();
let certs = load_capath(dir.path()).expect("should succeed");
assert_eq!(certs.len(), 1);
}
#[test]
fn load_capath_rejects_file_path() {
let f = tempfile::NamedTempFile::new().unwrap();
let err = load_capath(f.path()).unwrap_err();
assert!(err.to_string().contains("not a directory"));
}
}
|