dynamic_config_server/client/mod.rs
1//! Reading configuration *from* a config server.
2//!
3//! The other half of this crate, behind the `client` feature: a
4//! [`RemoteSource`] that fetches `GET /{application}/{profile}` and hands the
5//! document to the engine, exactly as an etcd or a Vault source does. The two
6//! halves live in one crate so that they are tested against each other —
7//! every test in `tests/client.rs` drives this against the real router rather
8//! than against a fixture of what the router is believed to return.
9//!
10//! ```no_run
11//! use std::time::Duration;
12//! use dynamic_config_server::client::ConfigServer;
13//!
14//! # fn main() -> Result<(), dynamic_config::Error> {
15//! let source = ConfigServer::new("https://config.internal", "billing", "prod")
16//! .with_token(std::env::var("CONFIG_TOKEN").unwrap_or_default())
17//! .with_timeout(Duration::from_secs(5));
18//! # let _ = source;
19//! # Ok(())
20//! # }
21//! ```
22//!
23//! ## What it does not do
24//!
25//! **It does not subscribe.** `GET /{application}/{profile}/stream` carries a
26//! generation, and a client that follows it calls
27//! `refresh_remote()` when the number
28//! moves — a loop of a dozen lines that belongs to whoever owns the reload
29//! cadence. Building it in would mean this crate owning a task, a backoff and
30//! a reconnect policy that the application is better placed to choose; what
31//! this crate owes is the half that is fiddly to get right, which is the
32//! bounded, deadline-covered, credential-carrying fetch below.
33//!
34//! **It does not verify provenance.** The document arrives as JSON with no
35//! signature, so a client trusts the server exactly as far as TLS and the
36//! bearer token take it. A deployment that needs more should read from the
37//! store the server reads from.
38
39mod http;
40
41use std::sync::Arc;
42use std::time::Duration;
43
44use dynamic_config::{Error, Fetched, Format, RemoteSource};
45use dynamic_config_store_core::tls::TlsConfig;
46use dynamic_config_store_core::{redacted, LoneAuthority};
47
48use http::{Budget, Connection, Endpoint};
49
50/// How much of a response body is read before it is refused.
51///
52/// A configuration document that does not fit in a megabyte is not a
53/// configuration document, and a client that trusts a server to send
54/// something finite is a client that can be made to allocate until it dies.
55const MOST_BYTES: usize = 1024 * 1024;
56
57/// The default deadline for one fetch — connect, handshake, request and body.
58const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
59
60/// A [`RemoteSource`] reading one application-and-profile from a config
61/// server.
62///
63/// The credential is a bearer token, scoped by the server to the applications
64/// it may read; TLS with a private authority and a client certificate is
65/// [`TlsConfig`], the same type every store crate in this workspace takes.
66pub struct ConfigServer {
67 url: String,
68 application: String,
69 profile: String,
70 token: Option<String>,
71 tls: TlsConfig,
72 timeout: Duration,
73 /// Built once from `tls`, on the first fetch: assembling a rustls
74 /// configuration reads files, and a fetch path is not where that belongs.
75 client: std::sync::OnceLock<Arc<rustls::ClientConfig>>,
76 described: String,
77}
78
79impl ConfigServer {
80 /// A source reading `{url}/{application}/{profile}`.
81 ///
82 /// `url` may carry a path prefix — `https://config.internal/config` — for
83 /// a server mounted behind one. A userinfo component is refused rather
84 /// than dropped: this server's credential is a bearer token, and a
85 /// password in a url is a password in every log that url reaches.
86 #[must_use]
87 pub fn new(
88 url: impl Into<String>,
89 application: impl Into<String>,
90 profile: impl Into<String>,
91 ) -> Self {
92 let (url, application, profile) = (url.into(), application.into(), profile.into());
93
94 // Redacted as the description is built, rather than where each
95 // message is written: this string is quoted into every error this
96 // source raises and is what `describe()` returns — and one of those
97 // errors is the *refusal* of a `user:password@` authority. Printing
98 // the password while saying it is refused would be a leak with a
99 // note attached.
100 let described = format!(
101 "config server {} {application}/{profile}",
102 redacted(&url, LoneAuthority::Username)
103 );
104
105 Self {
106 // Parsing is deferred to the first fetch so that `new` cannot
107 // fail: a source that refuses to be *built* is awkward to place
108 // in a builder chain, and the url is checked before it is used.
109 url,
110 application,
111 profile,
112 token: None,
113 tls: TlsConfig::new(),
114 timeout: DEFAULT_TIMEOUT,
115 client: std::sync::OnceLock::new(),
116 described,
117 }
118 }
119
120 /// The bearer token this server issued for these applications.
121 ///
122 /// Without one the server answers `401` unless it was started with
123 /// anonymous access explicitly enabled.
124 #[must_use]
125 pub fn with_token(mut self, token: impl Into<String>) -> Self {
126 self.token = Some(token.into());
127 self
128 }
129
130 /// A private certificate authority, a client certificate, or both.
131 ///
132 /// The same [`TlsConfig`] the store crates take, so a deployment spells
133 /// its trust once and uses it everywhere.
134 #[must_use]
135 pub fn with_tls(mut self, tls: TlsConfig) -> Self {
136 self.tls = tls;
137 self
138 }
139
140 /// The deadline for one fetch: connect, TLS handshake, request and body.
141 ///
142 /// Ten seconds by default. A fetch that hangs is a reload that never
143 /// happens, and the loop above has no other way to notice.
144 #[must_use]
145 pub fn with_timeout(mut self, timeout: Duration) -> Self {
146 self.timeout = timeout;
147 self
148 }
149
150 /// The rustls configuration, built once.
151 ///
152 /// Building it reads files, so it is done on the first fetch and kept —
153 /// not per fetch, and not at construction, where it would make `new`
154 /// fallible for a source that may never be used.
155 fn tls_client(&self, secure: bool) -> Result<Option<&Arc<rustls::ClientConfig>>, Error> {
156 if !secure {
157 return Ok(None);
158 }
159
160 if let Some(built) = self.client.get() {
161 return Ok(Some(built));
162 }
163
164 let built = self.build_tls_client()?;
165
166 Ok(Some(self.client.get_or_init(|| built)))
167 }
168
169 fn build_tls_client(&self) -> Result<Arc<rustls::ClientConfig>, Error> {
170 use rustls::pki_types::pem::PemObject as _;
171 use rustls::pki_types::{CertificateDer, PrivateKeyDer};
172
173 let mut roots = rustls::RootCertStore::empty();
174
175 // The platform store first, then the caller's authority on top: a
176 // private CA is one *more* certificate to trust, which is the whole
177 // reason this crate offers no way to turn verification off.
178 for certificate in rustls_native_certs::load_native_certs().certs {
179 let _ = roots.add(certificate);
180 }
181
182 if let Some(pem) = self.tls.ca_certificate_pem(&self.described)? {
183 let mut added = 0;
184
185 for certificate in CertificateDer::pem_slice_iter(&pem) {
186 let certificate = certificate.map_err(|_| {
187 Error::remote(format!(
188 "{}: the certificate authority is not readable as PEM",
189 self.described
190 ))
191 })?;
192
193 roots
194 .add(certificate)
195 .map_err(|error| Error::remote(format!("{}: {error}", self.described)))?;
196 added += 1;
197 }
198
199 if added == 0 {
200 return Err(Error::remote(format!(
201 "{}: the certificate authority holds no certificate",
202 self.described
203 )));
204 }
205 }
206
207 let builder = rustls::ClientConfig::builder().with_root_certificates(roots);
208
209 let Some((certificate, key)) = self.tls.client_certificate_pem(&self.described)? else {
210 return Ok(Arc::new(builder.with_no_client_auth()));
211 };
212
213 let chain = CertificateDer::pem_slice_iter(&certificate)
214 .collect::<Result<Vec<_>, _>>()
215 .map_err(|_| {
216 Error::remote(format!(
217 "{}: the client certificate is not readable as PEM",
218 self.described
219 ))
220 })?;
221
222 // The key's own parse error is deliberately dropped: the one thing
223 // such an error has to say is the line it choked on, and in a key
224 // file that line is key material.
225 let key = PrivateKeyDer::from_pem_slice(&key).map_err(|_| {
226 Error::remote(format!(
227 "{}: the client private key is not readable as PEM",
228 self.described
229 ))
230 })?;
231
232 builder
233 .with_client_auth_cert(chain, key)
234 .map(Arc::new)
235 .map_err(|error| Error::remote(format!("{}: {error}", self.described)))
236 }
237
238 /// One fetch, on the current thread's runtime.
239 async fn read(&self) -> Result<Fetched, Error> {
240 let endpoint = Endpoint::parse(&self.url, &self.described)?;
241 let path = endpoint.path(&format!("/{}/{}", self.application, self.profile));
242
243 // One budget for the whole attempt, started here: the deadline
244 // `with_timeout` documents is for a fetch, and a fetch is the
245 // connect, the handshake, the request and the body together.
246 let budget = Budget::starting(self.timeout);
247
248 let secure = endpoint.secure;
249 let mut connection =
250 Connection::open(&endpoint, self.tls_client(secure)?, budget, &self.described).await?;
251
252 let response = connection
253 .get(
254 &endpoint,
255 &path,
256 self.token.as_deref(),
257 "application/json",
258 budget,
259 &self.described,
260 )
261 .await?;
262
263 if !response.status().is_success() {
264 return Err(http::refused(response.status(), &self.described));
265 }
266
267 let body = http::body(response, MOST_BYTES, budget, &self.described).await?;
268 let text = String::from_utf8(body)
269 .map_err(|_| Error::remote(format!("{}: the document is not UTF-8", self.described)))?;
270
271 // The server answers `{application, profile, generation, config}`;
272 // the engine wants the document, which is `config`. Reaching for it
273 // by name rather than deserializing the envelope keeps this working
274 // when the envelope grows a field.
275 let document = extract(&text, &self.described)?;
276
277 Ok(Fetched::new(document, Format::Json))
278 }
279}
280
281/// The `config` member of the server's envelope, re-rendered.
282fn extract(text: &str, described: &str) -> Result<String, Error> {
283 let envelope: serde_json::Value = serde_json::from_str(text)
284 .map_err(|_| Error::remote(format!("{described}: the answer is not JSON")))?;
285
286 let document = envelope.get("config").ok_or_else(|| {
287 Error::remote(format!(
288 "{described}: the answer carries no `config` member; is this a \
289 config server?"
290 ))
291 })?;
292
293 serde_json::to_string(document)
294 .map_err(|_| Error::remote(format!("{described}: the document will not re-render")))
295}
296
297impl RemoteSource for ConfigServer {
298 fn fetch(&self) -> Result<Fetched, Error> {
299 // A blocking `fetch` on a client built from an async stack: one
300 // runtime, current-thread, for this call only. A source is fetched
301 // when a caller asks, minutes or hours apart, so the cost of starting
302 // one is not on any path that matters — and owning a long-lived
303 // runtime here would put a second one inside applications that
304 // already have theirs.
305 let runtime = tokio::runtime::Builder::new_current_thread()
306 .enable_all()
307 .build()
308 .map_err(|error| {
309 Error::remote(format!(
310 "{}: no runtime for the fetch: {error}",
311 self.described
312 ))
313 })?;
314
315 runtime.block_on(self.read())
316 }
317
318 fn describe(&self) -> String {
319 self.described.clone()
320 }
321}
322
323impl std::fmt::Debug for ConfigServer {
324 /// Shape only. The token is the credential and never prints; `TlsConfig`
325 /// redacts its own key material; and the URL is redacted too, because a
326 /// `user:password@` authority is refused at fetch time rather than at
327 /// construction — so a source carrying one can be printed.
328 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329 formatter
330 .debug_struct("ConfigServer")
331 .field("url", &redacted(&self.url, LoneAuthority::Username))
332 .field("application", &self.application)
333 .field("profile", &self.profile)
334 .field("token", &self.token.as_ref().map(|_| "<redacted>"))
335 .field("tls", &self.tls)
336 .field("timeout", &self.timeout)
337 .finish()
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344
345 #[test]
346 fn a_document_is_lifted_out_of_the_servers_envelope() {
347 let text = r#"{"application":"billing","profile":"prod","generation":7,
348 "config":{"port":8080}}"#;
349
350 assert_eq!(extract(text, "a server").unwrap(), r#"{"port":8080}"#);
351 }
352
353 #[test]
354 fn an_answer_from_something_that_is_not_a_config_server_says_so() {
355 let error = extract(r#"{"hello":"world"}"#, "a server").unwrap_err();
356
357 assert!(error.to_string().contains("no `config` member"), "{error}");
358 }
359
360 /// A password in the URL is refused rather than sent — and the refusal
361 /// must not be where it gets printed. `new` cannot fail, so the source
362 /// exists, is `Debug`-printed and describes itself long before the
363 /// parser gets to say no.
364 #[test]
365 fn a_password_in_the_url_reaches_neither_debug_nor_a_message() {
366 let source = ConfigServer::new(
367 "https://user:hunter2-do-not-print@config.internal",
368 "billing",
369 "prod",
370 );
371
372 let rendered = format!("{source:?}");
373 assert!(!rendered.contains("hunter2"), "{rendered}");
374
375 let described = source.describe();
376 assert!(!described.contains("hunter2"), "{described}");
377 assert!(described.contains("user:***@"), "{described}");
378
379 // And the refusal itself, which quotes the description.
380 let error = Endpoint::parse(&source.url, &source.described)
381 .expect_err("a `user:password@` authority is refused");
382 assert!(!error.to_string().contains("hunter2"), "{error}");
383 }
384
385 #[test]
386 fn a_token_never_reaches_debug() {
387 let source = ConfigServer::new("https://config.internal", "billing", "prod")
388 .with_token("hunter2-do-not-print");
389
390 let rendered = format!("{source:?}");
391
392 assert!(!rendered.contains("hunter2"), "{rendered}");
393 assert!(rendered.contains("<redacted>"), "{rendered}");
394 }
395}