ultimate_common/model/sensitive/
uri_string.rs

1use core::{fmt, ops::Deref};
2use std::borrow::Cow;
3
4use regex::Regex;
5use serde::{de::Visitor, Deserialize, Serialize};
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
66/// 替换 <username>:<password> 部分
67fn replace_uri_username_password(v: &str) -> Cow<'_, str> {
68  let r: Regex = Regex::new(r#"://(.+):(.+)@"#).unwrap();
69  r.replace(v, "://<username>:<password>@")
70}
71
72impl<'de> Deserialize<'de> for UriString {
73  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
74  where
75    D: serde::Deserializer<'de>,
76  {
77    struct UriStringVisitor;
78    impl<'de> Visitor<'de> for UriStringVisitor {
79      type Value = UriString;
80
81      fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
82        formatter.write_str("Unsupport type, need string.")
83      }
84
85      fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
86      where
87        E: serde::de::Error,
88      {
89        Ok(UriString(v))
90      }
91
92      fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
93      where
94        E: serde::de::Error,
95      {
96        Ok(UriString(v.to_string()))
97      }
98    }
99    deserializer.deserialize_string(UriStringVisitor)
100  }
101}
102
103#[cfg(test)]
104mod tests {
105  use super::*;
106
107  #[test]
108  fn test_url_string() {
109    let url_string = UriString::new("postgres://abcdefg:2023.ultimate@localhost:5432/ultimate");
110    let text = serde_json::to_string(&url_string).unwrap();
111    assert_eq!(text, "\"postgres://<username>:<password>@localhost:5432/ultimate\"");
112
113    let url_string = UriString::new("postgres://localhost:5432/ultimate");
114    let text = serde_json::to_string(&url_string).unwrap();
115    assert_eq!(text, "\"postgres://localhost:5432/ultimate\"");
116  }
117}