Debian Codegraph @

src/desktop/handle_token.rs

raw
1 use std::{
2 convert::TryFrom,
3 fmt::{self, Debug, Display},
4 };
5
6 use serde::{Deserialize, Serialize};
7 use zbus::zvariant::Type;
8
9 /// A handle token is a DBus Object Path element.
10 ///
11 /// Specified in the [`Request`](crate::desktop::Request) or
12 /// [`Session`](crate::desktop::Session) object path following this format
13 /// `/org/freedesktop/portal/desktop/request/SENDER/TOKEN` where sender is the
14 /// caller's unique name and token is the [`HandleToken`].
15 ///
16 /// A valid object path element must only contain the ASCII characters
17 /// `[A-Z][a-z][0-9]_`
18 #[derive(Serialize, Type, PartialEq, Eq, Hash, Clone)]
19 pub struct HandleToken(String);
20
21 impl Display for HandleToken {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 f.write_str(&self.0)
24 }
25 }
26
27 impl Debug for HandleToken {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 f.debug_tuple("HandleToken")
30 .field(&self.0.as_str())
31 .finish()
32 }
33 }
34
35 impl Default for HandleToken {
36 fn default() -> Self {
37 const ALPHANUMERIC: &[u8] =
38 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
39
40 let mut token = String::with_capacity(16); // "ashpd_" + 10 chars
41 token.push_str("ashpd_");
42
43 let mut rnd_bytes = [0u8; 10];
44 getrandom::fill(&mut rnd_bytes).expect("failed to generate random bytes");
45
46 for byte in rnd_bytes.iter() {
47 let idx = (*byte as usize) % ALPHANUMERIC.len();
48 token.push(ALPHANUMERIC[idx] as char);
49 }
50
51 Self(token)
52 }
53 }
54
55 #[derive(Debug)]
56 pub struct HandleInvalidCharacter(char);
57
58 impl std::fmt::Display for HandleInvalidCharacter {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.write_fmt(format_args!("Invalid Character {}", self.0))
61 }
62 }
63
64 impl std::error::Error for HandleInvalidCharacter {}
65
66 impl std::str::FromStr for HandleToken {
67 type Err = HandleInvalidCharacter;
68
69 fn from_str(value: &str) -> Result<Self, Self::Err> {
70 if value.is_empty() {
71 // Temporary value for backward compatibility
72 return Err(HandleInvalidCharacter('\0'));
73 }
74
75 for char in value.chars() {
76 if !char.is_ascii_alphanumeric() && char != '_' {
77 return Err(HandleInvalidCharacter(char));
78 }
79 }
80
81 Ok(Self(value.to_string()))
82 }
83 }
84
85 impl TryFrom<String> for HandleToken {
86 type Error = HandleInvalidCharacter;
87
88 fn try_from(value: String) -> Result<Self, Self::Error> {
89 value.parse::<Self>()
90 }
91 }
92
93 impl TryFrom<&str> for HandleToken {
94 type Error = HandleInvalidCharacter;
95
96 fn try_from(value: &str) -> Result<Self, Self::Error> {
97 value.parse::<Self>()
98 }
99 }
100
101 #[cfg(feature = "backend")]
102 impl TryFrom<&zbus::zvariant::OwnedObjectPath> for HandleToken {
103 type Error = HandleInvalidCharacter;
104
105 fn try_from(value: &zbus::zvariant::OwnedObjectPath) -> Result<Self, Self::Error> {
106 let base_segment = value
107 .as_str()
108 .split('/')
109 .next_back()
110 .expect("A valid request ObjectPath");
111 Self::try_from(base_segment)
112 }
113 }
114
115 impl<'de> Deserialize<'de> for HandleToken {
116 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
117 where
118 D: serde::Deserializer<'de>,
119 {
120 let token = String::deserialize(deserializer)?;
121 token
122 .parse::<Self>()
123 .map_err(|err| serde::de::Error::custom(err.to_string()))
124 }
125 }
126 #[cfg(test)]
127 mod test {
128 use std::str::FromStr;
129
130 use super::HandleToken;
131
132 #[test]
133 fn handle_token() {
134 assert!(HandleToken::from_str("token").is_ok());
135
136 let token = HandleToken::from_str("token2").unwrap();
137 assert_eq!(token.to_string(), "token2".to_string());
138
139 assert!(HandleToken::from_str("2token").is_ok());
140
141 assert!(HandleToken::from_str("/test").is_err());
142
143 assert!(HandleToken::from_str("تجربة").is_err());
144
145 assert!(HandleToken::from_str("test_token").is_ok());
146
147 assert!(HandleToken::from_str("").is_err());
148
149 HandleToken::default(); // ensure we don't panic
150 }
151 }