Skip to main content

tuwunel_core/config/
format.rs

1use std::fmt::{Display, Formatter, Result as FmtResult};
2
3use figment::providers::Format;
4use serde::de::DeserializeOwned;
5use toml::de::{Error as TomlError, from_str as from_toml_str};
6use url::{Position, Url};
7
8/// TOML data format for figment's file and string providers.
9///
10/// figment's own provider is gated behind `toml 0.8`, a second copy of the toml
11/// crate family alongside the `toml 1.x` the workspace uses. Supplying the
12/// format here keeps figment's file, nesting and profile machinery while
13/// parsing through the workspace crate.
14pub(super) struct Toml;
15
16/// Displays an optional relay URI with its userinfo concealed.
17///
18/// Unparsable or hostless values are concealed in full.
19pub(super) struct UriUserinfo<'a>(pub(super) Option<&'a str>);
20
21impl Format for Toml {
22	type Error = TomlError;
23
24	const NAME: &'static str = "TOML";
25
26	fn from_str<T: DeserializeOwned>(text: &str) -> Result<T, Self::Error> { from_toml_str(text) }
27}
28
29impl Display for UriUserinfo<'_> {
30	fn fmt(&self, out: &mut Formatter<'_>) -> FmtResult {
31		let Some(value) = self.0 else {
32			return out.write_str("None");
33		};
34
35		let Ok(uri) = Url::parse(value) else {
36			return out.write_str("***********");
37		};
38
39		if !uri.has_host() {
40			return out.write_str("***********");
41		}
42
43		if uri.username().is_empty() && uri.password().is_none() {
44			return write!(out, "{:?}", Some(uri.as_str()));
45		}
46
47		write!(
48			out,
49			"Some(\"{}***********@{}\")",
50			&uri[..Position::BeforeUsername],
51			&uri[Position::BeforeHost..],
52		)
53	}
54}