fusion_common/model/sensitive/
uri_string.rs1use core::{fmt, ops::Deref};
2use std::borrow::Cow;
3
4use regex::Regex;
5use serde::{Deserialize, Serialize, de::Visitor};
6
7use super::{AsUnderlying, ToSensitive};
8
9#[derive(Clone)]
10pub struct UriString(String);
11
12impl UriString {
13 pub fn new(s: impl Into<String>) -> Self {
14 Self(s.into())
15 }
16}
17
18impl fmt::Display for UriString {
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 f.write_str(&self.to_sensitive())
21 }
22}
23
24impl fmt::Debug for UriString {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 f.debug_tuple("UriString").field(&self.to_string()).finish()
27 }
28}
29
30impl Deref for UriString {
31 type Target = str;
32
33 fn deref(&self) -> &Self::Target {
34 &self.0
35 }
36}
37
38impl AsRef<str> for UriString {
39 fn as_ref(&self) -> &str {
40 &self.0
41 }
42}
43
44impl ToSensitive for UriString {
45 fn to_sensitive(&self) -> String {
46 replace_uri_username_password(self.deref()).into_owned()
47 }
48}
49
50impl AsUnderlying for UriString {
51 fn as_underlying(&self) -> &str {
52 &self.0
53 }
54}
55
56impl Serialize for UriString {
57 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
58 where
59 S: serde::Serializer,
60 {
61 let s = replace_uri_username_password(self.deref());
62 serializer.serialize_str(s.as_ref())
63 }
64}
65
66impl From<&str> for UriString {
67 fn from(v: &str) -> Self {
68 Self(v.to_string())
69 }
70}
71
72fn replace_uri_username_password(v: &str) -> Cow<'_, str> {
74 let r: Regex = Regex::new(r#"://(.+):(.+)@"#).unwrap();
75 r.replace(v, "://<username>:<password>@")
76}
77
78impl<'de> Deserialize<'de> for UriString {
79 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80 where
81 D: serde::Deserializer<'de>,
82 {
83 struct UriStringVisitor;
84 impl Visitor<'_> for UriStringVisitor {
85 type Value = UriString;
86
87 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
88 formatter.write_str("Unsupport type, need string.")
89 }
90
91 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
92 where
93 E: serde::de::Error,
94 {
95 Ok(UriString(v))
96 }
97
98 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
99 where
100 E: serde::de::Error,
101 {
102 Ok(UriString(v.to_string()))
103 }
104 }
105 deserializer.deserialize_string(UriStringVisitor)
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn test_url_string() {
115 let url_string = UriString::new("postgres://abcdefg:2023.fusion@localhost:5432/fusion");
116 let text = serde_json::to_string(&url_string).unwrap();
117 assert_eq!(text, "\"postgres://<username>:<password>@localhost:5432/fusion\"");
118
119 let url_string = UriString::new("postgres://localhost:5432/fusion");
120 let text = serde_json::to_string(&url_string).unwrap();
121 assert_eq!(text, "\"postgres://localhost:5432/fusion\"");
122 }
123}