nexo_plugin_browser/
profile.rs1use std::path::{Path, PathBuf};
25
26use sha2::{Digest, Sha256};
27use thiserror::Error;
28
29const MAX_AGENT_ID_LEN: usize = 64;
30
31#[derive(Debug, Clone, Error, PartialEq, Eq)]
35pub enum ProfileIdError {
36 #[error("agent_id is empty")]
38 Empty,
39 #[error("agent_id `{0}` exceeds 64 characters")]
41 TooLong(String),
42 #[error("agent_id `{0}` contains invalid characters (allowed: [A-Za-z0-9_-])")]
46 Invalid(String),
47}
48
49pub fn sanitize_agent_id(raw: &str) -> Result<String, ProfileIdError> {
58 let trimmed = raw.trim();
59 if trimmed.is_empty() {
60 return Err(ProfileIdError::Empty);
61 }
62 if trimmed.chars().count() > MAX_AGENT_ID_LEN {
63 return Err(ProfileIdError::TooLong(trimmed.to_string()));
64 }
65 for c in trimmed.chars() {
66 if !(c.is_ascii_alphanumeric() || c == '_' || c == '-') {
67 return Err(ProfileIdError::Invalid(trimmed.to_string()));
68 }
69 }
70 Ok(trimmed.to_ascii_lowercase())
71}
72
73pub fn user_data_dir_for(base: &Path, agent_id: &str) -> PathBuf {
85 debug_assert!(
86 sanitize_agent_id(agent_id).is_ok(),
87 "user_data_dir_for called with un-sanitised agent_id `{agent_id}`"
88 );
89 base.join("profiles").join(agent_id)
90}
91
92pub fn profile_color_argb(agent_id: &str) -> i32 {
103 let digest = Sha256::digest(agent_id.as_bytes());
104 let r = digest[0] as u32;
105 let g = digest[1] as u32;
106 let b = digest[2] as u32;
107 let argb_u32 = (0xFFu32 << 24) | (r << 16) | (g << 8) | b;
108 argb_u32 as i32
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 #[test]
118 fn sanitize_lowercases_and_returns_owned() {
119 assert_eq!(sanitize_agent_id("Ana").unwrap(), "ana");
120 }
121
122 #[test]
123 fn sanitize_accepts_underscores_and_hyphens() {
124 assert_eq!(sanitize_agent_id("agent_x-1").unwrap(), "agent_x-1");
125 }
126
127 #[test]
128 fn sanitize_accepts_max_length_64_chars() {
129 let s = "a".repeat(64);
130 assert_eq!(sanitize_agent_id(&s).unwrap(), s);
131 }
132
133 #[test]
134 fn sanitize_trims_surrounding_whitespace() {
135 assert_eq!(sanitize_agent_id(" ana ").unwrap(), "ana");
136 }
137
138 #[test]
139 fn sanitize_rejects_empty() {
140 assert_eq!(sanitize_agent_id("").unwrap_err(), ProfileIdError::Empty);
141 }
142
143 #[test]
144 fn sanitize_rejects_whitespace_only() {
145 assert_eq!(
146 sanitize_agent_id(" ").unwrap_err(),
147 ProfileIdError::Empty
148 );
149 }
150
151 #[test]
152 fn sanitize_rejects_too_long_65_chars() {
153 let s = "a".repeat(65);
154 match sanitize_agent_id(&s).unwrap_err() {
155 ProfileIdError::TooLong(got) => assert_eq!(got, s),
156 other => panic!("expected TooLong, got {other:?}"),
157 }
158 }
159
160 #[test]
161 fn sanitize_rejects_path_traversal_dot_dot() {
162 match sanitize_agent_id("..").unwrap_err() {
163 ProfileIdError::Invalid(got) => assert_eq!(got, ".."),
164 other => panic!("expected Invalid, got {other:?}"),
165 }
166 }
167
168 #[test]
169 fn sanitize_rejects_forward_slash() {
170 match sanitize_agent_id("a/b").unwrap_err() {
171 ProfileIdError::Invalid(got) => assert_eq!(got, "a/b"),
172 other => panic!("expected Invalid, got {other:?}"),
173 }
174 }
175
176 #[test]
177 fn sanitize_rejects_control_chars() {
178 match sanitize_agent_id("\x01ana").unwrap_err() {
179 ProfileIdError::Invalid(_) => {}
180 other => panic!("expected Invalid, got {other:?}"),
181 }
182 }
183
184 #[test]
185 fn sanitize_rejects_unicode_punctuation() {
186 match sanitize_agent_id("ana.es").unwrap_err() {
187 ProfileIdError::Invalid(got) => assert_eq!(got, "ana.es"),
188 other => panic!("expected Invalid, got {other:?}"),
189 }
190 }
191
192 #[test]
193 fn sanitize_rejects_non_ascii_letters() {
194 match sanitize_agent_id("ana-ñ").unwrap_err() {
199 ProfileIdError::Invalid(_) => {}
200 other => panic!("expected Invalid, got {other:?}"),
201 }
202 }
203
204 #[test]
207 fn user_data_dir_for_joins_profiles_subdir() {
208 let dir = user_data_dir_for(Path::new("/tmp/state"), "ana");
209 assert_eq!(dir, PathBuf::from("/tmp/state/profiles/ana"));
210 }
211
212 #[test]
213 fn user_data_dir_for_handles_relative_base() {
214 let dir = user_data_dir_for(Path::new("./.profile"), "x");
215 assert_eq!(dir, PathBuf::from("./.profile/profiles/x"));
216 }
217
218 #[test]
221 fn profile_color_argb_deterministic_across_calls() {
222 assert_eq!(profile_color_argb("ana"), profile_color_argb("ana"));
223 assert_eq!(profile_color_argb("juan"), profile_color_argb("juan"));
224 }
225
226 #[test]
227 fn profile_color_argb_alpha_byte_is_ff() {
228 let argb = profile_color_argb("ana") as u32;
229 let alpha = (argb >> 24) & 0xFF;
230 assert_eq!(alpha, 0xFF, "alpha must be 0xFF, got 0x{:02x}", alpha);
231 }
232
233 #[test]
234 fn profile_color_argb_distinct_for_distinct_agents_probabilistic() {
235 let agents = ["ana", "juan", "marketing", "tester", "default"];
238 let mut seen = std::collections::HashSet::new();
239 for agent in agents {
240 let argb = profile_color_argb(agent);
241 assert!(
242 seen.insert(argb),
243 "color collision for `{agent}` (0x{:08x}) within sample",
244 argb as u32
245 );
246 }
247 }
248}